selene-db-gql 1.3.0

ISO/IEC 39075:2024 GQL parser, planner, optimizer, and executor for selene-db.
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! ISO/IEC 39075:2024 §20.8 explicit `CAST(<value> AS <target>)` dispatch matrix.
//!
//! Each `Value` x `GqlType` pair routes through this module. The matrix is
//! split into helpers per source family (numeric, string, boolean, list,
//! decimal) so the dispatch stays linear and walker-friendly. The numeric
//! family is `Table 4`'s signed-/unsigned-exact + approximate base types
//! (`EN`/`UN`/`AN`); every `EN/UN/AN ↔ EN/UN/AN/C` cell is mandated `Y`, so a
//! `Uint`/`Int128`/`Uint128`/`Float32`/`Decimal` source widens to its target
//! the same as `Int`/`Float`. Failure modes:
//!
//! - `22018` (`InvalidCharacterValueForCast`) — strict-parse failure
//!   (string→numeric/boolean/decimal) and NaN→integer/decimal (per ISO §20.8,
//!   NaN has no representable exact image).
//! - `22007` (`InvalidDatetimeFormat`) — strict-parse failure for
//!   string→date/time/datetime casts.
//! - `22G0H` (`InvalidDurationFormat`) — strict-parse failure for
//!   string→duration casts.
//! - `22003` (`NumericValueOutOfRange`) — overflow on numeric→numeric,
//!   float→integer, or any widening/Decimal conversion that loses a leading
//!   significant digit (the value does not fit the target's range).
//! - `22G03` (`InvalidValueType`, datatype mismatch) — an invalid Table-4
//!   source/target combination, e.g. boolean ↔ numeric (Table 4 `N`), which
//!   ISO does not define a `CAST` for.
//! - `42N01` (`FEATURE_NOT_SUPPORTED`) — source or target outside the
//!   currently implemented explicit-cast scope (NODE / EDGE / PATH source or
//!   any cast whose target is `NULL` / `NOTHING`).

use std::borrow::Cow;
use std::sync::Arc;

use selene_core::{CharacterStringCoercionError, DbString, JsonValue, PropertyValueType, Value};

use crate::{
    GqlType, SourceSpan,
    runtime::{DataExceptionSubclass, EvalCtx, ExecutorError, value_type_match},
};

use super::uuid_fns::parse_uuid_string;

mod decimal;
mod float;
mod numeric_text;
mod record;
mod signed;
mod signed128;
mod temporal;
mod unsigned;
mod vector;

use float::{FloatTarget, cast_to_float};
use record::cast_to_record;
use signed::{SignedIntegerTarget, cast_to_signed_integer};
use signed128::cast_to_int128;
use temporal::cast_to_temporal;
use unsigned::{UnsignedIntegerTarget, cast_to_unsigned_integer};
use vector::cast_to_vector;

