hamelin_eval 0.8.0

Expression evaluation for Hamelin query language
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
use crate::value::Value;
use hamelin_lib::tree::ast::identifier::SimpleIdentifier;
use hamelin_lib::tree::builder::{
    array, call, cast, days, decimal, decimal_from_parts, null, tuple,
};
use hamelin_lib::types::array::Array;
use hamelin_lib::types::range::Range;
use hamelin_lib::types::struct_type::Struct;
use hamelin_lib::types::{decimal_type, Type, BOOLEAN, DOUBLE, INT, STRING, TIMESTAMP};
use ordermap::OrderMap;

use super::test_helpers::test_context;

const DECIMAL: Type = Type::Decimal(decimal_type::Decimal {
    precision: 18,
    scale: 6,
});

#[test]
fn test_identity_casts() {
    let ctx = test_context();

    // Same type casts should pass through unchanged
    assert_eq!(ctx.eval_expr(&cast(42, INT)), Value::Int(42));
    assert_eq!(ctx.eval_expr(&cast(3.14, DOUBLE)), Value::Double(3.14));
    assert_eq!(
        ctx.eval_expr(&cast("hello", STRING)),
        Value::String("hello".to_string())
    );
    assert_eq!(ctx.eval_expr(&cast(true, BOOLEAN)), Value::Boolean(true));
}

#[test]
fn test_null_casts() {
    let ctx = test_context();

    // NULL should cast to any type and remain NULL
    assert_eq!(ctx.eval_expr(&cast(null(), INT)), Value::Null);
    assert_eq!(ctx.eval_expr(&cast(null(), STRING)), Value::Null);
    assert_eq!(ctx.eval_expr(&cast(null(), BOOLEAN)), Value::Null);
    assert_eq!(ctx.eval_expr(&cast(null(), DOUBLE)), Value::Null);
}

#[test]
fn test_numeric_casts() {
    let ctx = test_context();

    // Int to Double
    assert_eq!(ctx.eval_expr(&cast(42, DOUBLE)), Value::Double(42.0));
    assert_eq!(ctx.eval_expr(&cast(-17, DOUBLE)), Value::Double(-17.0));
    assert_eq!(ctx.eval_expr(&cast(0, DOUBLE)), Value::Double(0.0));

    // Double to Int (truncation)
    assert_eq!(ctx.eval_expr(&cast(3.14, INT)), Value::Int(3));
    assert_eq!(ctx.eval_expr(&cast(3.99, INT)), Value::Int(3));
    assert_eq!(ctx.eval_expr(&cast(-2.7, INT)), Value::Int(-2));
    assert_eq!(ctx.eval_expr(&cast(0.0, INT)), Value::Int(0));
}

#[test]
fn test_double_overflow_to_int() {
    let ctx = test_context();

    // Test values that overflow i64 - use a much larger value
    let result = ctx.try_eval_expr(&cast(1e20, INT)); // Way beyond i64::MAX
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("overflows"));

    let result = ctx.try_eval_expr(&cast(-1e20, INT)); // Way beyond i64::MIN
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("overflows"));

    // Test infinite values (these would need special double literals)
    // For now, we'll skip these tests as they require more complex expression building
}

#[test]
fn test_string_casts() {
    let ctx = test_context();

    // To String conversions
    assert_eq!(
        ctx.eval_expr(&cast(42, STRING)),
        Value::String("42".to_string())
    );
    assert_eq!(
        ctx.eval_expr(&cast(3.14, STRING)),
        Value::String("3.14".to_string())
    );
    assert_eq!(
        ctx.eval_expr(&cast(true, STRING)),
        Value::String("true".to_string())
    );
    assert_eq!(
        ctx.eval_expr(&cast(false, STRING)),
        Value::String("false".to_string())
    );

    // From String conversions
    assert_eq!(ctx.eval_expr(&cast("42", INT)), Value::Int(42));
    assert_eq!(ctx.eval_expr(&cast("3.14", DOUBLE)), Value::Double(3.14));
    assert_eq!(ctx.eval_expr(&cast("true", BOOLEAN)), Value::Boolean(true));
    assert_eq!(
        ctx.eval_expr(&cast("false", BOOLEAN)),
        Value::Boolean(false)
    );
    assert_eq!(ctx.eval_expr(&cast("TRUE", BOOLEAN)), Value::Boolean(true)); // Case insensitive
    assert_eq!(
        ctx.eval_expr(&cast("False", BOOLEAN)),
        Value::Boolean(false)
    ); // Case insensitive
}

