ydb 0.12.0

Crate contains generated low-level grpc code from YDB API protobuf, used as base for ydb crate
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
use crate::client::Client;
use crate::errors::YdbError;
use crate::types::{Bytes, YdbDecimal};
use crate::{
    test_helpers::test_client_builder, ydb_params, Query, Sign, SignedInterval, Value, YdbResult,
};
use std::time::{Duration, SystemTime};
use uuid::Uuid;

#[test]
fn test_is_optional() -> YdbResult<()> {
    assert!(Value::optional_from(Value::Bool(false), None)?.is_optional());
    assert!(Value::optional_from(Value::Bool(false), Some(Value::Bool(false)))?.is_optional());
    assert!(!Value::Bool(false).is_optional());
    Ok(())
}

#[test]
fn test_ydb_decimal_preserves_precision_and_scale() {
    let value = "123.45".parse::<decimal_rs::Decimal>().unwrap();
    let ydb_dec = YdbDecimal::try_new(value, 22, 9).unwrap();
    assert_eq!(ydb_dec.precision(), 22);
    assert_eq!(ydb_dec.scale(), 9);
}

#[test]
fn test_ydb_decimal_rejects_precision_overflow() {
    // 10 digits, precision 5 — should fail
    let value = "1234567890.12".parse::<decimal_rs::Decimal>().unwrap();
    let result = YdbDecimal::try_new(value, 5, 2);
    assert!(result.is_err());
}

#[test]
fn test_ydb_decimal_rejects_scale_decrease() {
    // value has scale=3, requested scale=1 — should fail
    let value = "1.234".parse::<decimal_rs::Decimal>().unwrap();
    let result = YdbDecimal::try_new(value, 10, 1);
    assert!(result.is_err());
}

#[test]
fn test_ydb_decimal_allows_scale_increase() {
    // value has scale=2, requested scale=9 — should succeed
    let value = "123.45".parse::<decimal_rs::Decimal>().unwrap();
    let ydb_dec = YdbDecimal::try_new(value, 22, 9).unwrap();
    assert_eq!(ydb_dec.scale(), 9);
    assert_eq!(ydb_dec.precision(), 22);
}

#[test]
fn test_ydb_decimal_into_value() {
    let value = "99.99".parse::<decimal_rs::Decimal>().unwrap();
    let ydb_dec = YdbDecimal::try_new(value, 10, 2).unwrap();
    let v: Value = ydb_dec.into();
    match v {
        Value::Decimal(d) => {
            assert_eq!(d.precision(), 10);
            assert_eq!(d.scale(), 2);
        }
        _ => panic!("expected Value::Decimal"),
    }
}

#[test]
fn test_ydb_decimal_new_unchecked() {
    let value = "1.5".parse::<decimal_rs::Decimal>().unwrap();
    let ydb_dec = YdbDecimal::new_unchecked(value, 22, 9);
    assert_eq!(ydb_dec.precision(), 22);
    assert_eq!(ydb_dec.scale(), 9);
}

#[tokio::test]
#[ignore] // need YDB access
async fn test_decimal() -> YdbResult<()> {
    let client = test_client_builder().client()?;

    client.wait().await?;

    let db_value: Option<decimal_rs::Decimal> = client
        .table_client()
        .retry_transaction(|mut t| async move {
            let res = t
                .query(Query::from(
                    "select CAST(\"-1233333333333333333333345.34\" AS Decimal(28, 2)) as db_value",
                ))
                .await?;
            Ok(res.into_only_row()?.remove_field_by_name("db_value")?)
        })
        .await?
        .try_into()
        .unwrap();
    let test_value = Some(
        "-1233333333333333333333345.34"
            .parse::<decimal_rs::Decimal>()
            .unwrap(),
    );
    assert_eq!(test_value, db_value);

    Ok(())
}

/// One round-trip test case for a YQL primitive type.
///
/// Adding coverage for a new type/value is a single row in `type_cases()`.
#[derive(Debug, Clone)]
struct TypeCase {
    /// YQL type name as used in `DECLARE $x AS <yql_type>`. May contain
    /// parameters (e.g. `"Decimal(22, 9)"`).
    yql_type: String,
    /// Value sent as parameter; also expected back from the server.
    value: Value,
    /// Expected canonical text representation as produced by
    /// `CAST(<value> AS Utf8)` on the server, and accepted by
    /// `CAST(<text> AS <yql_type>)` on the server.
    text: String,
}