/// Evaluate an explicit CAST.
///
/// `value` is the already-evaluated source value; `target_type` is the
/// declared GQL target. The returned `Value` matches the canonical Rust
/// representation of `target_type` (`Integer` → `Value::Int(i64)`, `STRING`
/// → `Value::String(DbString)`, etc.). NULL propagates as NULL (ISO §22
/// universal rule). Unsupported source/target combinations produce
/// `FeatureNotSupportedYet` with a descriptive `feature` tag.
pub(super) fn eval_cast(
    value: Value,
    target_type: &GqlType,
    span: SourceSpan,
    ctx: &EvalCtx<'_, '_, '_, '_>,
) -> Result<Value, ExecutorError> {
    if let GqlType::NotNull(inner) = target_type {
        if matches!(value, Value::Null) {
            return Err(ExecutorError::data_exception(
                DataExceptionSubclass::NullValueNotAllowed,
                "CAST to a NOT NULL value type cannot produce NULL",
                span,
            ));
        }
        return eval_cast(value, inner, span, ctx);
    }

    if matches!(target_type, GqlType::ClosedDynamicUnion(_)) {
        return cast_to_closed_dynamic_union(value, target_type, span);
    }

    // §22 universal: NULL casts to NULL regardless of target.
    if matches!(value, Value::Null) {
        return Ok(Value::Null);
    }

    // Target-level rejections for non-NULL source values.
    match target_type {
        GqlType::Null => {
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST to NULL",
                span,
            });
        }
        GqlType::Nothing => {
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST to NOTHING",
                span,
            });
        }
        _ => {}
    }

    if matches!(target_type, GqlType::Any | GqlType::AnyProperty) {
        return cast_to_dynamic_union(value, target_type, span);
    }

    // A RECORD target is handled before the generic source-rejection block: per ISO §20.8
    // Table 4 the only valid source for a record target is a record (R -> R), so a record
    // source reaching a record target must not be spuriously rejected below.
    if let GqlType::Record(record_type) = target_type {
        return cast_to_record(value, record_type, span, ctx);
    }

    // Source-level rejections (graph-element / path / record).
    match &value {
        Value::NodeRef(_) => {
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST from NODE",
                span,
            });
        }
        Value::EdgeRef(_) => {
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST from EDGE",
                span,
            });
        }
        Value::Path(_) => {
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST from PATH",
                span,
            });
        }
        Value::Record(_) | Value::RecordTyped(_) => {
            // A record source to a non-record (scalar/list) target is an invalid type
            // combination per ISO §20.8 Table 4 (`N`), i.e. a 22G03 datatype mismatch —
            // not a missing feature.
            return Err(ExecutorError::data_exception(
                DataExceptionSubclass::InvalidValueType,
                "CAST from RECORD to a non-record type is not a valid type combination",
                span,
            ));
        }
        Value::Bytes(_) if !matches!(target_type, GqlType::Bytes | GqlType::ByteString(_)) => {
            // ISO §20.8 Table 4: byte strings only cast to byte strings. Every
            // byte-string source to a non-BYTES target is an invalid
            // source/target combination, not an unimplemented conversion.
            return Err(non_iso_combination(
                "CAST from BYTES to a non-BYTES type is not a valid type combination",
                span,
            ));
        }
        Value::Json(_)
            if !matches!(
                target_type,
                GqlType::Json | GqlType::String | GqlType::CharacterString(_)
            ) =>
        {
            return Err(non_iso_combination(
                "CAST from JSON to this target is not a valid type combination",
                span,
            ));
        }
        _ => {}
    }

    match target_type {
        GqlType::Integer | GqlType::Int64 | GqlType::BigInt => {
            cast_to_signed_integer(value, SignedIntegerTarget::I64, span)
        }
        GqlType::Int8 => cast_to_signed_integer(value, SignedIntegerTarget::I8, span),
        GqlType::Int16 | GqlType::SmallInt => {
            cast_to_signed_integer(value, SignedIntegerTarget::I16, span)
        }
        GqlType::Int32 => cast_to_signed_integer(value, SignedIntegerTarget::I32, span),
        GqlType::Int128 => cast_to_int128(value, span),
        GqlType::Uint8 => cast_to_unsigned_integer(value, UnsignedIntegerTarget::U8, span),
        GqlType::Uint16 | GqlType::USmallInt => {
            cast_to_unsigned_integer(value, UnsignedIntegerTarget::U16, span)
        }
        GqlType::Uint32 | GqlType::Uint => {
            cast_to_unsigned_integer(value, UnsignedIntegerTarget::U32, span)
        }
        GqlType::Uint64 | GqlType::UBigInt => {
            cast_to_unsigned_integer(value, UnsignedIntegerTarget::U64, span)
        }
        GqlType::Uint128 => cast_to_unsigned_integer(value, UnsignedIntegerTarget::U128, span),
        GqlType::Float | GqlType::Float64 | GqlType::Double => {
            cast_to_float(value, FloatTarget::F64, span)
        }
        GqlType::Float32 | GqlType::Real => cast_to_float(value, FloatTarget::F32, span),
        GqlType::Decimal => decimal::numeric_to_decimal(value, span),
        GqlType::DecimalExact(decimal_type) => {
            decimal::numeric_to_decimal_exact(value, *decimal_type, span)
        }
        GqlType::Boolean => cast_to_boolean(value, span),
        GqlType::String => cast_to_string(value, None, span),
        GqlType::CharacterString(character_type) => {
            cast_to_string(value, Some(character_type), span)
        }
        GqlType::Bytes => cast_to_bytes(value, None, span),
        GqlType::ByteString(byte_type) => cast_to_bytes(value, Some(byte_type), span),
        GqlType::Uuid => cast_to_uuid(value, span),
        GqlType::Json => cast_to_json(value, span),
        GqlType::Vector => cast_to_vector(value, span),
        GqlType::ZonedDateTime
        | GqlType::LocalDateTime
        | GqlType::Date
        | GqlType::ZonedTime
        | GqlType::LocalTime
        | GqlType::Duration
        | GqlType::DurationYearToMonth
        | GqlType::DurationDayToSecond => cast_to_temporal(value, target_type, span, ctx),
        GqlType::List(element_type) => cast_to_list(value, element_type, None, span, ctx),
        GqlType::BoundedList {
            element_type,
            max_len,
        } => cast_to_list(value, element_type, Some(*max_len), span, ctx),
        other => Err(ExecutorError::FeatureNotSupportedYet {
            feature: cast_to_type_feature(other),
            span,
        }),
    }
}

