icydb 0.199.0

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Module: db::session::load
//!
//! Responsibility: public session and fluent query facade.
//! Does not own: core execution, storage engines, or planner semantics.
//! Boundary: wraps core sessions with stable generated-code and application APIs.

use crate::{
    db::{
        AdminBatchRequest, ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
        query::{
            AggregateExpr, CompareOp, CompiledQuery, ExplainPlan, FilterExpr, PlannedQuery, Query,
            QueryTracePlan,
        },
        response::{PagedResponse, QueryResponse, Response},
        session::macros::{impl_session_materialization_methods, impl_session_query_shape_methods},
    },
    error::Error,
    traits::{Entity, SingletonEntity},
    types::{Decimal, Id},
    value::InputValue,
};

use icydb_core as core;

///
/// FluentLoadQuery
///
/// Session-bound fluent wrapper for typed load queries.
/// This facade keeps query shaping and execution on the public `icydb`
/// surface while delegating planning and execution to `icydb-core`.
///

pub struct FluentLoadQuery<'a, E: Entity> {
    pub(crate) inner: core::db::FluentLoadQuery<'a, E>,
}

impl<'a, E: Entity> FluentLoadQuery<'a, E> {
    // ------------------------------------------------------------------
    // Intent inspection
    // ------------------------------------------------------------------

    #[doc(hidden)]
    #[must_use]
    pub const fn query(&self) -> &Query<E> {
        self.inner.query()
    }

    // ------------------------------------------------------------------
    // Primary-key access (semantic)
    // ------------------------------------------------------------------

    impl_session_query_shape_methods!();

    // ------------------------------------------------------------------
    // Query refinement
    // ------------------------------------------------------------------

