scylla-cql 1.3.0

CQL data types and primitives, for interacting with Scylla.
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
use assert_matches::assert_matches;
use bytes::Bytes;
use scylla_macros::DeserializeRow;

use crate::deserialize::row::BuiltinDeserializationErrorKind;
use crate::deserialize::{value, DeserializationError, FrameSlice};
use crate::frame::response::result::{ColumnSpec, ColumnType, NativeType, TableSpec};

use super::super::tests::{serialize_cells, spec};
use super::{BuiltinDeserializationError, ColumnIterator, CqlValue, DeserializeRow, Row};
use super::{BuiltinTypeCheckError, BuiltinTypeCheckErrorKind};

#[test]
fn test_tuple_deserialization() {
    // Empty tuple
    deserialize::<()>(&[], &Bytes::new()).unwrap();

    // 1-elem tuple
    let (a,) = deserialize::<(i32,)>(
        &[spec("i", ColumnType::Native(NativeType::Int))],
        &serialize_cells([val_int(123)]),
    )
    .unwrap();
    assert_eq!(a, 123);

    // 3-elem tuple
    let (a, b, c) = deserialize::<(i32, i32, i32)>(
        &[
            spec("i1", ColumnType::Native(NativeType::Int)),
            spec("i2", ColumnType::Native(NativeType::Int)),
            spec("i3", ColumnType::Native(NativeType::Int)),
        ],
        &serialize_cells([val_int(123), val_int(456), val_int(789)]),
    )
    .unwrap();
    assert_eq!((a, b, c), (123, 456, 789));

    // Make sure that column type mismatch is detected
    deserialize::<(i32, String, i32)>(
        &[
            spec("i1", ColumnType::Native(NativeType::Int)),
            spec("i2", ColumnType::Native(NativeType::Int)),
            spec("i3", ColumnType::Native(NativeType::Int)),
        ],
        &serialize_cells([val_int(123), val_int(456), val_int(789)]),
    )
    .unwrap_err();

    // Make sure that borrowing types compile and work correctly
    let specs = &[spec("s", ColumnType::Native(NativeType::Text))];
    let byts = serialize_cells([val_str("abc")]);
    let (s,) = deserialize::<(&str,)>(specs, &byts).unwrap();
    assert_eq!(s, "abc");
}

#[test]
fn test_deserialization_as_column_iterator() {
    let col_specs = [
        spec("i1", ColumnType::Native(NativeType::Int)),
        spec("i2", ColumnType::Native(NativeType::Text)),
        spec("i3", ColumnType::Native(NativeType::Counter)),
    ];
    let serialized_values = serialize_cells([val_int(123), val_str("ScyllaDB"), None]);
    let mut iter = deserialize::<ColumnIterator>(&col_specs, &serialized_values).unwrap();

    let col1 = iter.next().unwrap().unwrap();
    assert_eq!(col1.spec.name(), "i1");
    assert_eq!(col1.spec.typ(), &ColumnType::Native(NativeType::Int));
    assert_eq!(col1.slice.unwrap().as_slice(), &123i32.to_be_bytes());

    let col2 = iter.next().unwrap().unwrap();
    assert_eq!(col2.spec.name(), "i2");
    assert_eq!(col2.spec.typ(), &ColumnType::Native(NativeType::Text));
    assert_eq!(col2.slice.unwrap().as_slice(), "ScyllaDB".as_bytes());

    let col3 = iter.next().unwrap().unwrap();
    assert_eq!(col3.spec.name(), "i3");
    assert_eq!(col3.spec.typ(), &ColumnType::Native(NativeType::Counter));
    assert!(col3.slice.is_none());

    assert!(iter.next().is_none());
}

// Do not remove. It's not used in tests but we keep it here to check that
// we properly ignore warnings about unused variables, unnecessary `mut`s
// etc. that usually pop up when generating code for empty structs.
#[derive(DeserializeRow)]
#[scylla(crate = crate)]
struct TestUdtWithNoFieldsUnordered {}

#[derive(DeserializeRow)]
#[scylla(crate = crate, flavor = "enforce_order")]
struct TestUdtWithNoFieldsOrdered {}

