icydb-core 0.145.5

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
use crate::{
    db::{
        numeric::{
            NumericArithmeticOp, apply_numeric_arithmetic_checked, coerce_numeric_decimal,
            compare_numeric_eq, compare_numeric_or_strict_order,
        },
        query::plan::expr::{
            BinaryOp, CaseWhenArm, Expr, Function, ScalarEvalFunctionShape, UnaryOp,
            collapse_true_only_boolean_admission,
        },
    },
    value::Value,
};
use std::cmp::Ordering;

///
/// NullableTextArg
///
/// Bounded decode result for one literal-owned text argument used by planner
/// preview evaluation.
///
/// This keeps `NULL` distinct from unsupported non-text values without
/// relying on nested `Option<Option<_>>` plumbing.
///

enum NullableTextArg<'a> {
    Null,
    Text(&'a str),
}

///
/// NullableIntegerArg
///
/// Bounded decode result for one literal-owned integer argument used by
/// planner preview evaluation.
///
/// This keeps `NULL` distinct from unsupported non-integer values while
/// preserving the existing `Uint` saturation rule for helper functions.
///

enum NullableIntegerArg {
    Null,
    Integer(i64),
}

/// Evaluate one planner-owned expression only when every reachable subtree is
/// literal-owned and can therefore be folded without depending on runtime
/// field reads or executor projection machinery.
///
/// Lowering uses this bounded preview to collapse wrapped constant helper
/// expressions inside scalar `WHERE` before the later planner normalization
/// passes try to recover predicate-shaped fast paths.
pub(in crate::db) fn eval_literal_only_expr_value(expr: &Expr) -> Option<Value> {
    match expr {
        Expr::Literal(value) => Some(value.clone()),
        Expr::Field(_) | Expr::FieldPath(_) | Expr::Aggregate(_) => None,
        Expr::FunctionCall { function, args } => eval_literal_only_function_call(*function, args),
        Expr::Case {
            when_then_arms,
            else_expr,
        } => eval_literal_only_case_expr(when_then_arms, else_expr.as_ref()),
        Expr::Binary { op, left, right } => {
            let left = eval_literal_only_expr_value(left.as_ref())?;
            let right = eval_literal_only_expr_value(right.as_ref())?;

            eval_literal_only_binary_expr(*op, &left, &right)
        }
        Expr::Unary { op, expr } => {
            let value = eval_literal_only_expr_value(expr.as_ref())?;

            eval_literal_only_unary_expr(*op, &value)
        }
        #[cfg(test)]
        Expr::Alias { expr, .. } => eval_literal_only_expr_value(expr.as_ref()),
    }
}

// Evaluate one literal-only CASE expression through the shared TRUE-only
// boolean admission boundary used elsewhere in planner-owned boolean semantics.
fn eval_literal_only_case_expr(when_then_arms: &[CaseWhenArm], else_expr: &Expr) -> Option<Value> {
    for arm in when_then_arms {
        let condition = eval_literal_only_expr_value(arm.condition())?;
        if collapse_true_only_boolean_admission(condition, |_| ()).ok()? {
            return eval_literal_only_expr_value(arm.result());
        }
    }

    eval_literal_only_expr_value(else_expr)
}

