clickhouse-native-rs 2.24.1

Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained continuation of the clickhouse-rs crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
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
/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! `Variant(T1, T2, ...)` columns (`SerializationVariant`): a row holds a
//! value of one of the types, or NULL. The Native form is a state prefix (the
//! discriminators' mode, then the prefixes of the alternatives), a
//! discriminator per row (the index of its type in the type name, 255 for
//! NULL), and then the rows of each alternative, in the order of the type.
//!
//! The server sorts the alternatives by name, reads a Variant in that order
//! and converts one Variant into another only when every alternative is in
//! both. So each alternative keeps the name the server gave it (a `Point` is
//! read as a tuple, a `DateTime('UTC')` as a `DateTime`), and a Variant is
//! written with those names, in their order.

use std::sync::Arc;

use chrono_tz::Tz;
use either::Either;

use crate::{
    binary::{Encoder, ReadEx},
    errors::{DriverError, Error, Result},
    types::{
        column::{
            chrono_datetime,
            column_data::{make_mut, ArcColumnData, BoxColumnData, ColumnData},
            date::{has_checked_leaf, leaves_fit, DateColumnData},
            decimal::check_decimal_push,
            dynamic::unresolved,
            tuple::split_top_level,
            ArcColumnWrapper,
        },
        DateTimeType, SqlType, Value, ValueRef,
    },
};

/// The discriminator of a NULL row (`ColumnVariant::NULL_DISCRIMINATOR`).
pub(crate) const NULL_DISCRIMINATOR: u8 = 255;

/// The most alternatives a Variant has: their discriminators are 0 to 254.
const MAX_ALTERNATIVES: usize = NULL_DISCRIMINATOR as usize;

/// The discriminators' mode that starts the state prefix: one per row
/// (`DiscriminatorsSerializationMode::BASIC`), the mode the Native format
/// uses.
pub(crate) const BASIC_DISCRIMINATORS: u64 = 0;