#[test]
fn test_struct_deserialization_loose_ordering() {
    #[derive(DeserializeRow, PartialEq, Eq, Debug)]
    #[scylla(crate = "crate")]
    struct MyRow<'a> {
        a: &'a str,
        b: Option<i32>,
        #[scylla(skip)]
        c: String,
    }

    // Original order of columns
    let specs = &[
        spec("a", ColumnType::Native(NativeType::Text)),
        spec("b", ColumnType::Native(NativeType::Int)),
    ];
    let byts = serialize_cells([val_str("abc"), val_int(123)]);
    let row = deserialize::<MyRow<'_>>(specs, &byts).unwrap();
    assert_eq!(
        row,
        MyRow {
            a: "abc",
            b: Some(123),
            c: String::new(),
        }
    );

    // Different order of columns - should still work
    let specs = &[
        spec("b", ColumnType::Native(NativeType::Int)),
        spec("a", ColumnType::Native(NativeType::Text)),
    ];
    let byts = serialize_cells([val_int(123), val_str("abc")]);
    let row = deserialize::<MyRow<'_>>(specs, &byts).unwrap();
    assert_eq!(
        row,
        MyRow {
            a: "abc",
            b: Some(123),
            c: String::new(),
        }
    );

    // Missing column
    let specs = &[spec("a", ColumnType::Native(NativeType::Text))];
    MyRow::type_check(specs).unwrap_err();

    // Wrong column type
    let specs = &[
        spec("a", ColumnType::Native(NativeType::Int)),
        spec("b", ColumnType::Native(NativeType::Int)),
    ];
    MyRow::type_check(specs).unwrap_err();
}

#[test]
fn test_struct_deserialization_strict_ordering() {
    #[derive(DeserializeRow, PartialEq, Eq, Debug)]
    #[scylla(crate = "crate", flavor = "enforce_order")]
    struct MyRow<'a> {
        a: &'a str,
        b: Option<i32>,
        #[scylla(skip)]
        c: String,
    }

    // Correct order of columns
    let specs = &[
        spec("a", ColumnType::Native(NativeType::Text)),
        spec("b", ColumnType::Native(NativeType::Int)),
    ];
    let byts = serialize_cells([val_str("abc"), val_int(123)]);
    let row = deserialize::<MyRow<'_>>(specs, &byts).unwrap();
    assert_eq!(
        row,
        MyRow {
            a: "abc",
            b: Some(123),
            c: String::new(),
        }
    );

    // Wrong order of columns
    let specs = &[
        spec("b", ColumnType::Native(NativeType::Int)),
        spec("a", ColumnType::Native(NativeType::Text)),
    ];
    MyRow::type_check(specs).unwrap_err();

    // Missing column
    let specs = &[spec("a", ColumnType::Native(NativeType::Text))];
    MyRow::type_check(specs).unwrap_err();

    // Wrong column type
    let specs = &[
        spec("a", ColumnType::Native(NativeType::Int)),
        spec("b", ColumnType::Native(NativeType::Int)),
    ];
    MyRow::type_check(specs).unwrap_err();
}

#[test]
fn test_struct_deserialization_no_name_check() {
    #[derive(DeserializeRow, PartialEq, Eq, Debug)]
    #[scylla(crate = "crate", flavor = "enforce_order", skip_name_checks)]
    struct MyRow<'a> {
        a: &'a str,
        b: Option<i32>,
        #[scylla(skip)]
        c: String,
    }

    // Correct order of columns
    let specs = &[
        spec("a", ColumnType::Native(NativeType::Text)),
        spec("b", ColumnType::Native(NativeType::Int)),
    ];
    let byts = serialize_cells([val_str("abc"), val_int(123)]);
    let row = deserialize::<MyRow<'_>>(specs, &byts).unwrap();
    assert_eq!(
        row,
        MyRow {
            a: "abc",
            b: Some(123),
            c: String::new(),
        }
    );

    // Correct order of columns, but different names - should still succeed
    let specs = &[
        spec("z", ColumnType::Native(NativeType::Text)),
        spec("x", ColumnType::Native(NativeType::Int)),
    ];
    let byts = serialize_cells([val_str("abc"), val_int(123)]);
    let row = deserialize::<MyRow<'_>>(specs, &byts).unwrap();
    assert_eq!(
        row,
        MyRow {
            a: "abc",
            b: Some(123),
            c: String::new(),
        }
    );
}