// Evaluate one literal-only function call through the bounded planner helper
// surface currently exercised by scalar WHERE constant-folding.
fn eval_literal_only_function_call(function: Function, args: &[Expr]) -> Option<Value> {
    let evaluated_args = args
        .iter()
        .map(eval_literal_only_expr_value)
        .collect::<Option<Vec<_>>>()?;

    match function.scalar_eval_shape() {
        ScalarEvalFunctionShape::NullTest => {
            eval_null_test_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::NonExecutableProjection => None,
        ScalarEvalFunctionShape::UnaryText => {
            eval_unary_text_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::DynamicCoalesce => {
            eval_coalesce_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::DynamicNullIf => {
            eval_nullif_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::UnaryNumeric => {
            eval_unary_numeric_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::BinaryNumeric => {
            eval_binary_numeric_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::LeftRightText => {
            eval_left_right_text_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::TextPredicate => {
            eval_text_predicate_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::PositionText => {
            eval_position_text_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::ReplaceText => {
            eval_replace_text_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::SubstringText => {
            eval_substring_text_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::NumericScale => {
            eval_numeric_scale_function_call(function, &evaluated_args)
        }
        ScalarEvalFunctionShape::OctetLength => eval_octet_length_function_call(&evaluated_args),
    }
}

// Evaluate one literal-only unary expression without touching executor-owned
// projection error taxonomy or runtime readers.
fn eval_literal_only_unary_expr(op: UnaryOp, value: &Value) -> Option<Value> {
    if matches!(value, Value::Null) {
        return Some(Value::Null);
    }

    match op {
        UnaryOp::Not => match value {
            Value::Bool(inner) => Some(Value::Bool(!inner)),
            _ => None,
        },
    }
}

// Evaluate one literal-only binary expression through planner-owned numeric and
// value comparison helpers.
fn eval_literal_only_binary_expr(op: BinaryOp, left: &Value, right: &Value) -> Option<Value> {
    match op {
        BinaryOp::Or | BinaryOp::And => eval_boolean_binary_expr(op, left, right),
        BinaryOp::Eq
        | BinaryOp::Ne
        | BinaryOp::Lt
        | BinaryOp::Lte
        | BinaryOp::Gt
        | BinaryOp::Gte => eval_compare_binary_expr(op, left, right),
        BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div => {
            if matches!(left, Value::Null) || matches!(right, Value::Null) {
                return Some(Value::Null);
            }

            let arithmetic_op = match op {
                BinaryOp::Add => NumericArithmeticOp::Add,
                BinaryOp::Sub => NumericArithmeticOp::Sub,
                BinaryOp::Mul => NumericArithmeticOp::Mul,
                BinaryOp::Div => NumericArithmeticOp::Div,
                _ => unreachable!("arithmetic dispatch drifted"),
            };

            apply_numeric_arithmetic_checked(arithmetic_op, left, right)
                .ok()
                .flatten()
                .map(Value::Decimal)
        }
    }
}

// Evaluate one literal-only boolean AND/OR using the shared three-valued
// truth table used by scalar projection evaluation.
fn eval_boolean_binary_expr(op: BinaryOp, left: &Value, right: &Value) -> Option<Value> {
    match op {
        BinaryOp::And => match (left, right) {
            (Value::Bool(false), _) | (_, Value::Bool(false)) => Some(Value::Bool(false)),
            (Value::Bool(true), Value::Bool(true)) => Some(Value::Bool(true)),
            (Value::Bool(true) | Value::Null, Value::Null) | (Value::Null, Value::Bool(true)) => {
                Some(Value::Null)
            }
            _ => None,
        },
        BinaryOp::Or => match (left, right) {
            (Value::Bool(true), _) | (_, Value::Bool(true)) => Some(Value::Bool(true)),
            (Value::Bool(false), Value::Bool(false)) => Some(Value::Bool(false)),
            (Value::Bool(false) | Value::Null, Value::Null) | (Value::Null, Value::Bool(false)) => {
                Some(Value::Null)
            }
            _ => None,
        },
        _ => unreachable!("boolean binary dispatch drifted"),
    }
}

// Evaluate one literal-only compare using the same numeric-widen versus strict
// fallback rule already shared elsewhere in planner/runtime comparison helpers.
fn eval_compare_binary_expr(op: BinaryOp, left: &Value, right: &Value) -> Option<Value> {
    if matches!(left, Value::Null) || matches!(right, Value::Null) {
        return Some(Value::Null);
    }

    let numeric_widen_enabled =
        left.supports_numeric_coercion() || right.supports_numeric_coercion();
    let result = match op {
        BinaryOp::Eq => {
            if let Some(equal) = compare_numeric_eq(left, right) {
                equal
            } else if !numeric_widen_enabled {
                left == right
            } else {
                return None;
            }
        }
        BinaryOp::Ne => {
            if let Some(equal) = compare_numeric_eq(left, right) {
                !equal
            } else if !numeric_widen_enabled {
                left != right
            } else {
                return None;
            }
        }
        BinaryOp::Lt => compare_numeric_or_strict_order(left, right).map(Ordering::is_lt)?,
        BinaryOp::Lte => compare_numeric_or_strict_order(left, right).map(Ordering::is_le)?,
        BinaryOp::Gt => compare_numeric_or_strict_order(left, right).map(Ordering::is_gt)?,
        BinaryOp::Gte => compare_numeric_or_strict_order(left, right).map(Ordering::is_ge)?,
        _ => unreachable!("compare dispatch drifted"),
    };

    Some(Value::Bool(result))
}

// Evaluate one NULL-test function when its only input is already literal-owned.
fn eval_null_test_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [value] = args else {
        return None;
    };

    Some(
        function
            .boolean_null_test_kind()
            .expect("null-test preview dispatch must keep one null-test kind")
            .eval_value(value),
    )
}

// Evaluate one text wrapper over a literal-owned text input.
fn eval_unary_text_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input] = args else {
        return None;
    };

    match input {
        Value::Null => Some(Value::Null),
        Value::Text(text) => Some(
            function
                .unary_text_function_kind()
                .expect("unary-text preview dispatch must keep one unary-text kind")
                .eval_text(text.as_str()),
        ),
        _ => None,
    }
}

// Evaluate one numeric wrapper over a literal-owned numeric input.
fn eval_unary_numeric_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input] = args else {
        return None;
    };

    match input {
        Value::Null => Some(Value::Null),
        value => {
            let decimal = coerce_numeric_decimal(value)?;

            function
                .unary_numeric_function_kind()
                .expect("unary-numeric preview dispatch must keep one unary-numeric kind")
                .eval_decimal(decimal)
                .ok()
        }
    }
}

// Evaluate one byte-length wrapper over a literal-owned text or blob input.
fn eval_octet_length_function_call(args: &[Value]) -> Option<Value> {
    let [input] = args else {
        return None;
    };

    match input {
        Value::Null => Some(Value::Null),
        Value::Text(text) => Some(Value::Uint(u64::try_from(text.len()).unwrap_or(u64::MAX))),
        Value::Blob(bytes) => Some(Value::Uint(u64::try_from(bytes.len()).unwrap_or(u64::MAX))),
        _ => None,
    }
}

// Evaluate one binary numeric wrapper over literal-owned numeric inputs.
fn eval_binary_numeric_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [left, right] = args else {
        return None;
    };

    match (left, right) {
        (Value::Null, _) | (_, Value::Null) => Some(Value::Null),
        (left, right) => {
            let left = coerce_numeric_decimal(left)?;
            let right = coerce_numeric_decimal(right)?;

            function
                .binary_numeric_function_kind()
                .expect("binary-numeric preview dispatch must keep one binary-numeric kind")
                .eval_decimal(left, right)
                .ok()
        }
    }
}

// Evaluate one literal-only COALESCE helper.
fn eval_coalesce_function_call(function: Function, args: &[Value]) -> Option<Value> {
    if args.len() < 2 {
        return None;
    }

    Some(function.eval_coalesce_values(args))
}

// Evaluate one literal-only NULLIF helper through the same compare semantics as
// the preview binary compare path.
fn eval_nullif_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [left, right] = args else {
        return None;
    };

    match eval_compare_binary_expr(BinaryOp::Eq, left, right)? {
        Value::Bool(true) => Some(function.eval_nullif_values(left, right, true)),
        Value::Bool(false) => Some(function.eval_nullif_values(left, right, false)),
        _ => None,
    }
}

// Evaluate one literal-only LEFT/RIGHT helper with the same integer coercion
// boundary already used by runtime projection evaluation.
fn eval_left_right_text_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input, length] = args else {
        return None;
    };
    let length = integer_value(length)?;

    match (input, length) {
        (Value::Null, _) | (_, NullableIntegerArg::Null) => Some(Value::Null),
        (Value::Text(text), NullableIntegerArg::Integer(length)) => Some(
            function
                .left_right_text_function_kind()
                .expect("left/right preview dispatch must keep one left/right kind")
                .eval_text(text.as_str(), length),
        ),
        _ => None,
    }
}

// Evaluate one literal-only text predicate helper.
fn eval_text_predicate_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input, literal] = args else {
        return None;
    };
    let literal = text_value(literal)?;

    match (input, literal) {
        (Value::Null, _) | (_, NullableTextArg::Null) => Some(Value::Null),
        (Value::Text(text), NullableTextArg::Text(needle)) => Some(
            function
                .boolean_text_predicate_kind()
                .expect("text-predicate preview dispatch must keep one text-predicate kind")
                .eval_text(text, needle),
        ),
        _ => None,
    }
}