/// The alternatives of a Variant: the name of each, and its type.
pub(crate) type Alternatives = [(String, &'static SqlType)];

/// The alternatives of a `Variant(...)` type name.
pub(crate) fn parse_variant_type(source: &str) -> Option<Vec<&str>> {
    let body = source.strip_prefix("Variant(")?.strip_suffix(')')?;
    let types = split_top_level(body)?;
    (!types.is_empty() && types.len() <= MAX_ALTERNATIVES).then_some(types)
}

/// The indexes of `alternatives` in the order of their names, which the
/// server reads a Variant in.
pub(crate) fn name_order(alternatives: &Alternatives) -> Vec<usize> {
    let mut order: Vec<usize> = (0..alternatives.len()).collect();
    order.sort_by(|&a, &b| alternatives[a].0.cmp(&alternatives[b].0));
    order
}

/// `alternatives` in the order of their names.
pub(crate) fn canonical(alternatives: &Alternatives) -> Vec<(String, &'static SqlType)> {
    name_order(alternatives)
        .into_iter()
        .map(|index| alternatives[index].clone())
        .collect()
}

pub(crate) struct VariantColumnData {
    /// The rows of each alternative.
    pub(crate) variants: Vec<ArcColumnData>,
    /// The alternative of each row, or `NULL_DISCRIMINATOR`.
    pub(crate) discriminators: Vec<u8>,
    /// The row of each row in its alternative.
    pub(crate) offsets: Vec<usize>,
    /// The type of the column, with the names of its alternatives.
    sql_type: &'static SqlType,
}

fn too_many(types: usize) -> Error {
    Error::Driver(DriverError::Deserialize(
        format!("a Variant has at most {MAX_ALTERNATIVES} types, not {types}").into(),
    ))
}

impl VariantColumnData {
    pub(crate) fn load<R: ReadEx>(
        reader: &mut R,
        types: Vec<&str>,
        size: usize,
        tz: Tz,
    ) -> Result<Self> {
        Self::load_as(reader, types, size, tz, |name| name, |_, _| Ok(()))
    }

    /// Loads a Variant of the alternatives `names`, each loaded as the type
    /// `load_type` gives for its name (that of a Dynamic's `SharedVariant` is
    /// a String) once `check` takes its number of rows.
    pub(crate) fn load_as<'a, R, F, C>(
        reader: &mut R,
        names: Vec<&'a str>,
        size: usize,
        tz: Tz,
        load_type: F,
        check: C,
    ) -> Result<Self>
    where
        R: ReadEx,
        F: Fn(&'a str) -> &'a str,
        C: Fn(&str, usize) -> Result<()>,
    {
        let mut discriminators = vec![0_u8; size];
        reader.read_bytes(&mut discriminators)?;
        let mut counts = vec![0_usize; names.len()];
        let mut offsets = Vec::with_capacity(size);
        for &discriminator in &discriminators {
            if discriminator == NULL_DISCRIMINATOR {
                offsets.push(0);
                continue;
            }
            let Some(count) = counts.get_mut(usize::from(discriminator)) else {
                return Err(Error::Driver(DriverError::Deserialize(
                    format!(
                        "a Variant of {} types has discriminator {discriminator}",
                        names.len()
                    )
                    .into(),
                )));
            };
            offsets.push(*count);
            *count += 1;
        }
        let mut variants = Vec::with_capacity(names.len());
        let mut alternatives = Vec::with_capacity(names.len());
        for (name, rows) in names.into_iter().zip(counts) {
            check(name, rows)?;
            let variant = <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(
                reader,
                load_type(name),
                rows,
                tz,
            )?;
            // As the server names it, its Dynamics unresolved.
            alternatives.push((unresolved(name).into_owned(), variant.sql_type().into()));
            variants.push(variant);
        }
        Ok(VariantColumnData {
            variants,
            discriminators,
            offsets,
            sql_type: SqlType::Variant(alternatives).into(),
        })
    }

    /// A column of no rows of `alternatives`, put in the order of their names,
    /// as the server has them.
    pub(crate) fn empty(alternatives: &Alternatives, tz: Tz, capacity: usize) -> Result<Self> {
        if alternatives.is_empty() || alternatives.len() > MAX_ALTERNATIVES {
            return Err(too_many(alternatives.len()));
        }
        let alternatives = &canonical(alternatives);
        let variants = alternatives
            .iter()
            .map(|(_, sql_type)| writable_column(sql_type, tz))
            .collect::<Result<_>>()?;
        Ok(VariantColumnData {
            variants,
            discriminators: Vec::with_capacity(capacity),
            offsets: Vec::with_capacity(capacity),
            sql_type: SqlType::Variant(alternatives.to_vec()).into(),
        })
    }

    /// `column`, of one of `alternatives` (or a Nullable of one), as a
    /// Variant of them.
    pub(crate) fn from_column(
        column: &ArcColumnData,
        alternatives: &Alternatives,
        tz: Tz,
    ) -> Result<Self> {
        let alternatives = &canonical(alternatives);
        let source = column.sql_type();
        let Some(index) = cast_alternative(alternatives, &source) else {
            return Err(Error::Other(
                format!("no alternative of a Variant takes {source}").into(),
            ));
        };
        let target = alternatives[index].1;
        let mut data = VariantColumnData::empty(alternatives, tz, column.len())?;
        let whole = if *target == source {
            Some(column.clone())
        } else {
            column.cast_to(column, target)
        };
        // A string longer than a FixedString would be cut short by its cast too.
        if whole.is_some() && has_fixed_string(target) {
            for row in 0..column.len() {
                let value = match Value::from(column.at(row)) {
                    Value::Nullable(Either::Right(value)) => *value,
                    value => value,
                };
                if !fits(target, &value) {
                    return Err(Error::Other(
                        format!("a value of row {row} does not fit in {target}").into(),
                    ));
                }
            }
        }
        // Chrono times before 1970 or after 2106 would wrap around in a DateTime.
        if whole.is_some()
            && matches!(target, SqlType::DateTime(DateTimeType::DateTime32))
            && matches!(source, SqlType::DateTime(DateTimeType::Chrono))
        {
            let times = chrono_datetime::get_date_slice(&**column)?;
            if let Some(row) = times
                .iter()
                .position(|time| u32::try_from(time.timestamp()).is_err())
            {
                return Err(Error::Other(
                    format!("the time of row {row} is outside the range of {target}").into(),
                ));
            }
        }
        if let Some(alternative) = whole {
            data.variants[index] = alternative;
            data.discriminators.resize(column.len(), index as u8);
            data.offsets.extend(0..column.len());
            return Ok(data);
        }
        if matches!(source, SqlType::DateTime(_)) {
            return Err(Error::Other(
                format!("{source} does not cast to {target}").into(),
            ));
        }
        for row in 0..column.len() {
            let value = match Value::from(column.at(row)) {
                Value::Nullable(Either::Left(_)) => {
                    data.push_null();
                    continue;
                }
                Value::Nullable(Either::Right(value)) => *value,
                value => value,
            };
            if !fits(target, &value) {
                return Err(Error::Other(
                    format!("a value of row {row} does not fit in {target}").into(),
                ));
            }
            data.push_to(index, value);
        }
        Ok(data)
    }

    pub(crate) fn alternatives(&self) -> &'static Alternatives {
        match self.sql_type {
            SqlType::Variant(alternatives) => alternatives,
            _ => unreachable!("a Variant column has a Variant type"),
        }
    }

    /// The alternative of `sql_type`, other than the one named `other_than`.
    pub(crate) fn alternative_of_type(
        &self,
        sql_type: &SqlType,
        other_than: &str,
    ) -> Option<usize> {
        self.alternatives()
            .iter()
            .position(|(name, alternative)| *alternative == sql_type && name != other_than)
    }

    /// Adds an alternative of no rows, and gives its index.
    pub(crate) fn add_alternative(
        &mut self,
        name: String,
        sql_type: &'static SqlType,
        tz: Tz,
    ) -> Result<usize> {
        let mut alternatives = self.alternatives().to_vec();
        if alternatives.len() >= MAX_ALTERNATIVES {
            return Err(too_many(alternatives.len() + 1));
        }
        self.variants.push(writable_column(sql_type, tz)?);
        alternatives.push((name, sql_type));
        self.sql_type = SqlType::Variant(alternatives).into();
        Ok(self.variants.len() - 1)
    }

    /// The index of the alternative named `name`.
    pub(crate) fn alternative_of_name(&self, name: &str) -> Option<usize> {
        self.alternatives()
            .iter()
            .position(|(alternative, _)| alternative == name)
    }

    /// The rows of alternative `index`.
    pub(crate) fn alternative_rows(&self, index: usize) -> usize {
        self.variants[index].len()
    }

    /// This Variant with the rows of alternative `shared`, strings that
    /// `decode` reads as typed values, in new alternatives of their types:
    /// NULL, or a value of the alternative of its name. The other
    /// alternatives keep their columns and rows as they are.
    pub(crate) fn spread<F>(mut self, shared: usize, tz: Tz, mut decode: F) -> Result<Self>
    where
        F: FnMut(&[u8]) -> Result<Option<(String, &'static SqlType, Value)>>,
    {
        let shared_column = std::mem::replace(
            &mut self.variants[shared],
            writable_column(&SqlType::String, tz)?,
        );
        let mut alternatives = self.alternatives().to_vec();
        let existing = alternatives.len();
        for row in 0..self.discriminators.len() {
            let discriminator = self.discriminators[row];
            if discriminator == NULL_DISCRIMINATOR || usize::from(discriminator) != shared {
                continue;
            }
            let ValueRef::String(bytes) = shared_column.at(self.offsets[row]) else {
                return Err(Error::Other("a shared value that is not a string".into()));
            };
            let Some((name, sql_type, value)) = decode(bytes)? else {
                self.discriminators[row] = NULL_DISCRIMINATOR;
                self.offsets[row] = 0;
                continue;
            };
            let index = match alternatives
                .iter()
                .position(|(alternative, _)| *alternative == name)
            {
                Some(index) if index >= existing => index,
                Some(_) => {
                    return Err(Error::Other(
                        format!("a shared value of {name}, a type of the column itself").into(),
                    ))
                }
                None => {
                    if alternatives.len() >= MAX_ALTERNATIVES {
                        return Err(too_many(alternatives.len() + 1));
                    }
                    self.variants.push(loaded_column(&name, tz)?);
                    alternatives.push((name, sql_type));
                    alternatives.len() - 1
                }
            };
            let column = make_mut(&mut self.variants[index]);
            self.offsets[row] = column.len();
            column.push(value);
            self.discriminators[row] = index as u8;
        }
        self.sql_type = SqlType::Variant(alternatives).into();
        Ok(self)
    }

    /// Adds an alternative of no rows of the type named `name`, made as a
    /// column of it read from the server is, and gives its index.
    pub(crate) fn add_named_alternative(
        &mut self,
        name: String,
        sql_type: &'static SqlType,
        tz: Tz,
    ) -> Result<usize> {
        let mut alternatives = self.alternatives().to_vec();
        if alternatives.len() >= MAX_ALTERNATIVES {
            return Err(too_many(alternatives.len() + 1));
        }
        self.variants.push(loaded_column(&name, tz)?);
        alternatives.push((name, sql_type));
        self.sql_type = SqlType::Variant(alternatives).into();
        Ok(self.variants.len() - 1)
    }

    pub(crate) fn clone_data(&self) -> Self {
        VariantColumnData {
            variants: self.variants.clone(),
            discriminators: self.discriminators.clone(),
            offsets: self.offsets.clone(),
            sql_type: self.sql_type,
        }
    }

    /// Appends a non-NULL `value` to alternative `index`.
    pub(crate) fn push_to(&mut self, index: usize, value: Value) {
        let variant = make_mut(&mut self.variants[index]);
        self.offsets.push(variant.len());
        variant.push(value);
        self.discriminators.push(index as u8);
    }

    pub(crate) fn push_null(&mut self) {
        self.discriminators.push(NULL_DISCRIMINATOR);
        self.offsets.push(0);
    }
}

/// An empty column of the type named `name`, as the reader makes it: every
/// DateTime in it, at any depth, is one the server sends, which writes itself.
fn loaded_column(name: &str, tz: Tz) -> Result<ArcColumnData> {
    <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(&mut std::io::empty(), name, 0, tz)
}

/// An empty column of `sql_type` that writes itself: a DateTime is the one
/// the server sends, not a column of chrono times.
fn writable_column(sql_type: &SqlType, tz: Tz) -> Result<ArcColumnData> {
    match sql_type {
        SqlType::DateTime(DateTimeType::DateTime32) => {
            Ok(Arc::new(DateColumnData::<u32>::with_capacity(0, tz)))
        }
        sql_type => <dyn ColumnData>::from_type::<ArcColumnWrapper>(sql_type.clone(), tz, 0),
    }
}

/// The alternative that values of `sql_type` go into: the one of that type,
/// else the LowCardinality one of it, else the one alternative that takes
/// such values (a named tuple, a FixedString for a string, and with `dates`
/// a DateTime of another zone or precision, which only a column's own cast
/// converts without loss); `None` when there is none, or more than one of
/// the last kind.
fn alternative(alternatives: &Alternatives, sql_type: &SqlType, dates: bool) -> Option<usize> {
    let types = || alternatives.iter().map(|(_, sql_type)| *sql_type);
    if let Some(index) = types().position(|variant| variant == sql_type) {
        return Some(index);
    }
    if let Some(index) = types()
        .position(|variant| matches!(variant, SqlType::LowCardinality(inner) if *inner == sql_type))
    {
        return Some(index);
    }
    let mut compatible = types()
        .enumerate()
        .filter(|(_, variant)| takes_values(variant, sql_type, dates))
        .map(|(index, _)| index);
    match (compatible.next(), compatible.next()) {
        (Some(index), None) => Some(index),
        _ => None,
    }
}

/// Whether a column of `target` takes values of `source` as they are. A date
/// of another zone or precision only at the top, and only with `dates`:
/// inside a tuple its value would lose what the other type does not keep.
fn takes_values(target: &SqlType, source: &SqlType, dates: bool) -> bool {
    match (target, source) {
        (SqlType::DateTime(_), SqlType::DateTime(_)) => dates,
        (target, source) => takes_inner_values(target, source),
    }
}

fn takes_inner_values(target: &SqlType, source: &SqlType) -> bool {
    match (target, source) {
        (SqlType::Tuple(targets), SqlType::Tuple(sources)) => {
            targets.len() == sources.len()
                && targets
                    .iter()
                    .zip(sources)
                    .all(|((_, target), (_, source))| {
                        target == source || takes_inner_values(target, source)
                    })
        }
        (SqlType::FixedString(_), SqlType::String) => true,
        _ => false,
    }
}

/// Whether a column of `sql_type` made from values holds a DateTime as chrono
/// times somewhere below its top, which it does not write (a DateTime64 is
/// made as its ticks, which it writes).
fn has_chrono_child(sql_type: &SqlType) -> bool {
    let chrono = |inner: &SqlType| match inner {
        SqlType::DateTime(DateTimeType::DateTime64(..)) => false,
        SqlType::DateTime(_) => true,
        inner => has_chrono_child(inner),
    };
    match sql_type {
        SqlType::Nullable(inner)
        | SqlType::Array(inner)
        | SqlType::LowCardinality(inner)
        | SqlType::SimpleAggregateFunction(_, inner) => chrono(inner),
        SqlType::Map(keys, values) => chrono(keys) || chrono(values),
        SqlType::Tuple(elements) => elements.iter().any(|(_, element)| chrono(element)),
        _ => false,
    }
}

/// Whether a value of `sql_type` holds a date or time anywhere: a column of
/// it made from values keeps them as chrono times, which it does not write.
fn has_datetime(sql_type: &SqlType) -> bool {
    match sql_type {
        SqlType::DateTime(_) => true,
        SqlType::Nullable(inner)
        | SqlType::Array(inner)
        | SqlType::LowCardinality(inner)
        | SqlType::SimpleAggregateFunction(_, inner) => has_datetime(inner),
        SqlType::Map(keys, values) => has_datetime(keys) || has_datetime(values),
        SqlType::Tuple(elements) => elements.iter().any(|(_, element)| has_datetime(element)),
        SqlType::Variant(alternatives) => alternatives.iter().any(|(_, t)| has_datetime(t)),
        _ => false,
    }
}

impl ColumnData for VariantColumnData {
    fn sql_type(&self) -> SqlType {
        self.sql_type.clone()
    }

    /// The discriminators of the rows, then the rows of each alternative
    /// among them (those of one alternative follow one another in its
    /// column), in the order of the names of the alternatives.
    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        let order = name_order(self.alternatives());
        if order
            .iter()
            .enumerate()
            .all(|(position, &index)| position == index)
        {
            encoder.write_bytes(&self.discriminators[start..end]);
        } else {
            let mut rank = vec![0_u8; order.len()];
            for (position, &index) in order.iter().enumerate() {
                rank[index] = position as u8;
            }
            for &discriminator in &self.discriminators[start..end] {
                encoder.write(match discriminator {
                    NULL_DISCRIMINATOR => NULL_DISCRIMINATOR,
                    discriminator => rank[usize::from(discriminator)],
                });
            }
        }
        let mut ranges = vec![None::<(usize, usize)>; self.variants.len()];
        for row in start..end {
            let discriminator = self.discriminators[row];
            if discriminator == NULL_DISCRIMINATOR {
                continue;
            }
            let offset = self.offsets[row];
            let range = &mut ranges[usize::from(discriminator)];
            *range = Some(match *range {
                None => (offset, offset + 1),
                Some((first, _)) => (first, offset + 1),
            });
        }
        // No rows of an alternative are no bytes of it, whatever its type.
        for index in order {
            if let Some((first, last)) = ranges[index] {
                self.variants[index].save(encoder, first, last);
            }
        }
    }

    fn len(&self) -> usize {
        self.discriminators.len()
    }

    /// A value of one of the types, or NULL; a value no alternative takes
    /// panics, as a value of the wrong type does in any column.
    fn push(&mut self, value: Value) {
        let value = match value {
            Value::Nullable(Either::Left(_)) => return self.push_null(),
            Value::Nullable(Either::Right(inner)) => *inner,
            value => value,
        };
        let sql_type = SqlType::from(value.clone());
        let Some(index) = alternative(self.alternatives(), &sql_type, false) else {
            panic!(
                "no alternative, or more than one, of {} takes {sql_type}",
                self.sql_type
            );
        };
        self.push_to(index, value);
    }

    /// NULL, or the value of the row's alternative: read as an `Option` of
    /// that alternative's type.
    fn at(&self, index: usize) -> ValueRef<'_> {
        match self.discriminators[index] {
            NULL_DISCRIMINATOR => ValueRef::Nullable(Either::Left(self.sql_type)),
            discriminator => {
                let value = self.variants[usize::from(discriminator)].at(self.offsets[index]);
                ValueRef::Nullable(Either::Right(Box::new(value)))
            }
        }
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(VariantColumnData {
            variants: self.variants.clone(),
            discriminators: self.discriminators.clone(),
            offsets: self.offsets.clone(),
            sql_type: self.sql_type,
        })
    }

    fn get_timezone(&self) -> Option<Tz> {
        None
    }

    fn variant_parts(&self) -> Option<(&[u8], &[usize], &[ArcColumnData])> {
        Some((&self.discriminators, &self.offsets, &self.variants))
    }

    /// The discriminators' mode, then the prefixes of the alternatives in the
    /// order of their names, from their data (a Dynamic inside names its
    /// types there).
    fn save_prefix(&self, encoder: &mut Encoder) {
        encoder.write(BASIC_DISCRIMINATORS);
        for index in name_order(self.alternatives()) {
            self.variants[index].save_prefix(encoder);
        }
    }
}

