cqlite-core 0.13.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally without a cluster
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
//! Delta-scan Arrow schema derivation (Epic #696, Issue #703).
//!
//! Derives the Arrow envelope schema from a [`TableSchema`] for CDC-style
//! Parquet projections of individual SSTable generations.
//!
//! ## Schema layout
//!
//! For a table `t (pk int, ck text, val text, st text STATIC, PRIMARY KEY (pk, ck))`:
//!
//! ```text
//! pk          : Int32               -- partition key, plain type
//! ck          : Utf8                -- clustering key, plain type (null on partition/static ops)
//! val         : Struct(nullable) {  -- regular column cell struct
//!                 value:      Utf8,
//!                 writetime:  Int64,
//!                 expires_at: Int64 (nullable),
//!               }
//! st          : Struct(nullable) {  -- static column cell struct (no `replaced`)
//!                 value:      Utf8,
//!                 writetime:  Int64,
//!                 expires_at: Int64 (nullable),
//!               }
//! __op        : Dictionary(Int8, Utf8)   -- op discriminator, dictionary-encoded
//! __ts        : Int64 (nullable)         -- deletion/liveness timestamp
//! __range_start : Struct(nullable) {    -- range-delete lower bound
//!                   ck:         Utf8,
//!                   inclusive:  Boolean,
//!                 }
//! __range_end   : Struct(nullable) {    -- range-delete upper bound
//!                   ck:         Utf8,
//!                   inclusive:  Boolean,
//!                 }
//! ```
//!
//! ## Feature gate
//!
//! This module is compiled only when **both** `delta-scan` and `arrow` features
//! are enabled.  It deliberately reuses [`cql_type_to_arrow_data_type`] from
//! `export::arrow_convert` (the #673 mapping) for the cell `value` field, so
//! there is no duplicated CQL → Arrow type logic.
//!
//! ## Fail-before-writing rules
//!
//! Both error conditions are raised at schema-derivation time, before any
//! output bytes are produced:
//!
//! 1. **Counter tables** — rejected with a descriptive error.
//! 2. **Column-name collisions** — a user column whose name matches an envelope
//!    reserved name (e.g. `__op`) causes a hard error.  The caller may provide
//!    a custom [`DeltaSchemaOpts::envelope_prefix`] (e.g. `"_cqlite_"`) to
//!    choose a different prefix for all reserved names; the error message names
//!    the option.

use arrow::datatypes::{DataType as ArrowDataType, Field, Fields, Schema};
use thiserror::Error;

use crate::export::arrow_convert::cql_type_to_arrow_data_type;
use crate::schema::{CqlType, TableSchema};

// ============================================================================
// Error type
// ============================================================================

/// Errors produced by [`derive_delta_schema`] at schema-derivation time.
///
/// All errors are raised **before** any output bytes are written
/// (fail-before-writing guarantee, design §"Error handling").
#[derive(Debug, Error)]
pub enum DeltaSchemaError {
    /// A user column name collides with one of the envelope reserved names.
    ///
    /// The error message names the colliding column, the reserved name it
    /// conflicts with, and how to supply a different prefix via
    /// [`DeltaSchemaOpts::envelope_prefix`].
    #[error(
        "Column '{column}' collides with envelope reserved name '{reserved}'. \
         Use DeltaSchemaOpts::envelope_prefix to choose a different prefix \
         (e.g. envelope_prefix = \"_cqlite_\" gives \"_cqlite_op\", \"_cqlite_ts\", etc.)."
    )]
    ColumnCollision {
        /// The user column name that caused the collision.
        column: String,
        /// The reserved envelope name it collides with.
        reserved: String,
    },

    /// Counter tables cannot be projected to the delta envelope.
    ///
    /// Cassandra counter tables use a fundamentally different on-disk format
    /// (distributed counters) that cannot be represented as simple cell deltas.
    /// Reject at schema-derivation time rather than silently producing wrong output.
    #[error(
        "Counter tables cannot be projected to the delta envelope. \
         Table '{keyspace}.{table}' contains counter column(s): {columns}. \
         Counter semantics (distributed add/subtract) are incompatible with \
         the per-cell writetime delta model."
    )]
    CounterTable {
        /// Keyspace of the rejected table.
        keyspace: String,
        /// Table name of the rejected table.
        table: String,
        /// Comma-separated list of counter column names.
        columns: String,
    },

    /// CQL type parsing failed during schema derivation.
    #[error("CQL type parse error for column '{column}': {source}")]
    CqlTypeParse {
        /// The column whose type could not be parsed.
        column: String,
        /// The underlying error message.
        #[source]
        source: crate::error::Error,
    },
}