#[test]
fn test_struct_deserialization_cross_rename_fields() {
    #[derive(scylla_macros::DeserializeRow, PartialEq, Eq, Debug)]
    #[scylla(crate = crate)]
    struct TestRow {
        #[scylla(rename = "b")]
        a: i32,
        #[scylla(rename = "a")]
        b: String,
    }

    // Columns switched wrt fields - should still work.
    {
        let row_bytes =
            serialize_cells(["The quick brown fox".as_bytes(), &42_i32.to_be_bytes()].map(Some));
        let specs = [
            spec("a", ColumnType::Native(NativeType::Text)),
            spec("b", ColumnType::Native(NativeType::Int)),
        ];

        let row = deserialize::<TestRow>(&specs, &row_bytes).unwrap();
        assert_eq!(
            row,
            TestRow {
                a: 42,
                b: "The quick brown fox".to_owned(),
            }
        );
    }
}

fn val_int(i: i32) -> Option<Vec<u8>> {
    Some(i.to_be_bytes().to_vec())
}

fn val_str(s: &str) -> Option<Vec<u8>> {
    Some(s.as_bytes().to_vec())
}

pub(crate) fn deserialize<'frame, 'metadata, R>(
    specs: &'metadata [ColumnSpec<'metadata>],
    byts: &'frame Bytes,
) -> Result<R, DeserializationError>
where
    R: DeserializeRow<'frame, 'metadata>,
{
    <R as DeserializeRow<'frame, 'metadata>>::type_check(specs)
        .map_err(|typecheck_err| DeserializationError(typecheck_err.0))?;
    let slice = FrameSlice::new(byts);
    let iter = ColumnIterator::new(specs, slice);
    <R as DeserializeRow<'frame, 'metadata>>::deserialize(iter)
}

#[track_caller]
pub(crate) fn get_typck_err_inner<'a>(
    err: &'a (dyn std::error::Error + 'static),
) -> &'a BuiltinTypeCheckError {
    match err.downcast_ref() {
        Some(err) => err,
        None => panic!("not a BuiltinTypeCheckError: {err:?}"),
    }
}

#[track_caller]
fn get_typck_err(err: &DeserializationError) -> &BuiltinTypeCheckError {
    get_typck_err_inner(err.0.as_ref())
}

#[track_caller]
fn get_deser_err(err: &DeserializationError) -> &BuiltinDeserializationError {
    match err.0.downcast_ref() {
        Some(err) => err,
        None => panic!("not a BuiltinDeserializationError: {err:?}"),
    }
}

#[test]
fn test_tuple_errors() {
    // Column type check failure
    {
        let col_name: &str = "i";
        let specs = &[spec(col_name, ColumnType::Native(NativeType::Int))];
        let err = deserialize::<(i64,)>(specs, &serialize_cells([val_int(123)])).unwrap_err();
        let err = get_typck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i64,)>());
        assert_eq!(
            err.cql_types,
            specs
                .iter()
                .map(|spec| spec.typ().clone())
                .collect::<Vec<_>>()
        );
        let BuiltinTypeCheckErrorKind::ColumnTypeCheckFailed {
            column_index,
            column_name,
            err,
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(*column_index, 0);
        assert_eq!(column_name, col_name);
        let err = super::super::value::tests::get_typeck_err_inner(err.0.as_ref());
        assert_eq!(err.rust_name, std::any::type_name::<i64>());
        assert_eq!(err.cql_type, ColumnType::Native(NativeType::Int));
        assert_matches!(
            &err.kind,
            super::super::value::BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Native(NativeType::BigInt)]
            }
        );
    }

    // Column deserialization failure
    {
        let col_name: &str = "i";
        let err = deserialize::<(i64,)>(
            &[spec(col_name, ColumnType::Native(NativeType::BigInt))],
            &serialize_cells([val_int(123)]),
        )
        .unwrap_err();
        let err = get_deser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i64,)>());
        let BuiltinDeserializationErrorKind::ColumnDeserializationFailed {
            column_name, err, ..
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(column_name, col_name);
        let err = super::super::value::tests::get_deser_err(err);
        assert_eq!(err.rust_name, std::any::type_name::<i64>());
        assert_eq!(err.cql_type, ColumnType::Native(NativeType::BigInt));
        assert_matches!(
            err.kind,
            super::super::value::BuiltinDeserializationErrorKind::ByteLengthMismatch {
                expected: 8,
                got: 4
            }
        );
    }

    // Raw column deserialization failure
    {
        let col_name: &str = "i";
        let err = deserialize::<(i64,)>(
            &[spec(col_name, ColumnType::Native(NativeType::BigInt))],
            &Bytes::from_static(b"alamakota"),
        )
        .unwrap_err();
        let err = get_deser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i64,)>());
        let BuiltinDeserializationErrorKind::RawColumnDeserializationFailed {
            column_index: _column_index,
            column_name,
            err: _err,
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(column_name, col_name);
    }
}

