icydb-core 0.252.9

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
//! Module: query::builder::numeric_projection
//! Responsibility: shared bounded numeric projection helpers used by fluent
//! terminals and structural lowering.
//! Does not own: generic arithmetic expression parsing, grouped semantics, or
//! executor routing.
//! Boundary: this models the admitted scalar arithmetic surface without
//! opening a general expression-builder API.

use crate::{
    db::{
        QueryError,
        query::{
            builder::{
                ScalarProjectionPlan, ValueProjectionExpr,
                scalar_projection::render_scalar_projection_expr_plan_label,
            },
            plan::expr::{BinaryOp, Expr, FieldId, Function, eval_builder_expr_for_value_preview},
        },
    },
    types::NumericValue,
    value::Value,
};
use icydb_diagnostic_code::QueryProjectionCode;

///
/// NumericProjectionExpr
///
/// Shared bounded numeric projection over one source field and one numeric
/// literal.
/// This stays on the narrow `field op literal` seam admitted by the shipped
/// scalar projection surfaces.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NumericProjectionExpr {
    field: String,
    expr: Expr,
}

impl NumericProjectionExpr {
    // Build one bounded field-op-literal numeric projection after validating
    // that the literal stays on the admitted numeric seam.
    fn arithmetic_value(
        field: impl Into<String>,
        op: BinaryOp,
        literal: Value,
    ) -> Result<Self, QueryError> {
        if !matches!(
            literal,
            Value::Int64(_)
                | Value::Int128(_)
                | Value::IntBig(_)
                | Value::Nat64(_)
                | Value::Nat128(_)
                | Value::NatBig(_)
                | Value::U256(_)
                | Value::Decimal(_)
                | Value::Float32(_)
                | Value::Float64(_)
                | Value::Duration(_)
                | Value::Timestamp(_)
                | Value::Date(_)
        ) {
            return Err(QueryError::unsupported_projection(
                QueryProjectionCode::NumericLiteralRequired,
            ));
        }

        let field = field.into();

        Ok(Self {
            expr: Expr::Binary {
                op,
                left: Box::new(Expr::Field(FieldId::new(field.clone()))),
                right: Box::new(Expr::Literal(literal)),
            },
            field,
        })
    }

    // Build one bounded field-op-literal numeric projection from one typed
    // numeric literal helper.
    fn arithmetic_numeric_literal(
        field: impl Into<String>,
        op: BinaryOp,
        literal: impl Into<Value> + NumericValue,
    ) -> Self {
        let literal = literal.into();
        let field = field.into();

        Self {
            expr: Expr::Binary {
                op,
                left: Box::new(Expr::Field(FieldId::new(field.clone()))),
                right: Box::new(Expr::Literal(literal)),
            },
            field,
        }
    }

    // Build one field-plus-literal numeric projection.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn add_value(
        field: impl Into<String>,
        literal: Value,
    ) -> Result<Self, QueryError> {
        Self::arithmetic_value(field, BinaryOp::Add, literal)
    }

    // Build one field-minus-literal numeric projection.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn sub_value(
        field: impl Into<String>,
        literal: Value,
    ) -> Result<Self, QueryError> {
        Self::arithmetic_value(field, BinaryOp::Sub, literal)
    }

    // Build one field-times-literal numeric projection.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn mul_value(
        field: impl Into<String>,
        literal: Value,
    ) -> Result<Self, QueryError> {
        Self::arithmetic_value(field, BinaryOp::Mul, literal)
    }

    // Build one field-divided-by-literal numeric projection.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn div_value(
        field: impl Into<String>,
        literal: Value,
    ) -> Result<Self, QueryError> {
        Self::arithmetic_value(field, BinaryOp::Div, literal)
    }

    // Build one field-plus-literal numeric projection from one typed numeric
    // literal helper.
    pub(in crate::db) fn add_numeric_literal(
        field: impl Into<String>,
        literal: impl Into<Value> + NumericValue,
    ) -> Self {
        Self::arithmetic_numeric_literal(field, BinaryOp::Add, literal)
    }

    // Build one field-minus-literal numeric projection from one typed numeric
    // literal helper.
    pub(in crate::db) fn sub_numeric_literal(
        field: impl Into<String>,
        literal: impl Into<Value> + NumericValue,
    ) -> Self {
        Self::arithmetic_numeric_literal(field, BinaryOp::Sub, literal)
    }

    // Build one field-times-literal numeric projection from one typed numeric
    // literal helper.
    pub(in crate::db) fn mul_numeric_literal(
        field: impl Into<String>,
        literal: impl Into<Value> + NumericValue,
    ) -> Self {
        Self::arithmetic_numeric_literal(field, BinaryOp::Mul, literal)
    }

    // Build one field-divided-by-literal numeric projection from one typed
    // numeric literal helper.
    pub(in crate::db) fn div_numeric_literal(
        field: impl Into<String>,
        literal: impl Into<Value> + NumericValue,
    ) -> Self {
        Self::arithmetic_numeric_literal(field, BinaryOp::Div, literal)
    }

    /// Borrow the canonical planner expression carried by this helper.
    #[must_use]
    pub(in crate::db) const fn expr(&self) -> &Expr {
        &self.expr
    }

    // Build one rounded projection over either a plain field or one existing
    // bounded numeric expression rooted in the same source field.
    pub(in crate::db) fn round_with_scale(&self, scale: u32) -> RoundProjectionExpr {
        RoundProjectionExpr::with_valid_scale(self.field.clone(), self.expr.clone(), scale)
    }
}