// ============================================================================
// Options
// ============================================================================

/// Options for [`derive_delta_schema`].
///
/// All fields have sensible defaults via [`Default`].
#[derive(Debug, Clone)]
pub struct DeltaSchemaOpts {
    /// Prefix used for the envelope's reserved column names.
    ///
    /// Defaults to `"__"`, yielding `__op`, `__ts`, `__range_start`,
    /// `__range_end`.  If a user column collides with one of these names,
    /// change this to a prefix that does not appear in the schema (e.g.
    /// `"_cqlite_"`).
    pub envelope_prefix: String,
}

impl Default for DeltaSchemaOpts {
    fn default() -> Self {
        Self {
            envelope_prefix: "__".to_string(),
        }
    }
}

impl DeltaSchemaOpts {
    /// Create options with a custom envelope prefix.
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            envelope_prefix: prefix.into(),
        }
    }

    /// Return the name of the `__op` envelope column under the configured prefix.
    pub fn op_col(&self) -> String {
        format!("{}op", self.envelope_prefix)
    }

    /// Return the name of the `__ts` envelope column under the configured prefix.
    pub fn ts_col(&self) -> String {
        format!("{}ts", self.envelope_prefix)
    }

    /// Return the name of the `__range_start` envelope column under the configured prefix.
    pub fn range_start_col(&self) -> String {
        format!("{}range_start", self.envelope_prefix)
    }

    /// Return the name of the `__range_end` envelope column under the configured prefix.
    pub fn range_end_col(&self) -> String {
        format!("{}range_end", self.envelope_prefix)
    }

    /// Return all four reserved envelope names for collision checking.
    fn reserved_names(&self) -> [String; 4] {
        [
            self.op_col(),
            self.ts_col(),
            self.range_start_col(),
            self.range_end_col(),
        ]
    }
}

// ============================================================================
// Public API
// ============================================================================