fn cast_to_dynamic_union(
    value: Value,
    target_type: &GqlType,
    span: SourceSpan,
) -> Result<Value, ExecutorError> {
    match target_type {
        GqlType::Any => Ok(value),
        GqlType::AnyProperty if PropertyValueType::of(&value).is_some() => Ok(value),
        GqlType::AnyProperty => Err(ExecutorError::data_exception(
            DataExceptionSubclass::InvalidValueType,
            "CAST source is not a supported property value",
            span,
        )),
        _ => unreachable!("dynamic-union cast called for non-dynamic target"),
    }
}

fn cast_to_closed_dynamic_union(
    value: Value,
    target_type: &GqlType,
    span: SourceSpan,
) -> Result<Value, ExecutorError> {
    if value_type_match::value_matches_gql_type(&value, target_type) {
        return Ok(value);
    }
    Err(ExecutorError::data_exception(
        DataExceptionSubclass::InvalidValueType,
        "CAST source is not a member of the closed dynamic union type",
        span,
    ))
}

fn cast_to_boolean(value: Value, span: SourceSpan) -> Result<Value, ExecutorError> {
    // Per ISO §20.8 Table 4 the only valid sources for a boolean target are
    // `BO` (identity, GR4 boolean-source rule) and `C` (string, GR4q). Every
    // numeric source (`EN`/`UN`/`AN`, including DECIMAL) is a `N` cell — ISO
    // has no numeric→boolean cast — so it is a 22G03 datatype mismatch, not a
    // 0/1-truthiness extension.
    match value {
        Value::Bool(b) => Ok(Value::Bool(b)),
        Value::String(s) => string_to_boolean(s.as_str(), span),
        Value::Int(_)
        | Value::Uint(_)
        | Value::Int128(_)
        | Value::Uint128(_)
        | Value::Float(_)
        | Value::Float32(_)
        | Value::Decimal(_) => Err(non_iso_combination(
            "CAST from a numeric type to BOOLEAN is not a valid type combination",
            span,
        )),
        other => Err(
            non_iso_static_source_for_target(&other, "BOOLEAN", span).unwrap_or(
                ExecutorError::FeatureNotSupportedYet {
                    feature: "CAST source not supported for BOOLEAN target",
                    span,
                },
            ),
        ),
    }
}