    /// Return a deliberately partial row window.
    ///
    /// This is the hard-cut replacement for raw public read `.limit(...)` on
    /// load queries. Use it only when the endpoint contract is "the first N
    /// rows under this order." Use `page(...)` for public pages,
    /// `collect_complete()` for complete small sets, and exact aggregate
    /// helpers for semantic aggregates.
    #[must_use]
    pub fn partial_window(self, limit: u32) -> PartialWindowLoadQuery<'a, E> {
        PartialWindowLoadQuery {
            inner: self.inner.partial_window(limit),
        }
    }

    /// Mark this fluent read as trusted and bypass the default bounded read gate.
    ///
    /// Use this only for controller/admin maintenance code that has its own
    /// authorization and resource policy. Application-facing reads should stay
    /// on the normal bounded execution path through `execute`, `execute_rows`,
    /// `page(...)`, or terminal helpers.
    #[must_use]
    pub fn trusted_read_unchecked(mut self) -> Self {
        self.inner = self.inner.trusted_read_unchecked();
        self
    }

    /// Add one grouped key field.
    pub fn group_by(mut self, field: impl AsRef<str>) -> Result<Self, Error> {
        self.inner = self.inner.group_by(field)?;
        Ok(self)
    }

    /// Add one grouped aggregate terminal.
    #[must_use]
    pub fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
        self.inner = self.inner.aggregate(aggregate);
        self
    }

    /// Override grouped hard limits for grouped execution budget enforcement.
    #[must_use]
    pub fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
        self.inner = self.inner.grouped_limits(max_groups, max_group_bytes);
        self
    }

    /// Add one grouped HAVING compare clause over one grouped key field.
    pub fn having_group(
        mut self,
        field: impl AsRef<str>,
        op: CompareOp,
        value: InputValue,
    ) -> Result<Self, Error> {
        self.inner = self.inner.having_group(field, op, value)?;
        Ok(self)
    }

    /// Add one grouped HAVING compare clause over one grouped aggregate output.
    pub fn having_aggregate(
        mut self,
        aggregate_index: usize,
        op: CompareOp,
        value: InputValue,
    ) -> Result<Self, Error> {
        self.inner = self.inner.having_aggregate(aggregate_index, op, value)?;
        Ok(self)
    }

    // ------------------------------------------------------------------
    // Execution primitives
    // ------------------------------------------------------------------
    impl_session_materialization_methods!();

    /// Execute the first typed cursor page with the requested page size.
    ///
    /// Cursor pagination requires explicit ordering and disallows a prior
    /// `partial_window(...)`. IcyDB clamps the requested page size to the
    /// engine-owned public page cap.
    /// Cursor pagination runs through the default bounded read-admission lane.
    /// Continuation is best-effort and forward-only over live state:
    /// deterministic per request under canonical ordering, with no
    /// snapshot/version pinned across requests.
    pub fn page(self, limit: u32) -> Result<PagedResponse<E>, Error> {
        Ok(Self::paged_response_from_execution(self.inner.page(limit)?))
    }

    /// Execute the next typed cursor page from a previous continuation cursor.
    ///
    /// This is the continuation counterpart to `page(limit)`. The cursor is an
    /// opaque token returned by the previous page response.
    pub fn next_page(
        self,
        limit: u32,
        cursor: impl Into<String>,
    ) -> Result<PagedResponse<E>, Error> {
        Ok(Self::paged_response_from_execution(
            self.inner.next_page(limit, cursor)?,
        ))
    }

    /// Execute a trusted/admin cursor batch with an engine-owned batch size.
    ///
    /// This terminal is only for reads that have already opted into
    /// `trusted_read_unchecked()`. Application-facing list endpoints should
    /// use `page(limit)` / `next_page(limit, cursor)`.
    pub fn admin_batch(self, request: AdminBatchRequest) -> Result<PagedResponse<E>, Error>
    where
        E: Entity,
    {
        Ok(Self::paged_response_from_execution(
            self.inner.admin_batch(request)?,
        ))
    }

    fn paged_response_from_execution(execution: core::db::PagedLoadExecution<E>) -> PagedResponse<E>
    where
        E: Entity,
    {
        let read_intent = execution.read_intent();
        let (response, continuation_cursor) = execution.into_response_and_cursor();
        let next_cursor = continuation_cursor.as_deref().map(core::db::encode_cursor);

        PagedResponse::new(response.entities(), next_cursor, read_intent)
    }

    /// Execute as a scalar row load through the default bounded read-admission
    /// gate.
    ///
    /// Grouped queries return grouped rows through `execute().into_grouped()`;
    /// this method is for scalar entity-row reads.
    pub fn execute_rows(&self) -> Result<Response<E>, Error>
    where
        E: Entity,
    {
        Ok(Response::from_core(self.inner.execute_rows()?))
    }

    /// Return the stable plan hash for this query.
    pub fn plan_hash_hex(&self) -> Result<String, Error> {
        Ok(self.inner.plan_hash_hex()?)
    }

    /// Build one trace payload without executing the query.
    pub fn trace(&self) -> Result<QueryTracePlan, Error> {
        Ok(self.inner.trace()?)
    }

    /// Build the validated logical plan without compiling execution details.
    pub fn planned(&self) -> Result<PlannedQuery<E>, Error> {
        Ok(self.inner.planned()?)
    }

    /// Build the compiled executable plan for this query.
    pub fn plan(&self) -> Result<CompiledQuery<E>, Error> {
        Ok(self.inner.plan()?)
    }

    /// Build logical explain metadata for the current query.
    pub fn explain(&self) -> Result<ExplainPlan, Error> {
        Ok(self.inner.explain()?)
    }

    // ------------------------------------------------------------------
    // Aggregation helpers
    // ------------------------------------------------------------------

    /// Return whether at least one matching row exists.
    pub fn exists(&self) -> Result<bool, Error>
    where
        E: Entity,
    {
        Ok(self.inner.exists()?)
    }

    /// Return whether at least one matching row exists with terminal
    /// diagnostics attribution.
    #[cfg(feature = "diagnostics")]
    #[doc(hidden)]
    pub fn exists_with_attribution(
        &self,
    ) -> Result<(bool, crate::db::FluentTerminalExecutionAttribution), Error>
    where
        E: Entity,
    {
        Ok(self.inner.exists_with_attribution()?)
    }

    /// Explain scalar `exists()` routing without executing the terminal.
    pub fn explain_exists(&self) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_exists()?)
    }

    /// Return whether no matching row exists.
    pub fn not_exists(&self) -> Result<bool, Error>
    where
        E: Entity,
    {
        Ok(self.inner.not_exists()?)
    }

    /// Return all matching rows if the complete result fits in the default
    /// public-read small-set cap.
    ///
    /// This semantic terminal rejects a prior `partial_window(...)`; use
    /// `execute_rows()` when returning a partial row window is the endpoint
    /// contract.
    pub fn collect_complete(&self) -> Result<Vec<E>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.collect_complete()?)
    }

    /// Return all matching rows with query diagnostics attribution if the
    /// complete result fits in the default public-read small-set cap.
    #[cfg(feature = "diagnostics")]
    #[doc(hidden)]
    pub fn collect_complete_with_attribution(
        &self,
    ) -> Result<(Vec<E>, crate::db::QueryExecutionAttribution), Error>
    where
        E: Entity,
    {
        Ok(self.inner.collect_complete_with_attribution()?)
    }

    /// Return the exact number of matching rows.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact count must not mean "count the first N rows."
    pub fn count_exact(&self) -> Result<u32, Error>
    where
        E: Entity,
    {
        Ok(self.inner.count_exact()?)
    }

    /// Explain exact count routing without executing the terminal.
    pub fn explain_count_exact(&self) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_count_exact()?)
    }

    /// Return the exact row count with terminal diagnostics attribution.
    #[cfg(feature = "diagnostics")]
    #[doc(hidden)]
    pub fn count_exact_with_attribution(
        &self,
    ) -> Result<(u32, crate::db::FluentTerminalExecutionAttribution), Error>
    where
        E: Entity,
    {
        Ok(self.inner.count_exact_with_attribution()?)
    }

    /// Explain scalar `not_exists()` routing without executing the terminal.
    pub fn explain_not_exists(&self) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_not_exists()?)
    }

    /// Explain the execution shape without executing the query.
    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution()?)
    }

    /// Render execution explain output as a compact text tree.
    pub fn explain_execution_text(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_text()?)
    }

    /// Render execution explain output as canonical JSON.
    pub fn explain_execution_json(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_json()?)
    }

    /// Render execution explain output as a verbose text tree.
    pub fn explain_execution_verbose(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_verbose()?)
    }

    /// Return the exact minimum identifier under deterministic response ordering.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact minimum must not mean "minimum over the first N rows."
    pub fn min_id_exact(&self) -> Result<Option<Id<E>>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.min_id_exact()?)
    }

    /// Explain exact `min_id_exact()` routing without executing the terminal.
    pub fn explain_min_id_exact(&self) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_min_id_exact()?)
    }

    /// Return the identifier with the exact minimum `field` value.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact minimum must not mean "minimum over the first N rows."
    pub fn min_exact_by(&self, field: impl AsRef<str>) -> Result<Option<Id<E>>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.min_exact_by(field)?)
    }

    /// Explain exact `min_exact_by(field)` routing without executing the terminal.
    pub fn explain_min_exact_by(
        &self,
        field: impl AsRef<str>,
    ) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_min_exact_by(field)?)
    }

    /// Return the exact maximum identifier under deterministic response ordering.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact maximum must not mean "maximum over the first N rows."
    pub fn max_id_exact(&self) -> Result<Option<Id<E>>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.max_id_exact()?)
    }

    /// Explain exact `max_id_exact()` routing without executing the terminal.
    pub fn explain_max_id_exact(&self) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_max_id_exact()?)
    }

    /// Return the identifier with the exact maximum `field` value.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact maximum must not mean "maximum over the first N rows."
    pub fn max_exact_by(&self, field: impl AsRef<str>) -> Result<Option<Id<E>>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.max_exact_by(field)?)
    }

    /// Explain exact `max_exact_by(field)` routing without executing the terminal.
    pub fn explain_max_exact_by(
        &self,
        field: impl AsRef<str>,
    ) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_max_exact_by(field)?)
    }

    /// Return the exact sum of `field` over matching rows.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact sum must not mean "sum the first N rows."
    pub fn sum_exact(&self, field: impl AsRef<str>) -> Result<Option<Decimal>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.sum_exact(field)?)
    }

    /// Explain exact sum routing without executing the terminal.
    pub fn explain_sum_exact(
        &self,
        field: impl AsRef<str>,
    ) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_sum_exact(field)?)
    }

    /// Return the exact average of `field` over matching rows.
    ///
    /// This semantic aggregate rejects a prior partial row window because an
    /// exact average must not mean "average the first N rows."
    pub fn avg_exact(&self, field: impl AsRef<str>) -> Result<Option<Decimal>, Error>
    where
        E: Entity,
    {
        Ok(self.inner.avg_exact(field)?)
    }

    /// Explain exact `avg_exact(field)` routing without executing the terminal.
    pub fn explain_avg_exact(
        &self,
        field: impl AsRef<str>,
    ) -> Result<ExplainAggregateTerminalPlan, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_avg_exact(field)?)
    }

    /// Materialize zero or one entity, failing when more than one row matches.
    pub fn try_one(&self) -> Result<Option<E>, Error>
    where
        E: Entity,
    {
        icydb_core::db::ResponseCardinalityExt::try_entity(self.inner.execute_rows()?)
            .map_err(Into::into)
    }
}