#[test]
fn test_string_parse_errors() {
    let ctx = test_context();

    // Invalid integer strings
    let result = ctx.try_eval_expr(&cast("not_a_number", INT));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    let result = ctx.try_eval_expr(&cast("3.14", INT));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    let result = ctx.try_eval_expr(&cast("", INT));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    // Invalid double strings
    let result = ctx.try_eval_expr(&cast("not_a_number", DOUBLE));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    let result = ctx.try_eval_expr(&cast("3.14.15", DOUBLE));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    // Invalid boolean strings
    let result = ctx.try_eval_expr(&cast("yes", BOOLEAN));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    let result = ctx.try_eval_expr(&cast("1", BOOLEAN));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));

    let result = ctx.try_eval_expr(&cast("0", BOOLEAN));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Cannot parse"));
}

#[test]
fn test_boolean_casts() {
    let ctx = test_context();

    // To Boolean
    assert_eq!(ctx.eval_expr(&cast(0, BOOLEAN)), Value::Boolean(false));
    assert_eq!(ctx.eval_expr(&cast(1, BOOLEAN)), Value::Boolean(true));
    assert_eq!(ctx.eval_expr(&cast(-1, BOOLEAN)), Value::Boolean(true));
    assert_eq!(ctx.eval_expr(&cast(42, BOOLEAN)), Value::Boolean(true));

    // From Boolean
    assert_eq!(ctx.eval_expr(&cast(true, INT)), Value::Int(1));
    assert_eq!(ctx.eval_expr(&cast(false, INT)), Value::Int(0));
    assert_eq!(
        ctx.eval_expr(&cast(true, STRING)),
        Value::String("true".to_string())
    );
    assert_eq!(
        ctx.eval_expr(&cast(false, STRING)),
        Value::String("false".to_string())
    );
}