/// The alternative a column of `source` goes into on insert: one of the
/// types, LowCardinality of it, or a Nullable of either. A date or time goes
/// only into a date or time alternative, as it is or through the column's own
/// cast (which keeps fractions of a second): the values of a Nullable one, or
/// a LowCardinality dictionary of them, would lose them; and values of
/// another type do not go into an alternative with dates in it.
fn cast_alternative(alternatives: &Alternatives, source: &SqlType) -> Option<usize> {
    let (inner, nullable) = match source {
        SqlType::Nullable(inner) => (*inner, true),
        source => (source, false),
    };
    let index = alternative(alternatives, inner, true)?;
    let target = alternatives[index].1;
    let dated = matches!(inner, SqlType::DateTime(_));
    if dated && (nullable || matches!(target, SqlType::LowCardinality(_))) {
        return None;
    }
    // By values a nested Variant would choose its alternatives by the values'
    // types, not keep them.
    if !dated && *target != *source && (has_datetime(target) || has_variant(target)) {
        return None;
    }
    Some(index)
}

/// Whether `sql_type` holds a Variant anywhere.
fn has_variant(sql_type: &SqlType) -> bool {
    match sql_type {
        SqlType::Variant(_) => true,
        SqlType::Nullable(inner)
        | SqlType::Array(inner)
        | SqlType::LowCardinality(inner)
        | SqlType::SimpleAggregateFunction(_, inner) => has_variant(inner),
        SqlType::Map(keys, values) => has_variant(keys) || has_variant(values),
        SqlType::Tuple(elements) => elements.iter().any(|(_, element)| has_variant(element)),
        _ => false,
    }
}

