icydb 0.204.2

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
//! 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.

mod paging;
mod partial_window;

use crate::{
    db::{
        ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
        query::{AggregateExpr, CompareOp, ExplainPlan, FilterExpr, QueryTracePlan},
        response::{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;

pub use partial_window::PartialWindowLoadQuery;

///
/// 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> {
    /// Execute this query with diagnostics attribution.
    #[cfg(feature = "diagnostics")]
    #[doc(hidden)]
    pub fn execute_with_attribution(
        &self,
    ) -> Result<(QueryResponse<E>, crate::db::QueryExecutionAttribution), Error>
    where
        E: Entity,
    {
        let (result, attribution) = self.inner.execute_with_attribution()?;

        Ok((QueryResponse::from_core(result), attribution))
    }

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

    impl_session_query_shape_methods!();

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

    /// Return a deliberately partial row window.
    ///
    /// 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 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 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
    }
}