// Evaluate one literal-only POSITION helper.
fn eval_position_text_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [needle, input] = args else {
        return None;
    };
    let needle = text_value(needle)?;

    match (needle, input) {
        (_, Value::Null) | (NullableTextArg::Null, _) => Some(Value::Null),
        (NullableTextArg::Text(needle), Value::Text(text)) => {
            Some(function.eval_position_text(text, needle))
        }
        _ => None,
    }
}

// Evaluate one literal-only REPLACE helper.
fn eval_replace_text_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input, from, to] = args else {
        return None;
    };
    let from = text_value(from)?;
    let to = text_value(to)?;

    match (input, from, to) {
        (Value::Null, _, _) | (_, NullableTextArg::Null, _) | (_, _, NullableTextArg::Null) => {
            Some(Value::Null)
        }
        (Value::Text(text), NullableTextArg::Text(from), NullableTextArg::Text(to)) => {
            Some(function.eval_replace_text(text, from, to))
        }
        _ => None,
    }
}

// Evaluate one literal-only SUBSTRING helper.
fn eval_substring_text_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input, start, rest @ ..] = args else {
        return None;
    };
    let start = integer_value(start)?;
    let length = match rest {
        [] => Some(None),
        [length] => Some(match integer_value(length)? {
            NullableIntegerArg::Null => None,
            NullableIntegerArg::Integer(value) => Some(value),
        }),
        _ => None,
    }?;

    match (input, start) {
        (Value::Null, _) | (_, NullableIntegerArg::Null) => Some(Value::Null),
        (Value::Text(text), NullableIntegerArg::Integer(start)) => {
            Some(function.eval_substring_text(text, start, length))
        }
        _ => None,
    }
}