/// Whether `value` fits a column of `target` whole: a string not longer than
/// a FixedString, also inside a tuple, an array or a map; it would be cut
/// short there.
fn fits(target: &SqlType, value: &Value) -> bool {
    match (target, value) {
        (SqlType::FixedString(len), Value::String(bytes)) => bytes.len() <= *len,
        (SqlType::Nullable(inner), Value::Nullable(Either::Right(value))) => fits(inner, value),
        (SqlType::Tuple(elements), Value::Tuple(values)) => elements
            .iter()
            .zip(values.iter())
            .all(|((_, element), value)| fits(element, value)),
        (SqlType::Array(inner), Value::Array(_, values)) => {
            values.iter().all(|value| fits(inner, value))
        }
        (SqlType::Map(keys, values), Value::Map(_, _, entries)) => entries
            .iter()
            .all(|(key, value)| fits(keys, key) && fits(values, value)),
        _ => true,
    }
}

/// Whether a chrono time fits a DateTime32 alternative, seconds from 1970 in
/// an UInt32; it would wrap around there.
fn in_range(target: &SqlType, value: &Value) -> bool {
    match (target, value) {
        (SqlType::DateTime(DateTimeType::DateTime32), Value::ChronoDateTime(time)) => {
            u32::try_from(time.timestamp()).is_ok()
        }
        _ => true,
    }
}

/// Whether `sql_type` holds a FixedString anywhere.
fn has_fixed_string(sql_type: &SqlType) -> bool {
    match sql_type {
        SqlType::FixedString(_) => true,
        SqlType::Nullable(inner)
        | SqlType::Array(inner)
        | SqlType::LowCardinality(inner)
        | SqlType::SimpleAggregateFunction(_, inner) => has_fixed_string(inner),
        SqlType::Map(keys, values) => has_fixed_string(keys) || has_fixed_string(values),
        SqlType::Tuple(elements) => elements
            .iter()
            .any(|(_, element)| has_fixed_string(element)),
        SqlType::Variant(alternatives) => alternatives.iter().any(|(_, t)| has_fixed_string(t)),
        _ => false,
    }
}