#[test]
fn test_row_errors() {
    // Column type check failure - happens never, because Row consists of CqlValues,
    // which accept all CQL types.

    // Column deserialization failure
    {
        let col_name: &str = "i";
        let err = deserialize::<Row>(
            &[spec(col_name, ColumnType::Native(NativeType::BigInt))],
            &serialize_cells([val_int(123)]),
        )
        .unwrap_err();
        let err = get_deser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<Row>());
        let BuiltinDeserializationErrorKind::ColumnDeserializationFailed {
            column_index: _column_index,
            column_name,
            err,
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(column_name, col_name);
        let err = super::super::value::tests::get_deser_err(err);
        assert_eq!(err.rust_name, std::any::type_name::<Option<CqlValue>>());
        assert_eq!(err.cql_type, ColumnType::Native(NativeType::BigInt));
        let super::super::value::BuiltinDeserializationErrorKind::ByteLengthMismatch {
            expected: 8,
            got: 4,
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
    }

    // Raw column deserialization failure
    {
        let col_name: &str = "i";
        let err = deserialize::<Row>(
            &[spec(col_name, ColumnType::Native(NativeType::BigInt))],
            &Bytes::from_static(b"alamakota"),
        )
        .unwrap_err();
        let err = get_deser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<Row>());
        let BuiltinDeserializationErrorKind::RawColumnDeserializationFailed {
            column_index: _column_index,
            column_name,
            err: _err,
        } = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(column_name, col_name);
    }
}

fn specs_to_types<'a>(specs: &[ColumnSpec<'a>]) -> Vec<ColumnType<'a>> {
    specs.iter().map(|spec| spec.typ().clone()).collect()
}