impl TypeCase {
    fn new(yql_type: impl Into<String>, value: Value, text: impl Into<String>) -> Self {
        Self {
            yql_type: yql_type.into(),
            value,
            text: text.into(),
        }
    }
}

fn type_cases() -> Vec<TypeCase> {
    let mut cases: Vec<TypeCase> = Vec::new();

    // ---- Bool ----
    cases.push(TypeCase::new("Bool", Value::Bool(true), "true"));
    cases.push(TypeCase::new("Bool", Value::Bool(false), "false"));

    // ---- Signed integers ----
    for (v, s) in [
        (0i8, "0"),
        (1, "1"),
        (-1, "-1"),
        (i8::MAX, "127"),
        (i8::MIN, "-128"),
    ] {
        cases.push(TypeCase::new("Int8", Value::Int8(v), s));
    }
    for (v, s) in [
        (0i16, "0"),
        (1, "1"),
        (-1, "-1"),
        (i16::MAX, "32767"),
        (i16::MIN, "-32768"),
    ] {
        cases.push(TypeCase::new("Int16", Value::Int16(v), s));
    }
    for (v, s) in [
        (0i32, "0"),
        (1, "1"),
        (-1, "-1"),
        (i32::MAX, "2147483647"),
        (i32::MIN, "-2147483648"),
    ] {
        cases.push(TypeCase::new("Int32", Value::Int32(v), s));
    }
    for (v, s) in [
        (0i64, "0"),
        (1, "1"),
        (-1, "-1"),
        (i64::MAX, "9223372036854775807"),
        (i64::MIN, "-9223372036854775808"),
    ] {
        cases.push(TypeCase::new("Int64", Value::Int64(v), s));
    }

    // ---- Unsigned integers ----
    for (v, s) in [(0u8, "0"), (1, "1"), (u8::MAX, "255")] {
        cases.push(TypeCase::new("Uint8", Value::Uint8(v), s));
    }
    for (v, s) in [(0u16, "0"), (1, "1"), (u16::MAX, "65535")] {
        cases.push(TypeCase::new("Uint16", Value::Uint16(v), s));
    }
    for (v, s) in [(0u32, "0"), (1, "1"), (u32::MAX, "4294967295")] {
        cases.push(TypeCase::new("Uint32", Value::Uint32(v), s));
    }
    for (v, s) in [(0u64, "0"), (1, "1"), (u64::MAX, "18446744073709551615")] {
        cases.push(TypeCase::new("Uint64", Value::Uint64(v), s));
    }

    // ---- Floating point ----
    // Ordinary values, IEEE-754 magnitude edges, and special values
    // (±0, ±inf, NaN). NaN equality is handled by `value_roundtrip_eq`.
    for (v, s) in [
        (0.0f32, "0"),
        (-0.0, "-0"),
        (1.0, "1"),
        (-1.0, "-1"),
        (1.5, "1.5"),
        (-1.5, "-1.5"),
        (f32::MIN_POSITIVE, "1.1754944e-38"),
        (-f32::MIN_POSITIVE, "-1.1754944e-38"),
        (f32::MAX, "3.4028235e+38"),
        (f32::MIN, "-3.4028235e+38"),
        (f32::INFINITY, "inf"),
        (f32::NEG_INFINITY, "-inf"),
        (f32::NAN, "nan"),
    ] {
        cases.push(TypeCase::new("Float", Value::Float(v), s));
    }
    for (v, s) in [
        (0.0f64, "0"),
        (-0.0, "-0"),
        (1.0, "1"),
        (-1.0, "-1"),
        (1.5, "1.5"),
        (-1.5, "-1.5"),
        (f64::MIN_POSITIVE, "2.2250738585072014e-308"),
        (-f64::MIN_POSITIVE, "-2.2250738585072014e-308"),
        (f64::MAX, "1.7976931348623157e+308"),
        (f64::MIN, "-1.7976931348623157e+308"),
        (f64::INFINITY, "inf"),
        (f64::NEG_INFINITY, "-inf"),
        (f64::NAN, "nan"),
    ] {
        cases.push(TypeCase::new("Double", Value::Double(v), s));
    }

    // ---- Date (day granularity); YDB range: 1970-01-01 .. 2105-12-31 ----
    // 49672 days from epoch = 2105-12-31
    const DAYS_TO_2105_12_31: u64 = 49_672;
    cases.push(TypeCase::new(
        "Date",
        Value::Date(SystemTime::UNIX_EPOCH),
        "1970-01-01",
    ));
    cases.push(TypeCase::new(
        "Date",
        Value::Date(SystemTime::UNIX_EPOCH + Duration::from_secs(19_737 * 86_400)),
        "2024-01-15",
    ));
    cases.push(TypeCase::new(
        "Date",
        Value::Date(SystemTime::UNIX_EPOCH + Duration::from_secs(DAYS_TO_2105_12_31 * 86_400)),
        "2105-12-31",
    ));

    // ---- Datetime (second granularity); YDB range: 1970-01-01T00:00:00Z .. 2105-12-31T23:59:59Z ----
    const SECS_TO_2105_12_31_END: u64 = DAYS_TO_2105_12_31 * 86_400 + 23 * 3600 + 59 * 60 + 59;
    cases.push(TypeCase::new(
        "Datetime",
        Value::DateTime(SystemTime::UNIX_EPOCH),
        "1970-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Datetime",
        Value::DateTime(SystemTime::UNIX_EPOCH + Duration::from_secs(1_705_320_645)),
        "2024-01-15T12:10:45Z",
    ));
    cases.push(TypeCase::new(
        "Datetime",
        Value::DateTime(SystemTime::UNIX_EPOCH + Duration::from_secs(SECS_TO_2105_12_31_END)),
        "2105-12-31T23:59:59Z",
    ));

    // ---- Timestamp (microsecond granularity); YDB range: 1970-01-01T00:00:00Z .. 2105-12-31T23:59:59.999999Z ----
    cases.push(TypeCase::new(
        "Timestamp",
        Value::Timestamp(SystemTime::UNIX_EPOCH),
        "1970-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp",
        Value::Timestamp(SystemTime::UNIX_EPOCH + Duration::from_micros(1)),
        "1970-01-01T00:00:00.000001Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp",
        Value::Timestamp(SystemTime::UNIX_EPOCH + Duration::from_micros(1_705_320_645_123_456)),
        "2024-01-15T12:10:45.123456Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp",
        Value::Timestamp(
            SystemTime::UNIX_EPOCH
                + Duration::from_micros(SECS_TO_2105_12_31_END * 1_000_000 + 999_999),
        ),
        "2105-12-31T23:59:59.999999Z",
    ));

    // ---- Interval (signed microsecond duration, bounded to Timestamp domain) ----
    // Wire format: int64 microseconds. YDB validates with exclusive bounds
    // `(-MAX_TIMESTAMP, MAX_TIMESTAMP)` where
    // `MAX_TIMESTAMP = 86_400_000_000 * 49_673 = 4_291_747_200_000_000 µs`;
    // i.e. accepted values are `-INTERVAL_MAX ..= INTERVAL_MAX` where
    // `INTERVAL_MAX = MAX_TIMESTAMP - 1`. Source:
    // `yql/essentials/public/udf/udf_data_type.h`.
    const INTERVAL_MAX: u64 = 86_400_000_000 * 49_673 - 1;
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(1),
        }),
        "PT0.000001S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(1),
        }),
        "-PT0.000001S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(999_999),
        }),
        "PT0.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_secs(1),
        }),
        "PT1S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_secs(1),
        }),
        "-PT1S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(19_845_000_123),
        }),
        "PT5H30M45.000123S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(8_130_000_000),
        }),
        "-PT2H15M30S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(86_399_999_999),
        }),
        "PT23H59M59.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(86_399_999_999),
        }),
        "-PT23H59M59.999999S",
    ));
    // Server extreme bounds (±INTERVAL_MAX = ±(MAX_TIMESTAMP - 1 µs) =
    // ±4_291_747_199_999_999 µs = ±(49_672 days, 23h59m59.999999s)).
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(INTERVAL_MAX),
        }),
        "P49672DT23H59M59.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval",
        Value::IntervalMicros(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(INTERVAL_MAX),
        }),
        "-P49672DT23H59M59.999999S",
    ));

    // ---- Date32 (signed days from epoch) ----
    // YDB Date32 range per `yql/essentials/public/udf/udf_data_type.h`:
    //   MIN_DATE32 = -53_375_809 (year -144169-01-01)
    //   MAX_DATE32 =  53_375_807 (year 148107-12-31)
    // Cases: epoch, ±1 day, 2024-01-15, 0001-01-01 / 9999-12-31 (4-digit year edge),
    // and the server extreme bounds.
    const DATE32_EPOCH_TO_9999_12_31_SECS: u64 = 2_932_896 * 86_400;
    const DATE32_0001_01_01_TO_EPOCH_SECS: u64 = 719_162 * 86_400;
    const DATE32_MIN_DAYS_TO_EPOCH_SECS: u64 = 53_375_809 * 86_400;
    const DATE32_EPOCH_TO_MAX_DAYS_SECS: u64 = 53_375_807 * 86_400;
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH),
        "1970-01-01",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH + Duration::from_secs(19_737 * 86_400)),
        "2024-01-15",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH - Duration::from_secs(86_400)),
        "1969-12-31",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400)),
        "1970-01-02",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(
            SystemTime::UNIX_EPOCH + Duration::from_secs(DATE32_EPOCH_TO_9999_12_31_SECS),
        ),
        "9999-12-31",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(
            SystemTime::UNIX_EPOCH - Duration::from_secs(DATE32_0001_01_01_TO_EPOCH_SECS),
        ),
        "1-01-01",
    ));
    // Server extreme bounds (MIN_DATE32 / MAX_DATE32)
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH - Duration::from_secs(DATE32_MIN_DAYS_TO_EPOCH_SECS)),
        "-144169-01-01",
    ));
    cases.push(TypeCase::new(
        "Date32",
        Value::Date32(SystemTime::UNIX_EPOCH + Duration::from_secs(DATE32_EPOCH_TO_MAX_DAYS_SECS)),
        "148107-12-31",
    ));

    // ---- Datetime64 (signed seconds from epoch) ----
    // YDB Datetime64 range per `udf_data_type.h`:
    //   MIN_DATETIME64 = -4_611_669_897_600 (year -144169-01-01T00:00:00)
    //   MAX_DATETIME64 =  4_611_669_811_199 (year 148107-12-31T23:59:59)
    const DATETIME64_EPOCH_TO_9999_12_31_END_SECS: u64 =
        DATE32_EPOCH_TO_9999_12_31_SECS + 23 * 3600 + 59 * 60 + 59;
    const DATETIME64_MAX: u64 = 4_611_669_811_199;
    const DATETIME64_MIN_ABS: u64 = 4_611_669_897_600;
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH),
        "1970-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH + Duration::from_secs(1_705_320_645)),
        "2024-01-15T12:10:45Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH - Duration::from_secs(1)),
        "1969-12-31T23:59:59Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
        "1970-01-01T00:00:01Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(
            SystemTime::UNIX_EPOCH + Duration::from_secs(DATETIME64_EPOCH_TO_9999_12_31_END_SECS),
        ),
        "9999-12-31T23:59:59Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(
            SystemTime::UNIX_EPOCH - Duration::from_secs(DATE32_0001_01_01_TO_EPOCH_SECS),
        ),
        "1-01-01T00:00:00Z",
    ));
    // Server extreme bounds (MIN_DATETIME64 / MAX_DATETIME64)
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH - Duration::from_secs(DATETIME64_MIN_ABS)),
        "-144169-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Datetime64",
        Value::Datetime64(SystemTime::UNIX_EPOCH + Duration::from_secs(DATETIME64_MAX)),
        "148107-12-31T23:59:59Z",
    ));

    // ---- Timestamp64 (signed microseconds from epoch) ----
    // YDB Timestamp64 range per `udf_data_type.h`:
    //   MIN_TIMESTAMP64 = -4_611_669_897_600_000_000 (year -144169-01-01T00:00:00.000000)
    //   MAX_TIMESTAMP64 =  4_611_669_811_199_999_999 (year 148107-12-31T23:59:59.999999)
    const TIMESTAMP64_EPOCH_TO_9999_12_31_END_MICROS: u64 =
        DATETIME64_EPOCH_TO_9999_12_31_END_SECS * 1_000_000 + 999_999;
    const TIMESTAMP64_0001_01_01_TO_EPOCH_MICROS: u64 = DATE32_0001_01_01_TO_EPOCH_SECS * 1_000_000;
    const TIMESTAMP64_MAX: u64 = 4_611_669_811_199_999_999;
    const TIMESTAMP64_MIN_ABS: u64 = 4_611_669_897_600_000_000;
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH),
        "1970-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH + Duration::from_micros(1)),
        "1970-01-01T00:00:00.000001Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH + Duration::from_micros(1_705_320_645_123_456)),
        "2024-01-15T12:10:45.123456Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH - Duration::from_micros(1)),
        "1969-12-31T23:59:59.999999Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(
            SystemTime::UNIX_EPOCH
                + Duration::from_micros(TIMESTAMP64_EPOCH_TO_9999_12_31_END_MICROS),
        ),
        "9999-12-31T23:59:59.999999Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(
            SystemTime::UNIX_EPOCH - Duration::from_micros(TIMESTAMP64_0001_01_01_TO_EPOCH_MICROS),
        ),
        "1-01-01T00:00:00Z",
    ));
    // Server extreme bounds (MIN_TIMESTAMP64 / MAX_TIMESTAMP64)
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH - Duration::from_micros(TIMESTAMP64_MIN_ABS)),
        "-144169-01-01T00:00:00Z",
    ));
    cases.push(TypeCase::new(
        "Timestamp64",
        Value::Timestamp64(SystemTime::UNIX_EPOCH + Duration::from_micros(TIMESTAMP64_MAX)),
        "148107-12-31T23:59:59.999999Z",
    ));

    // ---- Interval64 (signed microsecond duration) ----
    // YDB Interval64 range per `udf_data_type.h`:
    //   MAX_INTERVAL64 = MAX_TIMESTAMP64 - MIN_TIMESTAMP64 = 9_223_339_708_799_999_999 µs
    //   (≈ ±292 270 years). Range: [-MAX_INTERVAL64, +MAX_INTERVAL64] inclusive.
    const INTERVAL64_MAX: u64 = 9_223_339_708_799_999_999;
    // YDB CAST(Interval64 AS Utf8) produces an ISO-8601 duration string.
    // Values taken from the Go SDK integration tests are used as a known-good
    // reference. Boundaries: ±1 microsecond, ±(1 second − 1 microsecond),
    // and ±(1 day − 1 microsecond) — the largest sub-day interval fitting
    // a predictable H/M/S format.
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(19_845_000_123),
        }),
        "PT5H30M45.000123S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(8_130_000_000),
        }),
        "-PT2H15M30S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(27_930_999_999),
        }),
        "PT7H45M30.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(1),
        }),
        "PT0.000001S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(1),
        }),
        "-PT0.000001S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(999_999),
        }),
        "PT0.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(999_999),
        }),
        "-PT0.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(86_399_999_999),
        }),
        "PT23H59M59.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(86_399_999_999),
        }),
        "-PT23H59M59.999999S",
    ));
    // Server extreme bounds (±MAX_INTERVAL64). Expected text is derived from the
    // ISO-8601 duration format. Fill in once the server returns the canonical form.
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Plus,
            duration: Duration::from_micros(INTERVAL64_MAX),
        }),
        "P106751616DT23H59M59.999999S",
    ));
    cases.push(TypeCase::new(
        "Interval64",
        Value::Interval64(SignedInterval {
            sign: Sign::Minus,
            duration: Duration::from_micros(INTERVAL64_MAX),
        }),
        "-P106751616DT23H59M59.999999S",
    ));

    // ---- Utf8 (Text) / String (Bytes) ----
    // Empty, ASCII, multi-byte UTF-8, special chars (newline/tab/quote).
    for s in ["", "hello", "привет", "a\nb", "a\tb", "a\"b"] {
        cases.push(TypeCase::new("Utf8", Value::Text(s.into()), s));
        cases.push(TypeCase::new("String", Value::Bytes(Bytes::from(s)), s));
    }

    // ---- Json (preserves text as-is) ----
    for s in [
        "null",
        "true",
        "false",
        "0",
        "-1",
        r#""hello""#,
        "[]",
        "[1,2,3]",
        "{}",
        r#"{"a":1}"#,
        r#"{"a":[1,2,{"b":"c"}]}"#,
    ] {
        cases.push(TypeCase::new("Json", Value::Json(s.into()), s));
    }

    // ---- JsonDocument (server canonicalizes; we use already-canonical form) ----
    for s in [
        "null",
        "true",
        "false",
        "0",
        "-1",
        r#""hello""#,
        "[]",
        "[1,2,3]",
        "{}",
        r#"{"a":1}"#,
        r#"{"a":[1,2,{"b":"c"}]}"#,
    ] {
        cases.push(TypeCase::new(
            "JsonDocument",
            Value::JsonDocument(s.into()),
            s,
        ));
    }

    // Yson is intentionally NOT covered here: YDB does not implement
    // `CAST(Yson AS Utf8)` / `CAST(Utf8 AS Yson)` (the engine reports
    // "Cannot cast type Yson into Utf8"), so the Utf8-bridged round-trip
    // pattern used by this test does not apply. Yson↔Text conversions
    // would have to go through `Yson::SerializeText` / `Yson::Parse`.

    // ---- Uuid ----
    // Fixed values only — random UUIDs would make test failures non-reproducible.
    // Includes the magnitude edges (nil, max) and synthetic v4-/v7-shaped values
    // that match what `Uuid::new_v4()` / `Uuid::now_v7()` would produce structurally.
    for u in [
        Uuid::nil(),                                         // all-zero
        Uuid::from_u128(u128::MAX),                          // all-ones
        Uuid::from_u128(0x1234567890abcdef1234567890abcdef), // arbitrary fixed
        Uuid::parse_str("12345678-1234-4abc-89ab-1234567890ab").expect("v4-shaped uuid"), // version=4 nibble, variant=10
        Uuid::parse_str("12345678-1234-7abc-89ab-1234567890ab").expect("v7-shaped uuid"), // version=7 nibble, variant=10
    ] {
        let text = u.to_string();
        cases.push(TypeCase::new("Uuid", Value::Uuid(u), text));
    }

    // ---- Decimal(p, s) ----
    let decimal_specs: &[(u32, u32, &[&str])] = &[
        // canonical YDB Decimal
        (
            22,
            9,
            &[
                "0",
                "1",
                "-1",
                "0.000000001",
                "-0.000000001",
                "9999999999999.999999999",
                "-9999999999999.999999999",
            ],
        ),
        // max precision, integer only
        (
            35,
            0,
            &[
                "0",
                "1",
                "-1",
                "99999999999999999999999999999999999",
                "-99999999999999999999999999999999999",
            ],
        ),
        // max precision, mixed
        (
            35,
            17,
            &[
                "0",
                "1",
                "-1",
                "0.00000000000000001",
                "-0.00000000000000001",
                "999999999999999999.99999999999999999",
                "-999999999999999999.99999999999999999",
            ],
        ),
        // max precision, fractional only; |x| < 1
        (
            35,
            35,
            &[
                "0",
                "0.00000000000000000000000000000000001",
                "-0.00000000000000000000000000000000001",
                "0.99999999999999999999999999999999999",
                "-0.99999999999999999999999999999999999",
            ],
        ),
    ];
    for (precision, scale, values) in decimal_specs {
        for raw in *values {
            let parsed: decimal_rs::Decimal = raw
                .parse()
                .unwrap_or_else(|e| panic!("parse decimal {raw:?}: {e}"));
            let ydb_dec = YdbDecimal::try_new(parsed, *precision, *scale).unwrap_or_else(|e| {
                panic!("YdbDecimal::try_new({raw:?}, {precision}, {scale}): {e}")
            });
            let text = ydb_dec.to_string();
            let yql_type = format!("Decimal({precision}, {scale})");
            cases.push(TypeCase::new(yql_type, Value::Decimal(ydb_dec), text));
        }
    }

    cases
}