/// Derive the Arrow envelope schema for a [`TableSchema`].
///
/// Produces the complete Arrow [`Schema`] for the delta-scan Parquet envelope,
/// including:
///
/// 1. **Key columns** — partition key and clustering key columns as plain Arrow
///    types (using the #673 mapping via [`cql_type_to_arrow_data_type`]).
/// 2. **Cell columns** — every non-key column becomes a nullable `Struct{
///    value: <Arrow type>, writetime: i64, expires_at: i64|null }`.  Collection
///    columns (`List`, `Set`, `Map`) additionally include `replaced: bool`.
/// 3. **`{prefix}op`** — dictionary-encoded `Utf8` (default `__op`).
/// 4. **`{prefix}ts`** — nullable `i64` (default `__ts`).
/// 5. **`{prefix}range_start`** / **`{prefix}range_end`** — nullable
///    `Struct{ <clustering columns...>, inclusive: bool }`.
///
/// # Errors
///
/// Returns [`DeltaSchemaError::CounterTable`] if any column has type `counter`.
///
/// Returns [`DeltaSchemaError::ColumnCollision`] if any user column name matches
/// one of the reserved envelope names (see [`DeltaSchemaOpts::envelope_prefix`]).
///
/// Returns [`DeltaSchemaError::CqlTypeParse`] if a column's `data_type` string
/// cannot be parsed into a [`CqlType`].
pub fn derive_delta_schema(
    table: &TableSchema,
    opts: &DeltaSchemaOpts,
) -> Result<Schema, DeltaSchemaError> {
    // ------------------------------------------------------------------
    // 1. Fail-before-writing: reject counter tables
    // ------------------------------------------------------------------
    let counter_cols: Vec<String> = table
        .columns
        .iter()
        .filter(|col| {
            // Parse the data type; on parse failure we'll catch it below.
            CqlType::parse(&col.data_type)
                .map(|t| is_counter_type(&t))
                .unwrap_or(false)
        })
        .map(|col| col.name.clone())
        .collect();

    if !counter_cols.is_empty() {
        return Err(DeltaSchemaError::CounterTable {
            keyspace: table.keyspace.clone(),
            table: table.table.clone(),
            columns: counter_cols.join(", "),
        });
    }

    // ------------------------------------------------------------------
    // 2. Fail-before-writing: check for column-name collisions
    //
    // The collision check must cover ALL user-visible column names, including
    // partition-key and clustering-key columns.  Key columns are emitted as
    // plain Arrow fields (steps 3a/3b) just like regular columns, so a key
    // column named e.g. `__op` would produce two Arrow fields with the same
    // name — silently malformed output rather than the intended error.
    // ------------------------------------------------------------------
    let reserved = opts.reserved_names();

    // Collect all column names: partition keys + clustering keys + regular columns.
    let all_column_names = table
        .partition_keys
        .iter()
        .map(|k| &k.name)
        .chain(table.clustering_keys.iter().map(|k| &k.name))
        .chain(table.columns.iter().map(|c| &c.name));

    for col_name in all_column_names {
        for res in &reserved {
            if col_name == res {
                return Err(DeltaSchemaError::ColumnCollision {
                    column: col_name.clone(),
                    reserved: res.clone(),
                });
            }
        }
    }

    // ------------------------------------------------------------------
    // 3. Build Arrow fields
    // ------------------------------------------------------------------
    let mut fields: Vec<Field> = Vec::new();

    // 3a. Partition key columns — plain Arrow types, non-nullable.
    let ordered_pk = table.ordered_partition_keys();
    for key_col in &ordered_pk {
        let cql_type =
            CqlType::parse(&key_col.data_type).map_err(|e| DeltaSchemaError::CqlTypeParse {
                column: key_col.name.clone(),
                source: e,
            })?;
        let arrow_type = cql_type_to_arrow_data_type(&cql_type);
        fields.push(Field::new(&key_col.name, arrow_type, false));
    }

    // 3b. Clustering key columns — plain Arrow types, nullable (null for
    //     partition-scoped ops like partition_delete / static_upsert).
    let ordered_ck = table.ordered_clustering_keys();
    for ck_col in &ordered_ck {
        let cql_type =
            CqlType::parse(&ck_col.data_type).map_err(|e| DeltaSchemaError::CqlTypeParse {
                column: ck_col.name.clone(),
                source: e,
            })?;
        let arrow_type = cql_type_to_arrow_data_type(&cql_type);
        fields.push(Field::new(&ck_col.name, arrow_type, true));
    }

    // 3c. Non-key columns — cell structs.
    //
    // Key column names for quick membership check.
    let pk_names: std::collections::HashSet<&str> =
        ordered_pk.iter().map(|k| k.name.as_str()).collect();
    let ck_names: std::collections::HashSet<&str> =
        ordered_ck.iter().map(|k| k.name.as_str()).collect();

    for col in &table.columns {
        if pk_names.contains(col.name.as_str()) || ck_names.contains(col.name.as_str()) {
            // Already emitted as a plain key field above.
            continue;
        }

        let cql_type =
            CqlType::parse(&col.data_type).map_err(|e| DeltaSchemaError::CqlTypeParse {
                column: col.name.clone(),
                source: e,
            })?;

        let cell_field = build_cell_struct_field(&col.name, &cql_type);
        fields.push(cell_field);
    }

    // 3d. Envelope columns.
    fields.push(build_op_field(&opts.op_col()));
    fields.push(Field::new(opts.ts_col(), ArrowDataType::Int64, true));
    fields.push(build_range_bound_field(
        &opts.range_start_col(),
        &ordered_ck,
    )?);
    fields.push(build_range_bound_field(&opts.range_end_col(), &ordered_ck)?);

    Ok(Schema::new(fields))
}

// ============================================================================
// Internal helpers
// ============================================================================

/// Returns `true` if the CQL type is `Counter` (including through `Frozen`).
fn is_counter_type(cql_type: &CqlType) -> bool {
    match cql_type {
        CqlType::Counter => true,
        CqlType::Frozen(inner) => is_counter_type(inner),
        _ => false,
    }
}

/// Returns `true` if the CQL type is a non-frozen collection (`List`, `Set`, `Map`).
///
/// Frozen collections do NOT get the `replaced` field — they behave like scalars.
fn is_collection_type(cql_type: &CqlType) -> bool {
    match cql_type {
        CqlType::List(_) | CqlType::Set(_) | CqlType::Map(_, _) => true,
        // All other types, including Frozen<collection>, are treated as scalars.
        _ => false,
    }
}

/// Build the nullable cell `Struct` field for a non-key column.
///
/// ```text
/// Struct(nullable) {
///   value:      <Arrow type per #673>,
///   writetime:  Int64,
///   expires_at: Int64 (nullable),
///   replaced:   Boolean  -- collection columns ONLY
/// }
/// ```
///
/// Reuses [`cql_type_to_arrow_data_type`] (the #673 mapping) for `value`.
fn build_cell_struct_field(col_name: &str, cql_type: &CqlType) -> Field {
    let value_arrow_type = cql_type_to_arrow_data_type(cql_type);
    let is_collection = is_collection_type(cql_type);

    let mut struct_fields = vec![
        // value: nullable — `None` encodes a cell tombstone.
        Field::new("value", value_arrow_type, true),
        // writetime: always present (i64 µs since epoch).
        Field::new("writetime", ArrowDataType::Int64, false),
        // expires_at: nullable — `None` means no TTL.
        Field::new("expires_at", ArrowDataType::Int64, true),
    ];

    if is_collection {
        // replaced: present only for non-frozen collection columns (v1 design).
        struct_fields.push(Field::new("replaced", ArrowDataType::Boolean, false));
    }

    // The struct itself is nullable: null struct = column not present in this delta.
    Field::new(
        col_name,
        ArrowDataType::Struct(Fields::from(struct_fields)),
        true, // nullable struct
    )
}