/// Whether every Variant in a column of `sql_type`, at any depth, takes its
/// part of `value`.
pub(crate) fn variants_take(sql_type: &SqlType, value: &Value) -> bool {
    // The values of a type with no Variant in it are not walked through.
    if !has_variant(sql_type) {
        return true;
    }
    match (sql_type, value) {
        (SqlType::Variant(alternatives), value) => takes_value(alternatives, value),
        // As a Nullable column takes a value: NULL, its inner value, or a bare
        // one it hands on.
        (SqlType::Nullable(_), Value::Nullable(Either::Left(_))) => true,
        (SqlType::Nullable(inner), Value::Nullable(Either::Right(value))) => {
            variants_take(inner, value)
        }
        (SqlType::Nullable(inner), value) | (SqlType::SimpleAggregateFunction(_, inner), value) => {
            variants_take(inner, value)
        }
        (SqlType::Array(inner), Value::Array(_, values)) => {
            values.iter().all(|value| variants_take(inner, value))
        }
        (SqlType::Tuple(elements), Value::Tuple(values)) => elements
            .iter()
            .zip(values.iter())
            .all(|((_, element), value)| variants_take(element, value)),
        (SqlType::Map(keys, values), Value::Map(_, _, entries)) => entries
            .iter()
            .all(|(key, value)| variants_take(keys, key) && variants_take(values, value)),
        _ => true,
    }
}

/// Whether a Variant of `alternatives` takes `value`: NULL, or a value of one
/// alternative (and only one of the kind that takes other types' values)
/// that fits it.
pub(crate) fn takes_value(alternatives: &Alternatives, value: &Value) -> bool {
    let value = match value {
        Value::Nullable(Either::Left(_)) => return true,
        Value::Nullable(Either::Right(inner)) => inner,
        value => value,
    };
    alternative(alternatives, &SqlType::from(value.clone()), false).is_some_and(|index| {
        let target = alternatives[index].1;
        fits(target, value)
            && in_range(target, value)
            && (!has_checked_leaf(target) || leaves_fit(target, value))
            && check_decimal_push("", target, value).is_ok()
            && variants_take(target, value)
            // A date inside another type is built as a chrono time, which a
            // column made from values does not write.
            && !has_chrono_child(target)
    })
}

/// Whether a Variant of `alternatives` takes a column of `source` on insert.
pub(crate) fn takes(alternatives: &Alternatives, source: &SqlType) -> bool {
    cast_alternative(alternatives, source).is_some()
}

/// `column` in a Variant of `alternatives`, every row in the alternative of
/// the column's type, a NULL staying NULL. A column of exactly that type, or
/// one that casts itself to it, is that alternative as it is.
pub(crate) fn cast_to_variant(
    column: &ArcColumnData,
    alternatives: &Alternatives,
    tz: Tz,
) -> Result<ArcColumnData> {
    Ok(Arc::new(VariantColumnData::from_column(
        column,
        alternatives,
        tz,
    )?))
}

#[cfg(test)]
mod test {
    use std::io::Cursor;

    use chrono::{DateTime, TimeZone};

    use super::*;
    use crate::types::{column::ColumnFrom, DateTimeType};

    fn texts(column: &(dyn ColumnData + Send + Sync)) -> Vec<String> {
        (0..column.len())
            .map(|row| Value::from(column.at(row)).to_string())
            .collect()
    }