fn cast_to_string(
    value: Value,
    target_type: Option<&crate::ast::CharacterStringType>,
    span: SourceSpan,
) -> Result<Value, ExecutorError> {
    let rendered: String = match value {
        // ISO §20.8 GR4(j)(v)(1): boolean→string renders the UPPERCASE literal
        // `'TRUE'`/`'FALSE'` (GR4v), not lowercase.
        Value::Bool(b) => if b { "TRUE" } else { "FALSE" }.to_owned(),
        // Numeric → C (GR4j): the shortest conforming literal. Every numeric
        // family is a Table-4 `Y` source, rendered through its own `Display`.
        Value::Int(v) => v.to_string(),
        Value::Uint(v) => v.to_string(),
        Value::Int128(v) => v.to_string(),
        Value::Uint128(v) => v.to_string(),
        Value::Float(f) => format_float(f),
        Value::Float32(f) => format_float(f64::from(f)),
        Value::Decimal(d) => decimal::decimal_to_string(&d),
        Value::String(s) => s.as_str().to_owned(),
        Value::Uuid(v) => v.to_string(),
        Value::ZonedDateTime(v) => format!("{}{}", v.datetime(), v.offset()),
        Value::LocalDateTime(v) => v.to_string(),
        Value::Date(v) => v.to_string(),
        Value::ZonedTime(v) => format!("{}{}", v.time(), v.offset()),
        Value::LocalTime(v) => v.to_string(),
        Value::Duration(v) => v.to_string(),
        Value::Json(v) => v.to_canonical_string(),
        other => {
            if let Some(error) = non_iso_static_source_for_target(&other, "STRING", span) {
                return Err(error);
            }
            return Err(ExecutorError::FeatureNotSupportedYet {
                feature: "CAST source not supported for STRING target",
                span,
            });
        }
    };
    // CAST output strings construct a plain `Value::String`; the global guard
    // remains IL013, while an explicit target type applies the character-count
    // envelope before storage construction.
    let rendered = coerce_string_to_type(rendered, target_type, span)?;
    match DbString::from_string(rendered) {
        Ok(db_string) => Ok(Value::String(db_string)),
        Err(_err) => Err(ExecutorError::data_exception(
            DataExceptionSubclass::DataException,
            "CAST result string exceeds the maximum byte length",
            span,
        )),
    }
}

fn coerce_string_to_type(
    mut value: String,
    target_type: Option<&crate::ast::CharacterStringType>,
    span: SourceSpan,
) -> Result<String, ExecutorError> {
    let Some(target_type) = target_type else {
        return Ok(value);
    };
    // Parser-validated bounds (`1 <= min_len <= max_len`) satisfy the core
    // envelope invariants by construction. The shared core coercion keeps the
    // CAST funnel on the same IV023 space-only truncation policy as store
    // assignment and DEFAULT descriptor coercion.
    let target = selene_core::CharacterStringType {
        min_len: target_type.min_len,
        max_len: target_type.max_len,
    };
    let coerced = selene_core::coerce_character_string_to_type(&value, target).map_err(|err| {
        let (subclass, detail) = match err {
            CharacterStringCoercionError::SourceLengthOverflow => (
                DataExceptionSubclass::NumericValueOutOfRange,
                "character string source length exceeds supported range",
            ),
            CharacterStringCoercionError::TargetMinOverflow => (
                DataExceptionSubclass::NumericValueOutOfRange,
                "character string target minimum length exceeds supported range",
            ),
            CharacterStringCoercionError::TargetMaxOverflow => (
                DataExceptionSubclass::NumericValueOutOfRange,
                "character string target maximum length exceeds supported range",
            ),
            CharacterStringCoercionError::NonSpaceTruncation => (
                DataExceptionSubclass::StringDataRightTruncation,
                "character string cast would truncate non-space trailing characters",
            ),
        };
        ExecutorError::data_exception(subclass, detail, span)
    })?;
    match coerced {
        Cow::Owned(coerced) => Ok(coerced),
        Cow::Borrowed(coerced) => {
            // A borrowed result is the whole value or a truncated prefix of
            // it, so the rendered buffer is reused in place.
            let keep = coerced.len();
            value.truncate(keep);
            Ok(value)
        }
    }
}

fn cast_to_json(value: Value, span: SourceSpan) -> Result<Value, ExecutorError> {
    match value {
        Value::Json(value) => Ok(Value::Json(value)),
        Value::String(value) => parse_json_value(value.as_str(), span),
        _ => Err(non_iso_combination(
            "CAST from this source to JSON is not a valid type combination",
            span,
        )),
    }
}

pub(super) fn parse_json_value(text: &str, span: SourceSpan) -> Result<Value, ExecutorError> {
    JsonValue::parse_str(text).map(Value::Json).map_err(|err| {
        if err.gqlstatus() == "22018" {
            ExecutorError::data_exception(
                DataExceptionSubclass::InvalidCharacterValueForCast,
                format!("STRING value is not valid JSON: {err}"),
                span,
            )
        } else {
            ExecutorError::data_exception(
                DataExceptionSubclass::DataException,
                format!("JSON value exceeds implementation-defined limits: {err}"),
                span,
            )
        }
    })
}