impl super::scalar_projection::private::Sealed for NumericProjectionExpr {}

impl ValueProjectionExpr for NumericProjectionExpr {
    fn field(&self) -> &str {
        self.field.as_str()
    }

    fn projection_plan(&self) -> ScalarProjectionPlan {
        ScalarProjectionPlan::new(self.expr.clone())
    }

    fn projection_label(&self) -> String {
        render_scalar_projection_expr_plan_label(&self.expr)
    }

    fn apply_value(&self, value: Value) -> Result<Value, QueryError> {
        eval_builder_expr_for_value_preview(&self.expr, self.field.as_str(), &value)
    }
}

///
/// RoundProjectionExpr
///
/// Shared bounded numeric rounding projection over one source field and one
/// canonical scalar numeric expression.
/// This keeps `ROUND` on the scalar projection seam without opening a generic
/// function-builder surface.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoundProjectionExpr {
    field: String,
    expr: Expr,
}

impl RoundProjectionExpr {
    // Build one bounded `ROUND(expr, scale)` projection after validating that
    // `scale` stays on the admitted non-negative integer seam.
    #[cfg(test)]
    pub(in crate::db) fn new(
        field: impl Into<String>,
        inner: Expr,
        scale: Value,
    ) -> Result<Self, QueryError> {
        match scale {
            Value::Int64(value) if value < 0 => {
                return Err(QueryError::unsupported_projection(
                    QueryProjectionCode::NumericScaleArguments,
                ));
            }
            Value::Int64(_) | Value::Nat64(_) => {}
            _ => {
                return Err(QueryError::unsupported_projection(
                    QueryProjectionCode::NumericScaleArguments,
                ));
            }
        }

        Ok(Self {
            field: field.into(),
            expr: Expr::FunctionCall {
                function: Function::Round,
                args: vec![inner, Expr::Literal(scale)],
            },
        })
    }

    // Build one rounded field projection from the intrinsically valid `u32`
    // public scale domain.
    pub(in crate::db) fn field(field: impl Into<String>, scale: u32) -> Self {
        let field = field.into();

        Self::with_valid_scale(field.clone(), Expr::Field(FieldId::new(field)), scale)
    }

    fn with_valid_scale(field: String, inner: Expr, scale: u32) -> Self {
        Self {
            field,
            expr: Expr::FunctionCall {
                function: Function::Round,
                args: vec![inner, Expr::Literal(Value::Nat64(u64::from(scale)))],
            },
        }
    }

    /// Borrow the canonical planner expression carried by this helper.
    #[must_use]
    pub(in crate::db) const fn expr(&self) -> &Expr {
        &self.expr
    }
}

impl super::scalar_projection::private::Sealed for RoundProjectionExpr {}

impl ValueProjectionExpr for RoundProjectionExpr {
    fn field(&self) -> &str {
        self.field.as_str()
    }

    fn projection_plan(&self) -> ScalarProjectionPlan {
        ScalarProjectionPlan::new(self.expr.clone())
    }