    /// Alternatives named as their types print.
    fn named(types: &[&'static SqlType]) -> Vec<(String, &'static SqlType)> {
        types
            .iter()
            .map(|&t| (t.to_string().into_owned(), t))
            .collect()
    }

    #[test]
    fn test_parse_variant_type() {
        assert_eq!(
            parse_variant_type("Variant(Array(UInt8), String, UInt64)"),
            Some(vec!["Array(UInt8)", "String", "UInt64"])
        );
        assert_eq!(
            parse_variant_type("Variant(Map(String, UInt8), Tuple(a UInt8, b String))"),
            Some(vec!["Map(String, UInt8)", "Tuple(a UInt8, b String)"])
        );
        assert_eq!(parse_variant_type("Variant()"), None);
        assert_eq!(parse_variant_type("Tuple(UInt8)"), None);
        // 255 alternatives, discriminators 0 to 254, and not one more.
        let names = |count: usize| -> String {
            let types: Vec<String> = (0..count)
                .map(|i| format!("FixedString({})", i + 1))
                .collect();
            format!("Variant({})", types.join(", "))
        };
        assert_eq!(parse_variant_type(&names(255)).map(|t| t.len()), Some(255));
        assert_eq!(parse_variant_type(&names(256)), None);
        let types: Vec<&'static SqlType> =
            (1..=256).map(|n| SqlType::FixedString(n).into()).collect();
        assert!(VariantColumnData::empty(&named(&types[..255]), Tz::UTC, 0).is_ok());
        assert!(VariantColumnData::empty(&named(&types), Tz::UTC, 0).is_err());
    }

    #[test]
    fn test_load_save_and_values() {
        // Five rows of Variant(String, UInt64): 'a', 7, NULL, 'bc', 9.
        let mut encoder = Encoder::new();
        encoder.write_bytes(&[0, 1, NULL_DISCRIMINATOR, 0, 1]);
        encoder.string("a");
        encoder.string("bc");
        encoder.write(7_u64);
        encoder.write(9_u64);
        let bytes = encoder.get_buffer();
        let mut cursor = Cursor::new(&bytes[..]);
        let column =
            VariantColumnData::load(&mut cursor, vec!["String", "UInt64"], 5, Tz::UTC).unwrap();
        assert_eq!(cursor.position() as usize, bytes.len());
        assert_eq!(column.sql_type().to_string(), "Variant(String, UInt64)");
        assert_eq!(texts(&column), ["a", "7", "NULL", "bc", "9"]);

        // Saved whole, the bytes it came from.
        let mut saved = Encoder::new();
        column.save(&mut saved, 0, 5);
        assert_eq!(saved.get_buffer(), bytes);

        // A range: NULL, 'bc', 9.
        let mut saved = Encoder::new();
        column.save(&mut saved, 2, 5);
        let mut expected = Encoder::new();
        expected.write_bytes(&[NULL_DISCRIMINATOR, 0, 1]);
        expected.string("bc");
        expected.write(9_u64);
        assert_eq!(saved.get_buffer(), expected.get_buffer());

        // A discriminator past the types is an error.
        let bytes = [2_u8];
        let err = VariantColumnData::load(&mut Cursor::new(&bytes[..]), vec!["String"], 1, Tz::UTC)
            .err()
            .expect("an unknown discriminator");
        assert!(err.to_string().contains("discriminator 2"), "{err}");
    }

    #[test]
    fn test_names_are_kept_and_written_in_their_order() {
        // The server's Variant(Point, String): the point is read as a tuple,
        // and named, typed and written as the point it is.
        let mut encoder = Encoder::new();
        encoder.write_bytes(&[0, 1, NULL_DISCRIMINATOR]);
        encoder.write(1.5_f64);
        encoder.write(2.5_f64);
        encoder.string("x");
        let bytes = encoder.get_buffer();
        let column = VariantColumnData::load(
            &mut Cursor::new(&bytes[..]),
            vec!["Point", "String"],
            3,
            Tz::UTC,
        )
        .unwrap();
        assert_eq!(column.sql_type().to_string(), "Variant(Point, String)");
        assert_eq!(texts(&column), ["(1.5, 2.5)", "x", "NULL"]);
        let mut saved = Encoder::new();
        column.save(&mut saved, 0, 3);
        assert_eq!(saved.get_buffer(), bytes);

        // Alternatives made in another order are written in that of names.
        let alternatives = vec![
            ("UInt64".to_owned(), &SqlType::UInt64),
            ("String".to_owned(), &SqlType::String),
        ];
        let mut column = VariantColumnData::empty(&alternatives, Tz::UTC, 2).unwrap();
        column.push(Value::from(7_u64));
        column.push(Value::from("y"));
        assert_eq!(column.sql_type().to_string(), "Variant(String, UInt64)");
        let mut saved = Encoder::new();
        column.save(&mut saved, 0, 2);
        let mut expected = Encoder::new();
        expected.write_bytes(&[1, 0]);
        expected.string("y");
        expected.write(7_u64);
        assert_eq!(saved.get_buffer(), expected.get_buffer());
    }

    #[test]
    fn test_push_and_cast() {
        let alternatives = named(&[
            SqlType::LowCardinality(&SqlType::String).into(),
            SqlType::UInt64.into(),
        ]);
        let mut column = VariantColumnData::empty(&alternatives, Tz::UTC, 3).unwrap();
        column.push(Value::from(5_u64));
        column.push(Value::Nullable(Either::Left(SqlType::UInt64.into())));
        column.push(Value::from("x"));
        assert_eq!(texts(&column), ["5", "NULL", "x"]);
        assert_eq!(column.offsets, [0, 0, 0]);

        // A column of one of the types, Nullable too.
        assert!(takes(&alternatives, &SqlType::Nullable(&SqlType::UInt64)));
        assert!(takes(&alternatives, &SqlType::String));
        assert!(!takes(&alternatives, &SqlType::Int64));
        let mut nullable = <dyn ColumnData>::from_type::<ArcColumnWrapper>(
            SqlType::Nullable(&SqlType::UInt64),
            Tz::UTC,
            2,
        )
        .unwrap();
        let data = make_mut(&mut nullable);
        data.push(Value::Nullable(Either::Left(SqlType::UInt64.into())));
        data.push(Value::Nullable(Either::Right(Box::new(Value::from(3_u64)))));
        let cast = cast_to_variant(&nullable, &alternatives, Tz::UTC).unwrap();
        assert_eq!(texts(&*cast), ["NULL", "3"]);
        assert_eq!(
            cast.sql_type().to_string(),
            "Variant(LowCardinality(String), UInt64)"
        );

        // A column of exactly one of the types is that alternative.
        let numbers: ArcColumnData =
            <Vec<u64> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![8]);
        let cast = cast_to_variant(&numbers, &alternatives, Tz::UTC).unwrap();
        let (discriminators, _, variants) = cast.variant_parts().unwrap();
        assert_eq!(discriminators, [1]);
        assert!(Arc::ptr_eq(&variants[1], &numbers));
    }

    #[test]
    fn test_values_that_alternatives_take() {
        // A tuple value has no names; the named tuple alternative takes it.
        let tuple = SqlType::Tuple(vec![(Some("a".into()), SqlType::UInt8.into())]);
        let alternatives = named(&[tuple.into(), SqlType::UInt64.into()]);
        let mut column = VariantColumnData::empty(&alternatives, Tz::UTC, 1).unwrap();
        column.push(Value::Tuple(Arc::new(vec![Value::from(1_u8)])));
        assert_eq!(column.discriminators, [0]);
        // A string goes into the one FixedString; two of them are ambiguous.
        let fixed = named(&[SqlType::FixedString(2).into()]);
        assert_eq!(alternative(&fixed, &SqlType::String, false), Some(0));
        let two = named(&[
            SqlType::FixedString(2).into(),
            SqlType::FixedString(3).into(),
        ]);
        assert_eq!(alternative(&two, &SqlType::String, false), None);
        // A tuple with a date, by values, would lose it.
        let date_time: &'static SqlType = SqlType::DateTime(DateTimeType::DateTime32).into();
        let dated = named(&[SqlType::Tuple(vec![(Some("t".into()), date_time)]).into()]);
        assert!(!takes(&dated, &SqlType::Tuple(vec![(None, date_time)])));
    }

    #[test]
    fn test_alternatives_with_and_without_rows_are_written() {
        let date_time: &'static SqlType = SqlType::DateTime(DateTimeType::DateTime32).into();
        let alternatives = vec![
            ("DateTime('UTC')".to_owned(), date_time),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ];

        // Numbers only: the DateTime alternative has no rows and no bytes.
        let numbers: ArcColumnData =
            <Vec<u64> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![4, 5]);
        let cast = cast_to_variant(&numbers, &alternatives, Tz::UTC).unwrap();
        assert_eq!(
            cast.sql_type().to_string(),
            "Variant(DateTime('UTC'), UInt64)"
        );
        let mut encoder = Encoder::new();
        cast.save(&mut encoder, 0, 2);
        let mut expected = Encoder::new();
        expected.write_bytes(&[1, 1]);
        expected.write(4_u64);
        expected.write(5_u64);
        assert_eq!(encoder.get_buffer(), expected.get_buffer());