// Evaluate one literal-only ROUND helper.
fn eval_numeric_scale_function_call(function: Function, args: &[Value]) -> Option<Value> {
    let [input, scale] = args else {
        return None;
    };
    let scale = integer_value(scale)?;

    match (input, scale) {
        (Value::Null, _) | (_, NullableIntegerArg::Null) => Some(Value::Null),
        (value, NullableIntegerArg::Integer(scale)) => {
            let scale = u32::try_from(scale).ok()?;

            function.eval_numeric_scale(value, scale)
        }
    }
}

// Decode one literal text argument, preserving NULL as its own boundary.
const fn text_value(value: &Value) -> Option<NullableTextArg<'_>> {
    match value {
        Value::Null => Some(NullableTextArg::Null),
        Value::Text(text) => Some(NullableTextArg::Text(text.as_str())),
        _ => None,
    }
}

// Decode one literal integer argument, preserving NULL as its own
// boundary while still accepting `Uint`.
fn integer_value(value: &Value) -> Option<NullableIntegerArg> {
    match value {
        Value::Null => Some(NullableIntegerArg::Null),
        Value::Int(inner) => Some(NullableIntegerArg::Integer(*inner)),
        Value::Uint(inner) => Some(NullableIntegerArg::Integer(
            i64::try_from(*inner).unwrap_or(i64::MAX),
        )),
        _ => None,
    }
}