#[test]
fn test_struct_deserialization_errors() {
    // Loose ordering
    {
        #[derive(scylla_macros::DeserializeRow, PartialEq, Eq, Debug)]
        #[scylla(crate = "crate")]
        struct MyRow<'a> {
            a: &'a str,
            #[scylla(skip)]
            x: String,
            b: Option<i32>,
            #[scylla(rename = "c")]
            d: bool,
        }

        // Type check errors
        {
            // Missing column
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Ascii)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::ValuesMissingForColumns {
                    column_names: ref missing_fields,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(missing_fields.as_slice(), &["c"]);
            }

            // Duplicated column
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Ascii)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("a", ColumnType::Native(NativeType::Ascii)),
                ];

                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::DuplicatedColumn {
                    column_index,
                    column_name,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 2);
                assert_eq!(column_name, "a");
            }

            // Unknown column
            {
                let specs = [
                    spec("d", ColumnType::Native(NativeType::Counter)),
                    spec("a", ColumnType::Native(NativeType::Ascii)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                ];

                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::ColumnWithUnknownName {
                    column_index,
                    ref column_name,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 0);
                assert_eq!(column_name.as_str(), "d");
            }

            // Column incompatible types - column type check failed
            {
                let specs = [
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("a", ColumnType::Native(NativeType::Blob)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::ColumnTypeCheckFailed {
                    column_index,
                    ref column_name,
                    ref err,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 1);
                assert_eq!(column_name.as_str(), "a");
                let err = value::tests::get_typeck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<&str>());
                assert_eq!(err.cql_type, ColumnType::Native(NativeType::Blob));
                assert_matches!(
                    err.kind,
                    value::BuiltinTypeCheckErrorKind::MismatchedType {
                        expected: &[
                            ColumnType::Native(NativeType::Ascii),
                            ColumnType::Native(NativeType::Text)
                        ]
                    }
                );
            }
        }

        // Deserialization errors
        {
            // Got null
            {
                let specs = [
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                    spec("a", ColumnType::Native(NativeType::Blob)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                ];

                let err = MyRow::deserialize(ColumnIterator::new(
                    &specs,
                    FrameSlice::new(&serialize_cells([Some([true as u8])])),
                ))
                .unwrap_err();
                let err = get_deser_err(&err);
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinDeserializationErrorKind::RawColumnDeserializationFailed {
                    column_index,
                    ref column_name,
                    ..
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 1);
                assert_eq!(column_name, "a");
            }

            // Column deserialization failed
            {
                let specs = [
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("a", ColumnType::Native(NativeType::Ascii)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];

                let row_bytes = serialize_cells(
                    [
                        &0_i32.to_be_bytes(),
                        "alamakota".as_bytes(),
                        &42_i16.to_be_bytes(),
                    ]
                    .map(Some),
                );

                let err = deserialize::<MyRow>(&specs, &row_bytes).unwrap_err();

                let err = get_deser_err(&err);
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinDeserializationErrorKind::ColumnDeserializationFailed {
                    column_index,
                    ref column_name,
                    ref err,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 2);
                assert_eq!(column_name.as_str(), "c");
                let err = value::tests::get_deser_err(err);
                assert_eq!(err.rust_name, std::any::type_name::<bool>());
                assert_eq!(err.cql_type, ColumnType::Native(NativeType::Boolean));
                assert_matches!(
                    err.kind,
                    value::BuiltinDeserializationErrorKind::ByteLengthMismatch {
                        expected: 1,
                        got: 2,
                    }
                );
            }
        }
    }

    // Strict ordering
    {
        #[derive(scylla_macros::DeserializeRow, PartialEq, Eq, Debug)]
        #[scylla(crate = "crate", flavor = "enforce_order")]
        struct MyRow<'a> {
            a: &'a str,
            #[scylla(skip)]
            x: String,
            b: Option<i32>,
            c: bool,
        }

        // Type check errors
        {
            // Too few columns
            {
                let specs = [spec("a", ColumnType::Native(NativeType::Text))];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::WrongColumnCount {
                    rust_cols,
                    cql_cols,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(rust_cols, 3);
                assert_eq!(cql_cols, 1);
            }

            // Excess columns
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                    spec("d", ColumnType::Native(NativeType::Counter)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::WrongColumnCount {
                    rust_cols,
                    cql_cols,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(rust_cols, 3);
                assert_eq!(cql_cols, 4);
            }

            // Renamed column name mismatch
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("d", ColumnType::Native(NativeType::Boolean)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinTypeCheckErrorKind::ColumnNameMismatch {
                    field_index,
                    column_index,
                    rust_column_name,
                    ref db_column_name,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(field_index, 3);
                assert_eq!(rust_column_name, "c");
                assert_eq!(column_index, 2);
                assert_eq!(db_column_name.as_str(), "d");
            }

            // Columns switched - column name mismatch
            {
                let specs = [
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::ColumnNameMismatch {
                    field_index,
                    column_index,
                    rust_column_name,
                    ref db_column_name,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(field_index, 0);
                assert_eq!(column_index, 0);
                assert_eq!(rust_column_name, "a");
                assert_eq!(db_column_name.as_str(), "b");
            }

            // Column incompatible types - column type check failed
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Blob)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];
                let err = MyRow::type_check(&specs).unwrap_err();
                let err = get_typck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                assert_eq!(err.cql_types, specs_to_types(&specs));
                let BuiltinTypeCheckErrorKind::ColumnTypeCheckFailed {
                    column_index,
                    ref column_name,
                    ref err,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 0);
                assert_eq!(column_name.as_str(), "a");
                let err = value::tests::get_typeck_err_inner(err.0.as_ref());
                assert_eq!(err.rust_name, std::any::type_name::<&str>());
                assert_eq!(err.cql_type, ColumnType::Native(NativeType::Blob));
                assert_matches!(
                    err.kind,
                    value::BuiltinTypeCheckErrorKind::MismatchedType {
                        expected: &[
                            ColumnType::Native(NativeType::Ascii),
                            ColumnType::Native(NativeType::Text)
                        ]
                    }
                );
            }
        }

        // Deserialization errors
        {
            // Too few columns
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];

                let err = MyRow::deserialize(ColumnIterator::new(
                    &specs,
                    FrameSlice::new(&serialize_cells([Some([true as u8])])),
                ))
                .unwrap_err();
                let err = get_deser_err(&err);
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinDeserializationErrorKind::RawColumnDeserializationFailed {
                    column_index,
                    ref column_name,
                    ..
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 1);
                assert_eq!(column_name, "b");
            }

            // Bad field format
            {
                let typ = [
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];

                let row_bytes = serialize_cells(
                    [(&b"alamakota"[..]), &42_i32.to_be_bytes(), &[true as u8]].map(Some),
                );

                let row_bytes_too_short = row_bytes.slice(..row_bytes.len() - 1);
                assert!(row_bytes.len() > row_bytes_too_short.len());

                let err = deserialize::<MyRow>(&typ, &row_bytes_too_short).unwrap_err();

                let err = get_deser_err(&err);
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinDeserializationErrorKind::RawColumnDeserializationFailed {
                    column_index,
                    ref column_name,
                    ..
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_index, 2);
                assert_eq!(column_name, "c");
            }

            // Column deserialization failed
            {
                let specs = [
                    spec("a", ColumnType::Native(NativeType::Text)),
                    spec("b", ColumnType::Native(NativeType::Int)),
                    spec("c", ColumnType::Native(NativeType::Boolean)),
                ];

                let row_bytes = serialize_cells(
                    [&b"alamakota"[..], &42_i64.to_be_bytes(), &[true as u8]].map(Some),
                );

                let err = deserialize::<MyRow>(&specs, &row_bytes).unwrap_err();

                let err = get_deser_err(&err);
                assert_eq!(err.rust_name, std::any::type_name::<MyRow>());
                let BuiltinDeserializationErrorKind::ColumnDeserializationFailed {
                    column_index: field_index,
                    ref column_name,
                    ref err,
                } = err.kind
                else {
                    panic!("unexpected error kind: {:?}", err.kind)
                };
                assert_eq!(column_name.as_str(), "b");
                assert_eq!(field_index, 2);
                let err = value::tests::get_deser_err(err);
                assert_eq!(err.rust_name, std::any::type_name::<Option<i32>>());
                assert_eq!(err.cql_type, ColumnType::Native(NativeType::Int));
                assert_matches!(
                    err.kind,
                    value::BuiltinDeserializationErrorKind::ByteLengthMismatch {
                        expected: 4,
                        got: 8,
                    }
                );
            }
        }
    }
}