        // Chrono times go into the DateTime alternative as its seconds.
        let time: DateTime<Tz> = Tz::UTC.with_ymd_and_hms(2026, 11, 28, 0, 0, 0).unwrap();
        let times: ArcColumnData =
            <Vec<DateTime<Tz>> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![time]);
        let cast = cast_to_variant(&times, &alternatives, Tz::UTC).unwrap();
        let mut encoder = Encoder::new();
        cast.save(&mut encoder, 0, 1);
        let mut expected = Encoder::new();
        expected.write_bytes(&[0]);
        expected.write(time.timestamp() as u32);
        assert_eq!(encoder.get_buffer(), expected.get_buffer());

        // Not those before 1970, which would wrap around.
        let early: DateTime<Tz> = Tz::UTC.with_ymd_and_hms(1969, 12, 31, 23, 59, 59).unwrap();
        let early: ArcColumnData =
            <Vec<DateTime<Tz>> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![time, early]);
        let err = cast_to_variant(&early, &alternatives, Tz::UTC)
            .err()
            .expect("a time before 1970");
        assert!(err.to_string().contains("row 1"), "{err}");
        assert!(!takes_value(
            &alternatives,
            &Value::ChronoDateTime(Tz::UTC.with_ymd_and_hms(1969, 1, 1, 0, 0, 0).unwrap())
        ));

        // And into a DateTime64 one with their fractions of a second.
        let ticks: &'static SqlType =
            SqlType::DateTime(DateTimeType::DateTime64(3, Tz::UTC)).into();
        let precise = vec![
            ("DateTime64(3, 'UTC')".to_owned(), ticks),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ];
        let time = time + chrono::Duration::milliseconds(250);
        let times: ArcColumnData =
            <Vec<DateTime<Tz>> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![time]);
        let cast = cast_to_variant(&times, &precise, Tz::UTC).unwrap();
        let mut encoder = Encoder::new();
        cast.save(&mut encoder, 0, 1);
        let mut expected = Encoder::new();
        expected.write_bytes(&[0]);
        expected.write(time.timestamp_millis());
        assert_eq!(encoder.get_buffer(), expected.get_buffer());

        // Nullable dates, and dates into a LowCardinality dictionary, would
        // lose their fractions: they are not taken.
        assert!(!takes(&precise, &SqlType::Nullable(date_time)));
        let low = named(&[SqlType::LowCardinality(date_time).into()]);
        assert!(!takes(&low, date_time));
        assert!(takes(&alternatives, date_time));
    }
}

#[cfg(test)]
mod checks {
    use std::io::Cursor;

    use super::*;
    use crate::{
        row,
        types::{column::ColumnFrom, Block, Simple},
    };

    #[test]
    fn test_strings_too_long_for_a_fixed_string() {
        let alternatives = vec![
            ("FixedString(2)".to_owned(), SqlType::FixedString(2).into()),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ];
        let fit: ArcColumnData =
            <Vec<&str> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec!["ab", "c"]);
        assert!(cast_to_variant(&fit, &alternatives, Tz::UTC).is_ok());
        let long: ArcColumnData =
            <Vec<&str> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec!["ab", "abc"]);
        let err = cast_to_variant(&long, &alternatives, Tz::UTC)
            .err()
            .expect("a string longer than the FixedString");
        assert!(err.to_string().contains("row 1"), "{err}");
        assert!(!takes_value(&alternatives, &Value::from("abc")));
        assert!(takes_value(&alternatives, &Value::from(3_u64)));

        // In a tuple too, where the column casts itself.
        let fixed_tuple: &'static SqlType =
            SqlType::Tuple(vec![(None, SqlType::FixedString(2).into())]).into();
        let tuples = vec![("Tuple(FixedString(2))".to_owned(), fixed_tuple)];
        let long: ArcColumnData =
            <Vec<(String,)> as ColumnFrom>::column_from::<ArcColumnWrapper>(vec![("abc".into(),)]);
        assert!(cast_to_variant(&long, &tuples, Tz::UTC).is_err());

        // A date the Date32 reader would reject, and a date inside a tuple of a
        // column made from values.
        let dates32 = vec![("Date32".to_owned(), &SqlType::Date32)];
        assert!(!takes_value(&dates32, &Value::Date32(i32::MAX)));
        assert!(takes_value(&dates32, &Value::Date32(0)));
        let date_time32: &'static SqlType = SqlType::DateTime(DateTimeType::DateTime32).into();
        let dated_tuple: &'static SqlType = SqlType::Tuple(vec![(None, date_time32)]).into();
        let tuples_of_dates = vec![("Tuple(DateTime)".to_owned(), dated_tuple)];
        assert!(!takes_value(
            &tuples_of_dates,
            &Value::Tuple(Arc::new(vec![Value::DateTime(5, Tz::UTC)]))
        ));
        // A DateTime64 inside one is made as its ticks and written.
        let ticks: &'static SqlType =
            SqlType::DateTime(DateTimeType::DateTime64(3, Tz::UTC)).into();
        let arrays_of_ticks = vec![(
            "Array(DateTime64(3, 'UTC'))".to_owned(),
            SqlType::Array(ticks).into(),
        )];
        let tick_values = Value::Array(ticks, Arc::new(vec![Value::DateTime64(5, (3, Tz::UTC))]));
        assert!(takes_value(&arrays_of_ticks, &tick_values));
        let mut column = VariantColumnData::empty(&arrays_of_ticks, Tz::UTC, 1).unwrap();
        column.push(tick_values);
        let mut encoder = Encoder::new();
        column.save(&mut encoder, 0, 1);
        let mut expected = Encoder::new();
        expected.write_bytes(&[0]);
        expected.write(1_u64);
        expected.write(5_i64);
        assert_eq!(encoder.get_buffer(), expected.get_buffer());

        // Alternatives made in any order are the server's, in that of names.
        let reversed = vec![
            ("UInt64".to_owned(), &SqlType::UInt64),
            ("String".to_owned(), &SqlType::String),
        ];
        let column = VariantColumnData::empty(&reversed, Tz::UTC, 0).unwrap();
        assert_eq!(
            column.sql_type(),
            SqlType::Variant(vec![
                ("String".to_owned(), &SqlType::String),
                ("UInt64".to_owned(), &SqlType::UInt64),
            ])
        );

        // A time of another precision is no value of a DateTime alternative.
        let date_time: &'static SqlType = SqlType::DateTime(DateTimeType::DateTime32).into();
        let dates = vec![("DateTime".to_owned(), date_time)];
        assert!(takes_value(&dates, &Value::DateTime(5, Tz::UTC)));
        assert!(!takes_value(&dates, &Value::DateTime64(-5, (3, Tz::UTC))));
    }

    #[test]
    fn test_a_pushed_date_time_is_written() {
        let date_time: &'static SqlType = SqlType::DateTime(DateTimeType::DateTime32).into();
        let alternatives = vec![
            ("DateTime".to_owned(), date_time),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ];
        let mut column = VariantColumnData::empty(&alternatives, Tz::UTC, 1).unwrap();
        column.push(Value::DateTime(1_700_000_000, Tz::UTC));
        let mut encoder = Encoder::new();
        column.save(&mut encoder, 0, 1);
        let mut expected = Encoder::new();
        expected.write_bytes(&[0]);
        expected.write(1_700_000_000_u32);
        assert_eq!(encoder.get_buffer(), expected.get_buffer());
    }

    #[test]
    fn test_a_value_no_alternative_takes_is_an_error() {
        // A block of one Variant(String, UInt64) row, 'a'.
        let mut encoder = Encoder::new();
        encoder.write_bytes(&[1, 0, 2, 0xff, 0xff, 0xff, 0xff, 0]);
        encoder.uvarint(1);
        encoder.uvarint(1);
        encoder.string("v");
        encoder.string("Variant(String, UInt64)");
        encoder.write(0_u8);
        encoder.write(BASIC_DISCRIMINATORS);
        encoder.write_bytes(&[0]);
        encoder.string("a");
        let bytes = encoder.get_buffer();
        let mut block =
            Block::<Simple>::load(&mut Cursor::new(&bytes[..]), Tz::UTC, false, 54491).unwrap();
        assert!(block.push(row! { v: 1_i64 }).is_err());
        block.push(row! { v: 2_u64 }).unwrap();
        assert_eq!(block.row_count(), 2);

        // And inside an array.
        let variant: &'static SqlType = SqlType::Variant(vec![
            ("String".to_owned(), &SqlType::String),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ])
        .into();
        let array = SqlType::Array(variant);
        assert!(!variants_take(
            &array,
            &Value::Array(&SqlType::Int64, Arc::new(vec![Value::from(1_i64)]))
        ));
        assert!(variants_take(
            &array,
            &Value::Array(&SqlType::UInt64, Arc::new(vec![Value::from(1_u64)]))
        ));
    }
}