impl<E: Entity + SingletonEntity> FluentLoadQuery<'_, E> {
    /// Load the singleton entity.
    #[must_use]
    pub fn singleton(mut self) -> Self
    where
        E::Key: Default,
    {
        self.inner = self.inner.singleton();
        self
    }
}

///
/// PartialWindowLoadQuery
///
/// Facade wrapper for deliberately partial row-window reads.
/// It exposes materialization and diagnostics, but not semantic terminals such
/// as paging, complete collection, existence, or exact aggregates.
///

pub struct PartialWindowLoadQuery<'a, E: Entity> {
    inner: core::db::PartialWindowLoadQuery<'a, E>,
}

impl<E: Entity> PartialWindowLoadQuery<'_, E> {
    #[doc(hidden)]
    #[must_use]
    pub const fn query(&self) -> &Query<E> {
        self.inner.query()
    }

    /// Mark this partial window as trusted and bypass the default bounded read
    /// gate.
    ///
    /// Use this only for controller/admin maintenance code that owns its
    /// authorization and resource policy. Caller-facing list endpoints should
    /// use `page(limit)` / `next_page(limit, cursor)` instead of trusted
    /// partial windows.
    #[must_use]
    pub fn trusted_read_unchecked(mut self) -> Self {
        self.inner = self.inner.trusted_read_unchecked();
        self
    }

    /// Execute this deliberately partial row window.
    ///
    /// Scalar queries return `QueryResponse::Rows`; grouped queries return
    /// `QueryResponse::Grouped`. Use `into_rows()` or `into_grouped()` when
    /// the endpoint expects one concrete shape.
    pub fn execute(&self) -> Result<QueryResponse<E>, Error>
    where
        E: Entity,
    {
        Ok(QueryResponse::from_core(self.inner.execute()?))
    }

    /// Execute this deliberately partial row window as scalar entity rows.
    pub fn execute_rows(&self) -> Result<Response<E>, Error>
    where
        E: Entity,
    {
        Ok(Response::from_core(self.inner.execute_rows()?))
    }

    /// Return the stable plan hash for this partial-window query.
    pub fn plan_hash_hex(&self) -> Result<String, Error> {
        Ok(self.inner.plan_hash_hex()?)
    }

    /// Build one trace payload without executing the partial-window query.
    pub fn trace(&self) -> Result<QueryTracePlan, Error> {
        Ok(self.inner.trace()?)
    }

    /// Build the validated logical plan without compiling execution details.
    pub fn planned(&self) -> Result<PlannedQuery<E>, Error> {
        Ok(self.inner.planned()?)
    }

    /// Build the compiled executable plan for this partial-window query.
    pub fn plan(&self) -> Result<CompiledQuery<E>, Error> {
        Ok(self.inner.plan()?)
    }

    /// Build logical explain metadata for the current partial-window query.
    pub fn explain(&self) -> Result<ExplainPlan, Error> {
        Ok(self.inner.explain()?)
    }

    /// Explain the execution shape without executing the partial-window query.
    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution()?)
    }

    /// Render execution explain output as a compact text tree.
    pub fn explain_execution_text(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_text()?)
    }

    /// Render execution explain output as canonical JSON.
    pub fn explain_execution_json(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_json()?)
    }

    /// Render execution explain output as a verbose text tree.
    pub fn explain_execution_verbose(&self) -> Result<String, Error>
    where
        E: Entity,
    {
        Ok(self.inner.explain_execution_verbose()?)
    }
}