fn cast_to_uuid(value: Value, span: SourceSpan) -> Result<Value, ExecutorError> {
    match value {
        Value::Uuid(v) => Ok(Value::Uuid(v)),
        Value::String(s) => parse_uuid_string(s.as_str(), span).map(Value::Uuid),
        _ => Err(ExecutorError::FeatureNotSupportedYet {
            feature: "CAST source not supported for UUID target",
            span,
        }),
    }
}

fn cast_to_bytes(
    value: Value,
    target_type: Option<&crate::ast::ByteStringType>,
    span: SourceSpan,
) -> Result<Value, ExecutorError> {
    match value {
        Value::Bytes(value) => coerce_bytes_to_type(value, target_type, span),
        _ => Err(non_iso_combination(
            "CAST from a non-BYTES type to BYTES is not a valid type combination",
            span,
        )),
    }
}

fn coerce_bytes_to_type(
    value: Arc<[u8]>,
    target_type: Option<&crate::ast::ByteStringType>,
    span: SourceSpan,
) -> Result<Value, ExecutorError> {
    let Some(target_type) = target_type else {
        return Ok(Value::Bytes(value));
    };
    let len = value.len() as u64;
    if len >= target_type.min_len && len <= target_type.max_len {
        return Ok(Value::Bytes(value));
    }
    if len < target_type.min_len {
        let target_len = usize::try_from(target_type.min_len).map_err(|_| {
            ExecutorError::data_exception(
                DataExceptionSubclass::NumericValueOutOfRange,
                "byte string target minimum length exceeds supported range",
                span,
            )
        })?;
        let mut padded = Vec::with_capacity(target_len);
        padded.extend_from_slice(&value);
        padded.resize(target_len, 0);
        return Ok(Value::Bytes(Arc::<[u8]>::from(padded.into_boxed_slice())));
    }

    let max_len = usize::try_from(target_type.max_len).map_err(|_| {
        ExecutorError::data_exception(
            DataExceptionSubclass::NumericValueOutOfRange,
            "byte string target maximum length exceeds supported range",
            span,
        )
    })?;
    if value[max_len..].iter().any(|byte| *byte != 0) {
        return Err(ExecutorError::data_exception(
            DataExceptionSubclass::StringDataRightTruncation,
            "byte string cast would truncate non-zero trailing bytes",
            span,
        ));
    }
    Ok(Value::Bytes(Arc::<[u8]>::from(&value[..max_len])))
}

fn cast_to_list(
    value: Value,
    element_type: &GqlType,
    max_len: Option<u64>,
    span: SourceSpan,
    ctx: &EvalCtx<'_, '_, '_, '_>,
) -> Result<Value, ExecutorError> {
    let items = match value {
        Value::List(items) => items,
        other => {
            return Err(
                non_iso_static_source_for_target(&other, "LIST", span).unwrap_or(
                    ExecutorError::FeatureNotSupportedYet {
                        feature: "CAST to LIST requires a LIST source",
                        span,
                    },
                ),
            );
        }
    };
    if let Some(max_len) = max_len
        && u64::try_from(items.len()).map_or(true, |len| len > max_len)
    {
        return Err(ExecutorError::data_exception(
            DataExceptionSubclass::InvalidValueType,
            "LIST cast result exceeds declared maximum cardinality",
            span,
        ));
    }
    let mut out = Vec::with_capacity(items.len());
    for item in items {
        // Recursive element-wise cast preserves nested-list semantics per
        // ISO §22.7. Stack-grown via `stacker::maybe_grow` to bound the
        // worst-case nested-LIST depth.
        out.push(stacker::maybe_grow(64 * 1024, 1024 * 1024, || {
            eval_cast(item, element_type, span, ctx)
        })?);
    }
    Ok(Value::List(out))
}

/// An invalid ISO §20.8 Table-4 source/target combination (a `N` cell) →
/// `22G03` datatype mismatch. Used for the boolean↔numeric cells ISO does not
/// define a `CAST` for.
fn non_iso_combination(message: impl Into<String>, span: SourceSpan) -> ExecutorError {
    ExecutorError::data_exception(DataExceptionSubclass::InvalidValueType, message, span)
}