/// Whether a Variant of `alternatives` has every alternative of `source`, a
/// Variant: the server converts such a Variant into it, and so does the
/// client on insert.
pub(crate) fn extends(alternatives: &Alternatives, source: &SqlType) -> bool {
    match source {
        SqlType::Variant(sources) => sources.iter().all(|source| alternatives.contains(source)),
        _ => false,
    }
}

/// A Variant `column` in a Variant of `alternatives` that has all of its
/// alternatives: the rows of each as they are, the discriminators renumbered.
pub(crate) fn cast_variant(
    column: &ArcColumnData,
    alternatives: &Alternatives,
    tz: Tz,
) -> Result<ArcColumnData> {
    Ok(Arc::new(widened(column, alternatives, tz)?))
}

/// A Variant `column` as a Variant of `alternatives`, which has all of its
/// alternatives.
pub(crate) fn widened(
    column: &ArcColumnData,
    alternatives: &Alternatives,
    tz: Tz,
) -> Result<VariantColumnData> {
    let alternatives = canonical(alternatives);
    let source = column.sql_type();
    let (SqlType::Variant(sources), Some((discriminators, offsets, children))) =
        (&source, column.variant_parts())
    else {
        return Err(Error::Other(
            format!("{source} is not a Variant column").into(),
        ));
    };
    let mut targets = Vec::with_capacity(sources.len());
    for alternative in sources {
        match alternatives.iter().position(|target| target == alternative) {
            Some(index) => targets.push(index),
            None => {
                return Err(Error::Other(
                    format!(
                        "{} has no alternative {}",
                        SqlType::Variant(alternatives),
                        alternative.0
                    )
                    .into(),
                ))
            }
        }
    }
    let mut data = VariantColumnData::empty(&alternatives, tz, discriminators.len())?;
    for (child, &target) in children.iter().zip(&targets) {
        data.variants[target] = child.clone();
    }
    data.discriminators.extend(
        discriminators
            .iter()
            .map(|&discriminator| match discriminator {
                NULL_DISCRIMINATOR => NULL_DISCRIMINATOR,
                discriminator => targets[usize::from(discriminator)] as u8,
            }),
    );
    data.offsets.extend_from_slice(offsets);
    Ok(data)
}

#[cfg(test)]
mod subsets {
    use std::io::Cursor;

    use super::*;

    #[test]
    fn test_a_variant_into_one_with_more_alternatives() {
        // Variant(String, UInt64): 'a', NULL, 7.
        let mut encoder = Encoder::new();
        encoder.write_bytes(&[0, NULL_DISCRIMINATOR, 1]);
        encoder.string("a");
        encoder.write(7_u64);
        let bytes = encoder.get_buffer();
        let column: ArcColumnData = Arc::new(
            VariantColumnData::load(
                &mut Cursor::new(&bytes[..]),
                vec!["String", "UInt64"],
                3,
                Tz::UTC,
            )
            .unwrap(),
        );
        let wider = vec![
            ("Int8".to_owned(), &SqlType::Int8),
            ("String".to_owned(), &SqlType::String),
            ("UInt64".to_owned(), &SqlType::UInt64),
        ];
        assert!(extends(&wider, &column.sql_type()));
        assert!(!extends(&wider[..2], &column.sql_type()));
        let cast = cast_variant(&column, &wider, Tz::UTC).unwrap();
        assert_eq!(cast.sql_type().to_string(), "Variant(Int8, String, UInt64)");
        let (discriminators, _, _) = cast.variant_parts().unwrap();
        assert_eq!(discriminators, [1, NULL_DISCRIMINATOR, 2]);
        let texts: Vec<String> = (0..3)
            .map(|row| Value::from(cast.at(row)).to_string())
            .collect();
        assert_eq!(texts, ["a", "NULL", "7"]);
        let mut saved = Encoder::new();
        cast.save(&mut saved, 0, 3);
        let mut expected = Encoder::new();
        expected.write_bytes(&[1, NULL_DISCRIMINATOR, 2]);
        expected.string("a");
        expected.write(7_u64);
        assert_eq!(saved.get_buffer(), expected.get_buffer());
    }
}