/// Verifies three independent round-trips for a single case:
///
/// 1. `Value → server (no cast) → Value` — wire-format round-trip.
/// 2. `Value → CAST AS Utf8 → string` — server sees the value as the
///    expected text.
/// 3. `Text → CAST AS yql_type → Value` — server parses the text into
///    the expected value.
async fn check_type_roundtrip(client: &Client, case: &TypeCase) -> YdbResult<()> {
    // --- 1) Value → server (no cast) → Value ---
    let q1 = format!(
        "\
declare $val AS {t};
select $val AS db_result",
        t = case.yql_type,
    );
    let recv_passthrough = client
        .table_client()
        .retry_transaction(|mut t| {
            let q = q1.clone();
            let v = case.value.clone();
            async move {
                let res = t
                    .query(Query::new(q).with_params(ydb_params! {
                        "$val" => v,
                    }))
                    .await?;
                let mut row = res.into_only_row()?;
                Ok(row.remove_field_by_name("db_result")?)
            }
        })
        .await?;
    let inner_passthrough = unwrap_optional(recv_passthrough, &case.yql_type, &case.text)?;
    assert!(
        value_roundtrip_eq(&case.value, &inner_passthrough),
        "Value→Value mismatch for case {case:?}: got {inner_passthrough:?}",
    );

    // --- 2) Value → CAST AS Utf8 → string ---
    let q2 = format!(
        "\
declare $val AS {t};
select cast(cast($val AS {t}) AS Utf8) AS db_result",
        t = case.yql_type,
    );
    let (db_text,): (Option<String>,) = client
        .table_client()
        .retry_transaction(|mut t| {
            let q = q2.clone();
            let v = case.value.clone();
            async move {
                let res = t
                    .query(Query::new(q).with_params(ydb_params! {
                        "$val" => v,
                    }))
                    .await?;
                let mut row = res.into_only_row()?;
                let v: Option<String> = row.remove_field_by_name("db_result")?.try_into()?;
                Ok((v,))
            }
        })
        .await?;
    assert_eq!(
        Some(case.text.clone()),
        db_text,
        "Value→Utf8 mismatch for case {case:?}",
    );

    // --- 3) Text → CAST AS yql_type → Value ---
    let q3 = format!(
        "\
declare $val AS Text;
select cast($val AS {t}) AS db_result",
        t = case.yql_type,
    );
    let recv_parsed = client
        .table_client()
        .retry_transaction(|mut t| {
            let q = q3.clone();
            let s = case.text.clone();
            async move {
                let res = t
                    .query(Query::new(q).with_params(ydb_params! {
                        "$val" => s,
                    }))
                    .await?;
                let mut row = res.into_only_row()?;
                Ok(row.remove_field_by_name("db_result")?)
            }
        })
        .await?;
    let inner_parsed = unwrap_optional(recv_parsed, &case.yql_type, &case.text)?;
    assert!(
        value_roundtrip_eq(&case.value, &inner_parsed),
        "Text→{} mismatch for case {case:?}: got {inner_parsed:?}",
        case.yql_type,
    );

    Ok(())
}

fn unwrap_optional(v: Value, yql_type: &str, text: &str) -> YdbResult<Value> {
    match v {
        Value::Optional(opt) => opt
            .value
            .ok_or_else(|| YdbError::Custom(format!("got NULL for {yql_type} from text {text:?}"))),
        other => Ok(other),
    }
}

/// Value equality that treats NaN as equal to NaN (PartialEq says they aren't).
fn value_roundtrip_eq(expected: &Value, actual: &Value) -> bool {
    match (expected, actual) {
        (Value::Float(e), Value::Float(a)) if e.is_nan() => a.is_nan(),
        (Value::Double(e), Value::Double(a)) if e.is_nan() => a.is_nan(),
        _ => expected == actual,
    }
}

#[tokio::test]
#[ignore = "needs YDB access"]
async fn test_type_serialization() -> YdbResult<()> {
    let client = test_client_builder().client()?;
    client.wait().await?;

    for case in type_cases() {
        check_type_roundtrip(&client, &case).await?;
    }
    Ok(())
}