pub(super) fn non_iso_static_source_for_target(
    value: &Value,
    target: &'static str,
    span: SourceSpan,
) -> Option<ExecutorError> {
    let source = iso_static_source_name(value)?;
    Some(non_iso_combination(
        format!("CAST from {source} to {target} is not a valid type combination"),
        span,
    ))
}

fn iso_static_source_name(value: &Value) -> Option<&'static str> {
    Some(match value {
        Value::Bool(_) => "BOOLEAN",
        Value::Int(_) | Value::Int128(_) | Value::Decimal(_) => "signed exact numeric",
        Value::Uint(_) | Value::Uint128(_) => "unsigned exact numeric",
        Value::Float(_) | Value::Float32(_) => "approximate numeric",
        Value::String(_) => "STRING",
        Value::Bytes(_) => "BYTES",
        Value::List(_) => "LIST",
        Value::Record(_) | Value::RecordTyped(_) => "RECORD",
        Value::Path(_) => "PATH",
        Value::ZonedDateTime(_) | Value::LocalDateTime(_) | Value::Date(_) => "datetime",
        Value::ZonedTime(_) | Value::LocalTime(_) => "time",
        Value::Duration(_) => "DURATION",
        Value::Null => "NULL",
        Value::NodeRef(_) | Value::EdgeRef(_) | Value::GraphRef(_) | Value::TableRef(_) => {
            return None;
        }
        Value::Extended { .. } | Value::Uuid(_) | Value::Vector(_) | Value::Json(_) => return None,
        _ => return None,
    })
}

fn string_to_boolean(text: &str, span: SourceSpan) -> Result<Value, ExecutorError> {
    // ISO §20.8 GR4(q) defers C→BO to the §21.2 boolean-literal rules, which
    // are case-insensitive (`TRUE`/`True`/`true`, `FALSE`/`False`/`false`).
    // Trim leading/trailing whitespace consistent with the numeric GR4(g)(ii)
    // truncating-whitespace rule used by string-to-integer casts.
    match text.trim().to_ascii_lowercase().as_str() {
        "true" => Ok(Value::Bool(true)),
        "false" => Ok(Value::Bool(false)),
        _ => Err(invalid_character(text, "BOOLEAN", span)),
    }
}

fn invalid_character(text: &str, target: &str, span: SourceSpan) -> ExecutorError {
    ExecutorError::data_exception(
        DataExceptionSubclass::InvalidCharacterValueForCast,
        format!("STRING value `{text}` is not a valid {target}"),
        span,
    )
}

fn format_float(f: f64) -> String {
    if f.is_nan() {
        "NaN".to_owned()
    } else if f.is_infinite() {
        if f > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
    } else {
        format!("{f}")
    }
}

fn cast_to_type_feature(target: &GqlType) -> &'static str {
    match target {
        GqlType::DecimalExact(_) => "CAST to DECIMAL",
        GqlType::CharacterString(_) => "CAST to STRING",
        GqlType::Bytes | GqlType::ByteString(_) => "CAST to BYTES",
        GqlType::ZonedDateTime => "CAST to ZONED DATETIME",
        GqlType::LocalDateTime => "CAST to LOCAL DATETIME",
        GqlType::Date => "CAST to DATE",
        GqlType::ZonedTime => "CAST to ZONED TIME",
        GqlType::LocalTime => "CAST to LOCAL TIME",
        GqlType::Duration | GqlType::DurationYearToMonth | GqlType::DurationDayToSecond => {
            "CAST to DURATION"
        }
        GqlType::Vector => "CAST to VECTOR",
        GqlType::Json => "CAST to JSON",
        GqlType::Record(_) => "CAST to RECORD",
        GqlType::ClosedDynamicUnion(_) => "CAST to closed dynamic union",
        GqlType::NotNull(inner) => cast_to_type_feature(inner),
        GqlType::Path => "CAST to PATH",
        GqlType::GraphRef => "CAST to GRAPH",
        GqlType::NodeRef => "CAST to NODE",
        GqlType::EdgeRef => "CAST to EDGE",
        GqlType::TableRef(_) => "CAST to TABLE",
        _ => "CAST to unsupported target type",
    }
}

#[cfg(test)]
mod tests;