/// Build the `__op` field: `Dictionary(Int8, Utf8)`.
///
/// Dictionary-encoded so that the five op strings (`upsert`, `static_upsert`,
/// `row_delete`, `range_delete`, `partition_delete`) are stored once in the
/// dictionary and referenced by small integer indices.
fn build_op_field(col_name: &str) -> Field {
    Field::new(
        col_name,
        ArrowDataType::Dictionary(Box::new(ArrowDataType::Int8), Box::new(ArrowDataType::Utf8)),
        false,
    )
}

/// Build a `__range_start` or `__range_end` field.
///
/// ```text
/// Struct(nullable) {
///   <ck_1>:    <Arrow type of first clustering column>,
///   <ck_2>:    <Arrow type of second clustering column>,
///   ...
///   inclusive: Boolean,
/// }
/// ```
///
/// The struct is nullable: null means "no range bound" (only non-null on
/// `range_delete` records).  Clustering-key columns within the struct are
/// individually nullable to support prefix bounds.
///
/// Tables with no clustering key produce an empty-struct with just `inclusive`
/// (degenerate but well-formed for the writer).
fn build_range_bound_field(
    col_name: &str,
    clustering_keys: &[&crate::schema::ClusteringColumn],
) -> Result<Field, DeltaSchemaError> {
    let mut struct_fields: Vec<Field> = Vec::with_capacity(clustering_keys.len() + 1);

    for ck_col in clustering_keys {
        let cql_type =
            CqlType::parse(&ck_col.data_type).map_err(|e| DeltaSchemaError::CqlTypeParse {
                column: ck_col.name.clone(),
                source: e,
            })?;
        let arrow_type = cql_type_to_arrow_data_type(&cql_type);
        // Nullable: trailing components absent in a prefix bound become null.
        struct_fields.push(Field::new(&ck_col.name, arrow_type, true));
    }

    struct_fields.push(Field::new("inclusive", ArrowDataType::Boolean, false));

    Ok(Field::new(
        col_name,
        ArrowDataType::Struct(Fields::from(struct_fields)),
        true, // nullable — null except on range_delete records
    ))
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{ClusteringColumn, ClusteringOrder, Column, KeyColumn, TableSchema};
    use std::collections::HashMap;

    // ------------------------------------------------------------------
    // Helper: build the design's example table
    //   t (pk int, ck text, val text, st text STATIC, PRIMARY KEY (pk, ck))
    // ------------------------------------------------------------------
    fn example_table() -> TableSchema {
        TableSchema {
            keyspace: "example_ks".to_string(),
            table: "t".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                name: "ck".to_string(),
                data_type: "text".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "ck".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "val".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "st".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: true,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        }
    }

    // ------------------------------------------------------------------
    // Snapshot test: schema for the design's example table
    // ------------------------------------------------------------------

    #[test]
    fn snapshot_example_table_schema() {
        let table = example_table();
        let opts = DeltaSchemaOpts::default();
        let schema = derive_delta_schema(&table, &opts).expect("derive_delta_schema failed");

        // --- Verify field count ---
        // pk, ck, val, st, __op, __ts, __range_start, __range_end = 8
        assert_eq!(
            schema.fields().len(),
            8,
            "expected 8 fields, got {}",
            schema.fields().len()
        );

        // --- 1. pk: Int32, non-nullable ---
        let pk = schema.field_with_name("pk").expect("no pk field");
        assert_eq!(*pk.data_type(), ArrowDataType::Int32, "pk should be Int32");
        assert!(!pk.is_nullable(), "pk should be non-nullable");

        // --- 2. ck: Utf8, nullable (null for partition-scoped ops) ---
        let ck = schema.field_with_name("ck").expect("no ck field");
        assert_eq!(*ck.data_type(), ArrowDataType::Utf8, "ck should be Utf8");
        assert!(ck.is_nullable(), "ck should be nullable");

        // --- 3. val: Struct(nullable) { value: Utf8, writetime: i64, expires_at: i64|null } ---
        //    val has no `replaced` (it is not a collection)
        let val = schema.field_with_name("val").expect("no val field");
        assert!(val.is_nullable(), "val cell struct should be nullable");
        if let ArrowDataType::Struct(val_fields) = val.data_type() {
            assert_eq!(
                val_fields.len(),
                3,
                "val struct should have 3 fields (no replaced)"
            );
            let vf = val_fields
                .find("value")
                .expect("no value field in val struct");
            assert_eq!(*vf.1.data_type(), ArrowDataType::Utf8);
            assert!(
                vf.1.is_nullable(),
                "value should be nullable (cell tombstone = null)"
            );
            let wt = val_fields.find("writetime").expect("no writetime field");
            assert_eq!(*wt.1.data_type(), ArrowDataType::Int64);
            assert!(!wt.1.is_nullable(), "writetime should be non-nullable");
            let ea = val_fields.find("expires_at").expect("no expires_at field");
            assert_eq!(*ea.1.data_type(), ArrowDataType::Int64);
            assert!(ea.1.is_nullable(), "expires_at should be nullable");
        } else {
            panic!("val should be a Struct, got {:?}", val.data_type());
        }

        // --- 4. st: same struct shape as val (static but same cell struct) ---
        let st = schema.field_with_name("st").expect("no st field");
        assert!(st.is_nullable(), "st cell struct should be nullable");
        if let ArrowDataType::Struct(st_fields) = st.data_type() {
            assert_eq!(
                st_fields.len(),
                3,
                "st struct should have 3 fields (no replaced)"
            );
        } else {
            panic!("st should be a Struct");
        }

        // --- 5. __op: Dictionary(Int8, Utf8), non-nullable ---
        let op = schema.field_with_name("__op").expect("no __op field");
        assert!(!op.is_nullable(), "__op should be non-nullable");
        assert!(
            matches!(op.data_type(), ArrowDataType::Dictionary(key, val)
                if **key == ArrowDataType::Int8 && **val == ArrowDataType::Utf8),
            "__op should be Dictionary(Int8, Utf8), got {:?}",
            op.data_type()
        );

        // --- 6. __ts: Int64, nullable ---
        let ts = schema.field_with_name("__ts").expect("no __ts field");
        assert_eq!(*ts.data_type(), ArrowDataType::Int64);
        assert!(ts.is_nullable(), "__ts should be nullable");

        // --- 7. __range_start: Struct(nullable) { ck: Utf8, inclusive: Boolean } ---
        let rs = schema
            .field_with_name("__range_start")
            .expect("no __range_start field");
        assert!(rs.is_nullable(), "__range_start should be nullable");
        if let ArrowDataType::Struct(rs_fields) = rs.data_type() {
            assert_eq!(
                rs_fields.len(),
                2,
                "__range_start struct should have 2 fields (ck + inclusive)"
            );
            let ck_f = rs_fields.find("ck").expect("no ck in __range_start");
            assert_eq!(*ck_f.1.data_type(), ArrowDataType::Utf8);
            assert!(
                ck_f.1.is_nullable(),
                "ck in range bound should be nullable (prefix)"
            );
            let inc_f = rs_fields
                .find("inclusive")
                .expect("no inclusive in __range_start");
            assert_eq!(*inc_f.1.data_type(), ArrowDataType::Boolean);
            assert!(!inc_f.1.is_nullable(), "inclusive should be non-nullable");
        } else {
            panic!("__range_start should be a Struct");
        }

        // --- 8. __range_end: same shape as __range_start ---
        let re = schema
            .field_with_name("__range_end")
            .expect("no __range_end field");
        assert!(re.is_nullable(), "__range_end should be nullable");
        if let ArrowDataType::Struct(re_fields) = re.data_type() {
            assert_eq!(
                re_fields.len(),
                2,
                "__range_end struct should have 2 fields"
            );
        } else {
            panic!("__range_end should be a Struct");
        }
    }

    // ------------------------------------------------------------------
    // Collection column: `replaced` field present ONLY for collections
    // ------------------------------------------------------------------

    #[test]
    fn collection_column_has_replaced_field() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "with_collection".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "tags".to_string(),
                    data_type: "set<text>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "name".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");

        // `tags` is a set — should have `replaced`.
        let tags = schema.field_with_name("tags").expect("no tags field");
        if let ArrowDataType::Struct(fields) = tags.data_type() {
            assert_eq!(
                fields.len(),
                4,
                "set column struct should have 4 fields (incl. replaced)"
            );
            assert!(
                fields.find("replaced").is_some(),
                "set column should have `replaced` field"
            );
        } else {
            panic!("tags should be Struct");
        }

        // `name` is text — should NOT have `replaced`.
        let name = schema.field_with_name("name").expect("no name field");
        if let ArrowDataType::Struct(fields) = name.data_type() {
            assert_eq!(
                fields.len(),
                3,
                "scalar column struct should have 3 fields (no replaced)"
            );
            assert!(
                fields.find("replaced").is_none(),
                "scalar column should NOT have `replaced`"
            );
        } else {
            panic!("name should be Struct");
        }
    }

    // ------------------------------------------------------------------
    // frozen<list<text>> is NOT a collection (frozen = scalar)
    // ------------------------------------------------------------------

    #[test]
    fn frozen_collection_is_scalar_no_replaced() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "frozen_test".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "frozen_list".to_string(),
                    data_type: "frozen<list<text>>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");

        let frozen_col = schema
            .field_with_name("frozen_list")
            .expect("no frozen_list field");
        if let ArrowDataType::Struct(fields) = frozen_col.data_type() {
            assert_eq!(
                fields.len(),
                3,
                "frozen<list> should be treated as scalar: 3 fields"
            );
            assert!(
                fields.find("replaced").is_none(),
                "frozen<list> should NOT have `replaced`"
            );
        } else {
            panic!("frozen_list should be Struct");
        }
    }

    // ------------------------------------------------------------------
    // Collision detection: __op column → error
    // ------------------------------------------------------------------

    #[test]
    fn column_collision_default_prefix() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "bad".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                // Legal CQL column name that collides with the envelope.
                Column {
                    name: "__op".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let err = derive_delta_schema(&table, &DeltaSchemaOpts::default())
            .expect_err("expected collision error");

        match err {
            DeltaSchemaError::ColumnCollision { column, reserved } => {
                assert_eq!(column, "__op");
                assert_eq!(reserved, "__op");
            }
            other => panic!("expected ColumnCollision, got {:?}", other),
        }
    }

    #[test]
    fn column_collision_ts_column() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "bad_ts".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "__ts".to_string(),
                    data_type: "bigint".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let err = derive_delta_schema(&table, &DeltaSchemaOpts::default())
            .expect_err("expected collision error");

        assert!(
            matches!(err, DeltaSchemaError::ColumnCollision { .. }),
            "expected ColumnCollision"
        );
    }

    // ------------------------------------------------------------------
    // Collision detection: key columns (partition / clustering) named __op
    // ------------------------------------------------------------------

    /// A partition key column named `__op` must trigger `ColumnCollision`.
    ///
    /// Before the fix, the check only iterated `table.columns`, so a key column
    /// with a reserved name escaped detection and produced a malformed Arrow
    /// `Schema` with two fields named `__op`.
    #[test]
    fn partition_key_collision_default_prefix() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "pk_collision".to_string(),
            partition_keys: vec![KeyColumn {
                // Partition key named after the envelope discriminator.
                name: "__op".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            // `table.columns` deliberately does NOT contain a column named `__op`
            // (simulating a schema where keys are not duplicated in the columns
            // list), so the pre-fix check over `table.columns` alone would have
            // missed this collision entirely.
            columns: vec![Column {
                name: "__op".to_string(),
                data_type: "int".to_string(),
                nullable: false,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let err = derive_delta_schema(&table, &DeltaSchemaOpts::default())
            .expect_err("expected ColumnCollision for partition key named __op");

        match err {
            DeltaSchemaError::ColumnCollision { column, reserved } => {
                assert_eq!(column, "__op");
                assert_eq!(reserved, "__op");
            }
            other => panic!("expected ColumnCollision, got {:?}", other),
        }
    }

    /// A clustering key column named `__ts` must trigger `ColumnCollision`.
    #[test]
    fn clustering_key_collision_default_prefix() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "ck_collision".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![ClusteringColumn {
                // Clustering key named after the envelope timestamp column.
                name: "__ts".to_string(),
                data_type: "text".to_string(),
                position: 0,
                order: ClusteringOrder::Asc,
            }],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "__ts".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let err = derive_delta_schema(&table, &DeltaSchemaOpts::default())
            .expect_err("expected ColumnCollision for clustering key named __ts");

        match err {
            DeltaSchemaError::ColumnCollision { column, reserved } => {
                assert_eq!(column, "__ts");
                assert_eq!(reserved, "__ts");
            }
            other => panic!("expected ColumnCollision, got {:?}", other),
        }
    }

    // ------------------------------------------------------------------
    // Configurable envelope_prefix changes the reserved names
    // ------------------------------------------------------------------

    #[test]
    fn custom_prefix_avoids_collision() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "custom_prefix".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                // Column named `__op` — collides with default prefix but not
                // with the custom `_cqlite_` prefix.
                Column {
                    name: "__op".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        // Default prefix → collision.
        assert!(derive_delta_schema(&table, &DeltaSchemaOpts::default()).is_err());

        // Custom prefix → success; envelope col is `_cqlite_op`, not `__op`.
        let opts = DeltaSchemaOpts::with_prefix("_cqlite_");
        let schema = derive_delta_schema(&table, &opts).expect("should succeed with custom prefix");

        // User column `__op` is present as a cell struct.
        let op_col = schema.field_with_name("__op").expect("no __op field");
        assert!(
            matches!(op_col.data_type(), ArrowDataType::Struct(_)),
            "__op should be a cell Struct under custom prefix"
        );

        // Envelope column is `_cqlite_op` (dictionary-encoded Utf8).
        let cqlite_op = schema
            .field_with_name("_cqlite_op")
            .expect("no _cqlite_op field");
        assert!(
            matches!(cqlite_op.data_type(), ArrowDataType::Dictionary(..)),
            "_cqlite_op should be Dictionary-encoded"
        );
    }

    // ------------------------------------------------------------------
    // Custom prefix also changes the error message
    // ------------------------------------------------------------------

    #[test]
    fn custom_prefix_collision_error_names_custom_reserved() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "t".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                // Column named `_cqlite_op` — collides with the custom prefix.
                Column {
                    name: "_cqlite_op".to_string(),
                    data_type: "text".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let opts = DeltaSchemaOpts::with_prefix("_cqlite_");
        let err = derive_delta_schema(&table, &opts).expect_err("expected collision");
        match err {
            DeltaSchemaError::ColumnCollision { column, reserved } => {
                assert_eq!(column, "_cqlite_op");
                assert_eq!(reserved, "_cqlite_op");
            }
            other => panic!("expected ColumnCollision, got {:?}", other),
        }
    }

    // ------------------------------------------------------------------
    // Counter table rejection
    // ------------------------------------------------------------------

    #[test]
    fn counter_table_rejected() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "counters".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "views".to_string(),
                    data_type: "counter".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let err = derive_delta_schema(&table, &DeltaSchemaOpts::default())
            .expect_err("expected counter error");

        match &err {
            DeltaSchemaError::CounterTable {
                keyspace,
                table: tbl,
                columns,
            } => {
                assert_eq!(keyspace, "ks");
                assert_eq!(tbl, "counters");
                assert!(columns.contains("views"), "error should name 'views'");
            }
            other => panic!("expected CounterTable, got {:?}", other),
        }

        // Error message should be descriptive.
        let msg = err.to_string();
        assert!(
            msg.contains("counter"),
            "message should mention counter: {}",
            msg
        );
        assert!(
            msg.contains("ks.counters"),
            "message should name the table: {}",
            msg
        );
    }

    // ------------------------------------------------------------------
    // Value types come from the #673 mapping (no duplicated mapping code)
    // ------------------------------------------------------------------

    #[test]
    fn value_types_from_673_mapping() {
        // Verify that the Arrow type assigned to the `value` field of each cell
        // struct matches what `cql_type_to_arrow_data_type` returns for the
        // same CQL type.  This is the proof that we are reusing the #673 mapping
        // rather than forking a second CQL→Arrow mapping.
        let types_under_test = vec![
            ("bigint", CqlType::BigInt),
            ("boolean", CqlType::Boolean),
            ("float", CqlType::Float),
            ("double", CqlType::Double),
            ("uuid", CqlType::Uuid),
            ("timeuuid", CqlType::TimeUuid),
            ("timestamp", CqlType::Timestamp),
            ("date", CqlType::Date),
            ("time", CqlType::Time),
            ("blob", CqlType::Blob),
            ("inet", CqlType::Inet),
            ("decimal", CqlType::Decimal),
            ("varint", CqlType::Varint),
        ];

        for (type_str, expected_cql_type) in types_under_test {
            let table = TableSchema {
                keyspace: "ks".to_string(),
                table: "t".to_string(),
                partition_keys: vec![KeyColumn {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    position: 0,
                }],
                clustering_keys: vec![],
                columns: vec![
                    Column {
                        name: "pk".to_string(),
                        data_type: "int".to_string(),
                        nullable: false,
                        default: None,
                        is_static: false,
                    },
                    Column {
                        name: "col".to_string(),
                        data_type: type_str.to_string(),
                        nullable: true,
                        default: None,
                        is_static: false,
                    },
                ],
                comments: HashMap::new(),
                dropped_columns: HashMap::new(),
            };

            let schema = derive_delta_schema(&table, &DeltaSchemaOpts::default())
                .unwrap_or_else(|e| panic!("derive failed for {}: {:?}", type_str, e));

            let col_field = schema.field_with_name("col").expect("no col field");
            if let ArrowDataType::Struct(struct_fields) = col_field.data_type() {
                let value_field = struct_fields
                    .find("value")
                    .expect("no value field in struct");
                let expected_arrow_type = cql_type_to_arrow_data_type(&expected_cql_type);
                assert_eq!(
                    *value_field.1.data_type(),
                    expected_arrow_type,
                    "value Arrow type mismatch for CQL type '{}': expected {:?}, got {:?}",
                    type_str,
                    expected_arrow_type,
                    value_field.1.data_type()
                );
            } else {
                panic!("col should be Struct for type {}", type_str);
            }
        }
    }

    // ------------------------------------------------------------------
    // No-clustering-key table: range bounds have only `inclusive`
    // ------------------------------------------------------------------

    #[test]
    fn no_clustering_keys_range_bound_has_only_inclusive() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "no_ck".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![Column {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                nullable: false,
                default: None,
                is_static: false,
            }],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");

        let rs = schema
            .field_with_name("__range_start")
            .expect("no __range_start");
        if let ArrowDataType::Struct(fields) = rs.data_type() {
            assert_eq!(
                fields.len(),
                1,
                "no-CK range bound should only have `inclusive`"
            );
            assert!(fields.find("inclusive").is_some());
        } else {
            panic!("__range_start should be Struct");
        }
    }

    // ------------------------------------------------------------------
    // Multiple clustering keys: range bound has typed fields + inclusive
    // ------------------------------------------------------------------

    #[test]
    fn multi_ck_range_bound_has_all_ck_fields() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "multi_ck".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![
                ClusteringColumn {
                    name: "year".to_string(),
                    data_type: "int".to_string(),
                    position: 0,
                    order: ClusteringOrder::Asc,
                },
                ClusteringColumn {
                    name: "month".to_string(),
                    data_type: "int".to_string(),
                    position: 1,
                    order: ClusteringOrder::Asc,
                },
            ],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "year".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "month".to_string(),
                    data_type: "int".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");

        let rs = schema
            .field_with_name("__range_start")
            .expect("no __range_start");
        if let ArrowDataType::Struct(fields) = rs.data_type() {
            // year + month + inclusive = 3 fields
            assert_eq!(fields.len(), 3);
            assert!(fields.find("year").is_some());
            assert!(fields.find("month").is_some());
            assert!(fields.find("inclusive").is_some());
            // Clustering fields are nullable (prefix bounds).
            let year_f = fields.find("year").unwrap();
            assert!(
                year_f.1.is_nullable(),
                "year in range bound should be nullable"
            );
        } else {
            panic!("__range_start should be Struct");
        }
    }

    // ------------------------------------------------------------------
    // Map column has `replaced` field
    // ------------------------------------------------------------------

    #[test]
    fn map_column_has_replaced_field() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "with_map".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "attrs".to_string(),
                    data_type: "map<text, text>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");
        let attrs = schema.field_with_name("attrs").expect("no attrs field");
        if let ArrowDataType::Struct(fields) = attrs.data_type() {
            assert_eq!(
                fields.len(),
                4,
                "map column should have 4 fields (incl. replaced)"
            );
            assert!(fields.find("replaced").is_some());
        } else {
            panic!("attrs should be Struct");
        }
    }

    // ------------------------------------------------------------------
    // List column has `replaced` field
    // ------------------------------------------------------------------

    #[test]
    fn list_column_has_replaced_field() {
        let table = TableSchema {
            keyspace: "ks".to_string(),
            table: "with_list".to_string(),
            partition_keys: vec![KeyColumn {
                name: "pk".to_string(),
                data_type: "int".to_string(),
                position: 0,
            }],
            clustering_keys: vec![],
            columns: vec![
                Column {
                    name: "pk".to_string(),
                    data_type: "int".to_string(),
                    nullable: false,
                    default: None,
                    is_static: false,
                },
                Column {
                    name: "events".to_string(),
                    data_type: "list<bigint>".to_string(),
                    nullable: true,
                    default: None,
                    is_static: false,
                },
            ],
            comments: HashMap::new(),
            dropped_columns: HashMap::new(),
        };

        let schema =
            derive_delta_schema(&table, &DeltaSchemaOpts::default()).expect("derive failed");
        let events = schema.field_with_name("events").expect("no events field");
        if let ArrowDataType::Struct(fields) = events.data_type() {
            assert_eq!(
                fields.len(),
                4,
                "list column should have 4 fields (incl. replaced)"
            );
            assert!(fields.find("replaced").is_some());
        } else {
            panic!("events should be Struct");
        }
    }
}