#[test]
fn test_array_element_casting() {
    let ctx = test_context();

    // Array element type conversion
    let int_array = array().element(1).element(2).element(3);
    let result = ctx.eval_expr(&cast(int_array, Type::Array(Array::new(DOUBLE))));
    assert_eq!(
        result,
        Value::Array(vec![
            Value::Double(1.0),
            Value::Double(2.0),
            Value::Double(3.0),
        ])
    );

    let double_array = array().element(1.1).element(2.7).element(3.9);
    let result = ctx.eval_expr(&cast(double_array, Type::Array(Array::new(INT))));
    assert_eq!(
        result,
        Value::Array(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
    );

    let string_array = array().element("1").element("2").element("3");
    let result = ctx.eval_expr(&cast(string_array, Type::Array(Array::new(INT))));
    assert_eq!(
        result,
        Value::Array(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
    );
}

#[test]
fn test_tuple_to_struct_casting() {
    let ctx = test_context();

    // Create a struct type with two fields: name (String) and age (Int)
    let mut fields = OrderMap::new();
    fields.insert(SimpleIdentifier::new("name"), STRING);
    fields.insert(SimpleIdentifier::new("age"), INT);
    let struct_type = Type::Struct(Struct::new(fields));

    // Test tuple with matching elements
    let tuple_expr = tuple().element("Alice").element(30);
    println!("Testing tuple cast: {:?} -> {:?}", tuple_expr, struct_type);

    // First test if the tuple evaluates correctly
    let tuple_result = ctx.try_eval_expr(&tuple_expr);
    println!("Tuple evaluation result: {:?}", tuple_result);

    // Now test the cast
    let cast_result = ctx.try_eval_expr(&cast(tuple_expr, struct_type.clone()));
    println!("Cast result: {:?}", cast_result);

    if let Ok(Value::Struct(struct_map)) = cast_result {
        assert_eq!(
            struct_map.get(&SimpleIdentifier::new("name")),
            Some(&Value::String("Alice".to_string()))
        );
        assert_eq!(
            struct_map.get(&SimpleIdentifier::new("age")),
            Some(&Value::Int(30))
        );
    } else {
        panic!("Expected struct result, got: {:?}", cast_result);
    }

    // Test tuple with matching length but different types (type conversion)
    let type_convert_tuple = tuple().element(42).element("30"); // Int and String
    let result = ctx.try_eval_expr(&cast(type_convert_tuple, struct_type.clone()));
    println!("Type conversion tuple cast result: {:?}", result);

    if let Ok(Value::Struct(struct_map)) = result {
        assert_eq!(
            struct_map.get(&SimpleIdentifier::new("name")),
            Some(&Value::String("42".to_string()))
        );
        assert_eq!(
            struct_map.get(&SimpleIdentifier::new("age")),
            Some(&Value::Int(30))
        );
    } else {
        panic!(
            "Expected struct result for type conversion tuple, got: {:?}",
            result
        );
    }

    // Test that tuple with wrong length fails type checking (should not compile)
    let short_tuple = tuple().element("Bob");
    let short_result = ctx.try_eval_expr(&cast(short_tuple, struct_type));
    // This should fail at type checking phase, not evaluation
    assert!(
        short_result.is_err(),
        "Expected type checking error for mismatched tuple/struct lengths"
    );
}

#[test]
fn test_decimal_casts() {
    let ctx = test_context();

    // Int to Decimal
    assert_eq!(
        ctx.eval_expr(&cast(42, DECIMAL)),
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 42,
            scale: 0
        })
    );

    // Double to Decimal
    let result = ctx.eval_expr(&cast(3.14, DECIMAL));
    if let Value::Decimal(dec) = result {
        assert_eq!(dec.scale, 6);
        // 3.14 * 10^6 = 3140000
        assert_eq!(dec.unscaled, 3140000);
    } else {
        panic!("Expected decimal result");
    }

    // Decimal to Int (truncation) - now using decimal literal builder
    let decimal_literal = decimal_from_parts(31415, 5, 4); // 3.1415 with precision 5, scale 4
    let result = ctx.eval_expr(&cast(decimal_literal, INT));
    assert_eq!(result, Value::Int(3)); // Should truncate to 3

    // Decimal to Double conversion
    let decimal_literal = decimal_from_parts(31415, 5, 4); // 3.1415
    let result = ctx.eval_expr(&cast(decimal_literal, DOUBLE));
    assert_eq!(result, Value::Double(3.1415));

    // String to Decimal
    assert_eq!(
        ctx.eval_expr(&cast("3.14", DECIMAL)),
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 314,
            scale: 2
        })
    );

    assert_eq!(
        ctx.eval_expr(&cast("42", DECIMAL)),
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 42,
            scale: 0
        })
    );

    // Decimal to String
    let decimal_expr = cast("3.14159", DECIMAL);
    let result = ctx.eval_expr(&cast(decimal_expr, STRING));
    assert_eq!(result, Value::String("3.14159".to_string()));

    // Test decimal convenience function with string parsing
    let decimal_literal = decimal("123.456").expect("Valid decimal string");
    let result = ctx.eval_expr(&decimal_literal);
    assert_eq!(
        result,
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 123456,
            scale: 3
        })
    );

    // Test decimal to string conversion with literal
    let decimal_literal = decimal("99.99").expect("Valid decimal string");
    let result = ctx.eval_expr(&cast(decimal_literal, STRING));
    assert_eq!(result, Value::String("99.99".to_string()));
}

#[test]
fn test_decimal_literal_builder() {
    let ctx = test_context();

    // Test decimal literal creation with string parsing
    let decimal_literal = decimal("42.75").expect("Valid decimal string");
    let result = ctx.eval_expr(&decimal_literal);
    assert_eq!(
        result,
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 4275,
            scale: 2
        })
    );

    // Test decimal literal creation from parts
    let decimal_literal = decimal_from_parts(12345, 5, 3); // 12.345
    let result = ctx.eval_expr(&decimal_literal);
    assert_eq!(
        result,
        Value::Decimal(crate::value::DecimalValue {
            unscaled: 12345,
            scale: 3
        })
    );
}