#[test]
fn metadata_does_not_bound_deserialized_rows() {
    /* It's important to understand what is a _deserialized row_. It's not just
     * an implementor of `DeserializeRow`; there are some implementors of `DeserializeRow`
     * who are not yet final rows, but partially deserialized rows that support further
     * deserialization - _row deserializers_, such as `ColumnIterator`.
     * _Row deserializers_, because they still need to deserialize some row, are naturally
     * bound by 'metadata lifetime. However, _rows_ are completely deserialized, so they
     * should not be bound by 'metadata - only by 'frame. This test asserts that.
     */

    // We don't care about the actual deserialized data - all `Err`s is OK.
    // This test's goal is only to compile, asserting that lifetimes are correct.
    let bytes = Bytes::new();

    // By this binding, we require that the deserialized rows live longer than metadata.
    let _decoded_results = {
        // Metadata's lifetime is limited to this scope.

        fn col_spec<'a>(name: &'a str, typ: ColumnType<'a>) -> ColumnSpec<'a> {
            ColumnSpec::borrowed(name, typ, TableSpec::borrowed("ks", "tbl"))
        }

        let row_typ = &[
            col_spec("bytes", ColumnType::Native(NativeType::Blob)),
            col_spec("text", ColumnType::Native(NativeType::Text)),
        ];

        // Tuple
        let decoded_tuple_res = deserialize::<(&[u8], &str)>(row_typ, &bytes);

        // Custom struct
        #[derive(DeserializeRow)]
        #[scylla(crate=crate)]
        struct MyRow<'frame> {
            #[expect(dead_code)]
            bytes: &'frame [u8],
            #[expect(dead_code)]
            text: &'frame str,
        }
        let decoded_custom_struct_res = deserialize::<MyRow>(row_typ, &bytes);

        (decoded_tuple_res, decoded_custom_struct_res)
    };
}