    fn projection_label(&self) -> String {
        render_scalar_projection_expr_plan_label(&self.expr)
    }

    fn apply_value(&self, value: Value) -> Result<Value, QueryError> {
        eval_builder_expr_for_value_preview(&self.expr, self.field.as_str(), &value)
    }
}

/// Build `field + literal`.
#[must_use]
pub fn add(
    field: impl AsRef<str>,
    literal: impl Into<Value> + NumericValue,
) -> NumericProjectionExpr {
    NumericProjectionExpr::add_numeric_literal(field.as_ref().to_string(), literal)
}

/// Build `field - literal`.
#[must_use]
pub fn sub(
    field: impl AsRef<str>,
    literal: impl Into<Value> + NumericValue,
) -> NumericProjectionExpr {
    NumericProjectionExpr::sub_numeric_literal(field.as_ref().to_string(), literal)
}

/// Build `field * literal`.
#[must_use]
pub fn mul(
    field: impl AsRef<str>,
    literal: impl Into<Value> + NumericValue,
) -> NumericProjectionExpr {
    NumericProjectionExpr::mul_numeric_literal(field.as_ref().to_string(), literal)
}

/// Build `field / literal`.
#[must_use]
pub fn div(
    field: impl AsRef<str>,
    literal: impl Into<Value> + NumericValue,
) -> NumericProjectionExpr {
    NumericProjectionExpr::div_numeric_literal(field.as_ref().to_string(), literal)
}

/// Build `ROUND(field, scale)`.
///
pub fn round(field: impl AsRef<str>, scale: u32) -> RoundProjectionExpr {
    RoundProjectionExpr::field(field.as_ref().to_string(), scale)
}

/// Build `ROUND(expr, scale)` for one existing bounded numeric projection.
///
#[must_use]
pub fn round_expr(projection: &NumericProjectionExpr, scale: u32) -> RoundProjectionExpr {
    projection.round_with_scale(scale)
}

#[cfg(test)]
mod tests {
    use super::{NumericProjectionExpr, RoundProjectionExpr, add};
    use crate::{
        db::{
            QueryError,
            query::plan::expr::{BinaryOp, Expr, FieldId},
        },
        types::U256,
        value::Value,
    };
    use icydb_diagnostic_code::{DiagnosticCode, DiagnosticDetail, QueryProjectionCode};

    fn assert_query_projection_error(err: QueryError, reason: QueryProjectionCode) {
        let diagnostic = err.diagnostic();

        assert_eq!(
            diagnostic.code(),
            DiagnosticCode::QueryUnsupportedProjection
        );
        assert_eq!(
            diagnostic.detail(),
            Some(&DiagnosticDetail::QueryProjection { reason }),
        );
    }

    #[test]
    fn numeric_projection_rejects_non_numeric_literal_with_compact_projection_code() {
        let err = NumericProjectionExpr::arithmetic_value("age", BinaryOp::Add, Value::Bool(true))
            .expect_err("non-numeric projection literal should fail closed");

        assert_query_projection_error(err, QueryProjectionCode::NumericLiteralRequired);
    }

    #[test]
    fn fluent_numeric_projection_accepts_constructed_u256_literals() {
        let projection = add("amount", U256::from(3_u64));

        assert_eq!(
            projection.expr(),
            &Expr::Binary {
                op: BinaryOp::Add,
                left: Box::new(Expr::Field(FieldId::new("amount"))),
                right: Box::new(Expr::Literal(Value::U256(U256::from(3_u64)))),
            },
        );
    }

    #[test]
    fn round_projection_rejects_negative_scale_with_compact_projection_code() {
        let err =
            RoundProjectionExpr::new("age", Expr::Field(FieldId::new("age")), Value::Int64(-1))
                .expect_err("negative ROUND scale should fail closed");

        assert_query_projection_error(err, QueryProjectionCode::NumericScaleArguments);
    }

    #[test]
    fn round_projection_rejects_non_integer_scale_with_compact_projection_code() {
        let err = RoundProjectionExpr::new(
            "age",
            Expr::Field(FieldId::new("age")),
            Value::Text("invalid".to_string()),
        )
        .expect_err("non-integer ROUND scale should fail closed");

        assert_query_projection_error(err, QueryProjectionCode::NumericScaleArguments);
    }
}