#[test]
fn test_edge_cases() {
    let ctx = test_context();

    // Empty array casting
    let empty_array = array();
    assert_eq!(
        ctx.eval_expr(&cast(empty_array, Type::Array(Array::new(STRING)))),
        Value::Array(vec![])
    );

    // Nested null values in arrays
    let array_with_nulls = array().element(1).element(null()).element(3);
    let result = ctx.eval_expr(&cast(array_with_nulls, Type::Array(Array::new(STRING))));
    assert_eq!(
        result,
        Value::Array(vec![
            Value::String("1".to_string()),
            Value::Null,
            Value::String("3".to_string()),
        ])
    );
}

#[test]
fn test_interval_to_timestamp_range() {
    let ctx = test_context();

    // Cast interval to Range<Timestamp>
    // Positive interval: [now(), now() + interval)
    let interval_expr = days(7);
    let result = ctx.eval_expr(&cast(interval_expr, Type::Range(Range::new(TIMESTAMP))));

    // Check that we got a range with two timestamps
    if let Value::Range(range) = result {
        assert!(range.lower.is_some(), "Lower bound should exist");
        assert!(range.upper.is_some(), "Upper bound should exist");

        // Check that both bounds are timestamps
        assert!(
            matches!(range.lower.as_ref().unwrap(), Value::Timestamp(_)),
            "Lower bound should be a timestamp"
        );
        assert!(
            matches!(range.upper.as_ref().unwrap(), Value::Timestamp(_)),
            "Upper bound should be a timestamp"
        );

        // For a positive interval, lower should be <= upper
        if let (Some(Value::Timestamp(lower_ts)), Some(Value::Timestamp(upper_ts))) =
            (range.lower.as_ref(), range.upper.as_ref())
        {
            assert!(
                lower_ts <= upper_ts,
                "For positive interval, lower should be <= upper"
            );
        }
    } else {
        panic!("Expected Range value, got: {:?}", result);
    }
}

#[test]
fn test_timestamp_to_timestamp_range() {
    let ctx = test_context();

    // Cast timestamp to Range<Timestamp>
    // Should create [timestamp, now())
    let timestamp_expr = call("now");
    let result = ctx.eval_expr(&cast(timestamp_expr, Type::Range(Range::new(TIMESTAMP))));

    // Check that we got a range with two timestamps
    if let Value::Range(range) = result {
        assert!(range.lower.is_some(), "Lower bound should exist");
        assert!(range.upper.is_some(), "Upper bound should exist");

        // Check that both bounds are timestamps
        assert!(
            matches!(range.lower.as_ref().unwrap(), Value::Timestamp(_)),
            "Lower bound should be a timestamp"
        );
        assert!(
            matches!(range.upper.as_ref().unwrap(), Value::Timestamp(_)),
            "Upper bound should be a timestamp"
        );
    } else {
        panic!("Expected Range value, got: {:?}", result);
    }
}

#[test]
fn test_interval_range_to_timestamp_range() {
    let ctx = test_context();

    // Cast Range<Interval> to Range<Timestamp>
    // Using Rust range syntax: days(1)..days(7)
    let interval_range = days(1)..days(7);
    let result = ctx.eval_expr(&cast(interval_range, Type::Range(Range::new(TIMESTAMP))));

    // Check that we got a range with two timestamps
    if let Value::Range(range) = result {
        assert!(range.lower.is_some(), "Lower bound should exist");
        assert!(range.upper.is_some(), "Upper bound should exist");

        // Check that both bounds are timestamps
        assert!(
            matches!(range.lower.as_ref().unwrap(), Value::Timestamp(_)),
            "Lower bound should be a timestamp"
        );
        assert!(
            matches!(range.upper.as_ref().unwrap(), Value::Timestamp(_)),
            "Upper bound should be a timestamp"
        );
    } else {
        panic!("Expected Range value, got: {:?}", result);
    }
}