clickhouse-native-client 0.1.0

Async ClickHouse client using the native TCP protocol with LZ4/ZSTD compression and TLS support
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
//! Date and DateTime column implementations
//!
//! **ClickHouse Documentation:**
//! - [Date](https://clickhouse.com/docs/en/sql-reference/data-types/date) -
//!   Days since 1970-01-01 (UInt16)
//! - [Date32](https://clickhouse.com/docs/en/sql-reference/data-types/date32)
//!   - Extended range date (Int32)
//! - [DateTime](https://clickhouse.com/docs/en/sql-reference/data-types/datetime)
//!   - Unix timestamp (UInt32)
//! - [DateTime64](https://clickhouse.com/docs/en/sql-reference/data-types/datetime64)
//!   - High-precision timestamp (Int64)
//!
//! ## Storage Details
//!
//! | Type | Storage | Range | Precision |
//! |------|---------|-------|-----------|
//! | `Date` | UInt16 | 1970-01-01 to 2149-06-06 | 1 day |
//! | `Date32` | Int32 | 1900-01-01 to 2299-12-31 | 1 day |
//! | `DateTime` | UInt32 | 1970-01-01 00:00:00 to 2106-02-07 06:28:15 UTC | 1 second |
//! | `DateTime64(P)` | Int64 | Large range | 10^-P seconds (P=0..9) |
//!
//! ## Timezones
//!
//! `DateTime` and `DateTime64` support optional timezone parameter:
//! - `DateTime('UTC')` - Store as UTC timestamp
//! - `DateTime('Europe/Moscow')` - Store with timezone info
//!
//! The timezone affects how values are displayed and interpreted, but storage
//! is always in Unix time.

use super::{
    Column,
    ColumnRef,
};
use crate::{
    types::Type,
    Error,
    Result,
};
use bytes::BytesMut;
use std::sync::Arc;

const SECONDS_PER_DAY: i64 = 86400;

/// Column for Date type (stored as UInt16 - days since Unix epoch 1970-01-01)
///
/// **Range:** 1970-01-01 to 2149-06-06
///
/// **ClickHouse Reference:** <https://clickhouse.com/docs/en/sql-reference/data-types/date>
///
/// **C++ Implementation Pattern:**
/// Uses delegation to `ColumnUInt16` for storage, matching the C++
/// clickhouse-cpp reference implementation's `std::shared_ptr<ColumnUInt16>
/// data_` pattern.
pub struct ColumnDate {
    type_: Type,
    data: Arc<super::ColumnUInt16>, /* Delegates to ColumnUInt16, matches
                                     * C++ pattern */
}

impl ColumnDate {
    /// Creates a new empty Date column with the given type.
    pub fn new(type_: Type) -> Self {
        Self { type_, data: Arc::new(super::ColumnUInt16::new()) }
    }

    /// Returns a new column populated with the given days-since-epoch values.
    pub fn with_data(mut self, data: Vec<u16>) -> Self {
        self.data =
            Arc::new(super::ColumnUInt16::from_vec(Type::uint16(), data));
        self
    }

    /// Append days since epoch (raw UInt16 value)
    pub fn append(&mut self, days: u16) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append(days);
    }

    /// Append from Unix timestamp (seconds since epoch)
    pub fn append_timestamp(&mut self, timestamp: i64) {
        let days = (timestamp / SECONDS_PER_DAY) as u16;
        self.append(days);
    }

    /// Get raw days value at index
    pub fn at(&self, index: usize) -> u16 {
        self.data.at(index)
    }

    /// Get Unix timestamp (seconds) at index
    pub fn timestamp_at(&self, index: usize) -> i64 {
        self.data.at(index) as i64 * SECONDS_PER_DAY
    }

    /// Returns the number of elements in the column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if the column contains no elements.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get reference to underlying data column (for advanced use)
    pub fn data(&self) -> &super::ColumnUInt16 {
        &self.data
    }
}

impl Column for ColumnDate {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.size()
    }

    fn clear(&mut self) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot clear shared column")
            .clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot reserve on shared column")
            .reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other =
            other.as_any().downcast_ref::<ColumnDate>().ok_or_else(|| {
                Error::TypeMismatch {
                    expected: self.type_.name(),
                    actual: other.column_type().name(),
                }
            })?;

        // Delegate to underlying ColumnUInt16
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append_column(other.data.clone() as ColumnRef)?;
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        // Delegate to ColumnUInt16 which has bulk copy optimization
        Arc::get_mut(&mut self.data)
            .expect("Cannot load into shared column")
            .load_from_buffer(buffer, rows)
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        // Delegate to ColumnUInt16 which has bulk copy optimization
        self.data.save_to_buffer(buffer)
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnDate::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        // Delegate to underlying column and wrap result
        let sliced_data = self.data.slice(begin, len)?;

        Ok(Arc::new(ColumnDate {
            type_: self.type_.clone(),
            data: sliced_data
                .as_any()
                .downcast_ref::<super::ColumnUInt16>()
                .map(|col| {
                    // Create new Arc from the sliced data
                    Arc::new(super::ColumnUInt16::from_vec(
                        Type::uint16(),
                        col.data().to_vec(),
                    ))
                })
                .expect("Slice should return ColumnUInt16"),
        }))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Column for Date32 type (stored as Int32 - days since Unix epoch 1970-01-01)
/// Extended range: 1900-01-01 to 2299-12-31
///
/// **C++ Implementation Pattern:**
/// Uses delegation to `ColumnInt32` for storage, matching the C++
/// clickhouse-cpp reference implementation's `std::shared_ptr<ColumnInt32>
/// data_` pattern.
pub struct ColumnDate32 {
    type_: Type,
    data: Arc<super::ColumnInt32>, /* Delegates to ColumnInt32, matches C++
                                    * pattern */
}

impl ColumnDate32 {
    /// Creates a new empty Date32 column with the given type.
    pub fn new(type_: Type) -> Self {
        Self { type_, data: Arc::new(super::ColumnInt32::new()) }
    }

    /// Returns a new column populated with the given days-since-epoch values.
    pub fn with_data(mut self, data: Vec<i32>) -> Self {
        self.data =
            Arc::new(super::ColumnInt32::from_vec(Type::int32(), data));
        self
    }

    /// Append days since epoch (raw Int32 value)
    pub fn append(&mut self, days: i32) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append(days);
    }

    /// Append from Unix timestamp (seconds since epoch)
    pub fn append_timestamp(&mut self, timestamp: i64) {
        let days = (timestamp / SECONDS_PER_DAY) as i32;
        self.append(days);
    }

    /// Get raw days value at index
    pub fn at(&self, index: usize) -> i32 {
        self.data.at(index)
    }

    /// Get Unix timestamp (seconds) at index
    pub fn timestamp_at(&self, index: usize) -> i64 {
        self.data.at(index) as i64 * SECONDS_PER_DAY
    }

    /// Returns the number of elements in the column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if the column contains no elements.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get reference to underlying data column (for advanced use)
    pub fn data(&self) -> &super::ColumnInt32 {
        &self.data
    }
}

impl Column for ColumnDate32 {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.size()
    }

    fn clear(&mut self) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot clear shared column")
            .clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot reserve on shared column")
            .reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other = other.as_any().downcast_ref::<ColumnDate32>().ok_or_else(
            || Error::TypeMismatch {
                expected: self.type_.name(),
                actual: other.column_type().name(),
            },
        )?;

        // Delegate to underlying ColumnInt32
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append_column(other.data.clone() as ColumnRef)?;
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        // Delegate to ColumnInt32 which has bulk copy optimization
        Arc::get_mut(&mut self.data)
            .expect("Cannot load into shared column")
            .load_from_buffer(buffer, rows)
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        // Delegate to ColumnInt32 which has bulk copy optimization
        self.data.save_to_buffer(buffer)
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnDate32::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        // Delegate to underlying column and wrap result
        let sliced_data = self.data.slice(begin, len)?;

        Ok(Arc::new(ColumnDate32 {
            type_: self.type_.clone(),
            data: sliced_data
                .as_any()
                .downcast_ref::<super::ColumnInt32>()
                .map(|col| {
                    // Create new Arc from the sliced data
                    Arc::new(super::ColumnInt32::from_vec(
                        Type::int32(),
                        col.data().to_vec(),
                    ))
                })
                .expect("Slice should return ColumnInt32"),
        }))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Column for DateTime type (stored as UInt32 - seconds since Unix epoch)
/// Range: 1970-01-01 00:00:00 to 2106-02-07 06:28:15
///
/// **C++ Implementation Pattern:**
/// Uses delegation to `ColumnUInt32` for storage, matching the C++
/// clickhouse-cpp reference implementation's `std::shared_ptr<ColumnUInt32>
/// data_` pattern.
pub struct ColumnDateTime {
    type_: Type,
    data: Arc<super::ColumnUInt32>, /* Delegates to ColumnUInt32, matches
                                     * C++ pattern */
    timezone: Option<String>,
}

impl ColumnDateTime {
    /// Creates a new empty DateTime column, extracting timezone from the type.
    pub fn new(type_: Type) -> Self {
        let timezone = match &type_ {
            Type::DateTime { timezone } => timezone.clone(),
            _ => None,
        };

        Self { type_, data: Arc::new(super::ColumnUInt32::new()), timezone }
    }

    /// Returns a new column populated with the given Unix timestamp values.
    pub fn with_data(mut self, data: Vec<u32>) -> Self {
        self.data =
            Arc::new(super::ColumnUInt32::from_vec(Type::uint32(), data));
        self
    }

    /// Append Unix timestamp (seconds since epoch)
    pub fn append(&mut self, timestamp: u32) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append(timestamp);
    }

    /// Get timestamp at index
    pub fn at(&self, index: usize) -> u32 {
        self.data.at(index)
    }

    /// Get timezone
    pub fn timezone(&self) -> Option<&str> {
        self.timezone.as_deref()
    }

    /// Returns the number of elements in the column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if the column contains no elements.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get reference to underlying data column (for advanced use)
    pub fn data(&self) -> &super::ColumnUInt32 {
        &self.data
    }
}

impl Column for ColumnDateTime {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.size()
    }

    fn clear(&mut self) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot clear shared column")
            .clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot reserve on shared column")
            .reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other = other
            .as_any()
            .downcast_ref::<ColumnDateTime>()
            .ok_or_else(|| Error::TypeMismatch {
                expected: self.type_.name(),
                actual: other.column_type().name(),
            })?;

        // Delegate to underlying ColumnUInt32
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append_column(other.data.clone() as ColumnRef)?;
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        // Delegate to ColumnUInt32 which has bulk copy optimization
        Arc::get_mut(&mut self.data)
            .expect("Cannot load into shared column")
            .load_from_buffer(buffer, rows)
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        // Delegate to ColumnUInt32 which has bulk copy optimization
        self.data.save_to_buffer(buffer)
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnDateTime::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        // Delegate to underlying column and wrap result
        let sliced_data = self.data.slice(begin, len)?;

        Ok(Arc::new(ColumnDateTime {
            type_: self.type_.clone(),
            timezone: self.timezone.clone(),
            data: sliced_data
                .as_any()
                .downcast_ref::<super::ColumnUInt32>()
                .map(|col| {
                    // Create new Arc from the sliced data
                    Arc::new(super::ColumnUInt32::from_vec(
                        Type::uint32(),
                        col.data().to_vec(),
                    ))
                })
                .expect("Slice should return ColumnUInt32"),
        }))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Column for DateTime64 type (stored as Int64 - subsecond precision)
/// Supports arbitrary sub-second precision, extended date range
///
/// **C++ Implementation Pattern:**
/// C++ uses delegation to `ColumnDecimal`, but we use `ColumnInt64` for
/// simplicity since DateTime64 is fundamentally stored as Int64.
pub struct ColumnDateTime64 {
    type_: Type,
    data: Arc<super::ColumnInt64>, // Delegates to ColumnInt64
    precision: usize,
    timezone: Option<String>,
}

impl ColumnDateTime64 {
    /// Creates a new empty DateTime64 column, extracting precision and
    /// timezone from the type.
    pub fn new(type_: Type) -> Self {
        let (precision, timezone) = match &type_ {
            Type::DateTime64 { precision, timezone } => {
                (*precision, timezone.clone())
            }
            _ => panic!("ColumnDateTime64 requires DateTime64 type"),
        };

        Self {
            type_,
            data: Arc::new(super::ColumnInt64::new()),
            precision,
            timezone,
        }
    }

    /// Returns a new column populated with the given sub-second timestamp
    /// values.
    pub fn with_data(mut self, data: Vec<i64>) -> Self {
        self.data =
            Arc::new(super::ColumnInt64::from_vec(Type::int64(), data));
        self
    }

    /// Append timestamp with precision (e.g., for precision 3, value is
    /// milliseconds)
    pub fn append(&mut self, value: i64) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append(value);
    }

    /// Get timestamp at index
    pub fn at(&self, index: usize) -> i64 {
        self.data.at(index)
    }

    /// Get precision (0-9, number of decimal places)
    pub fn precision(&self) -> usize {
        self.precision
    }

    /// Get timezone
    pub fn timezone(&self) -> Option<&str> {
        self.timezone.as_deref()
    }

    /// Returns the number of elements in the column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if the column contains no elements.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get reference to underlying data column (for advanced use)
    pub fn data(&self) -> &super::ColumnInt64 {
        &self.data
    }
}

impl Column for ColumnDateTime64 {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.size()
    }

    fn clear(&mut self) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot clear shared column")
            .clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        Arc::get_mut(&mut self.data)
            .expect("Cannot reserve on shared column")
            .reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other = other
            .as_any()
            .downcast_ref::<ColumnDateTime64>()
            .ok_or_else(|| Error::TypeMismatch {
                expected: self.type_.name(),
                actual: other.column_type().name(),
            })?;

        if self.precision != other.precision {
            return Err(Error::TypeMismatch {
                expected: format!("DateTime64({})", self.precision),
                actual: format!("DateTime64({})", other.precision),
            });
        }

        // Delegate to underlying ColumnInt64
        Arc::get_mut(&mut self.data)
            .expect("Cannot append to shared column")
            .append_column(other.data.clone() as ColumnRef)?;
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        // Delegate to ColumnInt64 which has bulk copy optimization
        Arc::get_mut(&mut self.data)
            .expect("Cannot load into shared column")
            .load_from_buffer(buffer, rows)
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        // Delegate to ColumnInt64 which has bulk copy optimization
        self.data.save_to_buffer(buffer)
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnDateTime64::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        // Delegate to underlying column and wrap result
        let sliced_data = self.data.slice(begin, len)?;

        Ok(Arc::new(ColumnDateTime64 {
            type_: self.type_.clone(),
            precision: self.precision,
            timezone: self.timezone.clone(),
            data: sliced_data
                .as_any()
                .downcast_ref::<super::ColumnInt64>()
                .map(|col| {
                    // Create new Arc from the sliced data
                    Arc::new(super::ColumnInt64::from_vec(
                        Type::int64(),
                        col.data().to_vec(),
                    ))
                })
                .expect("Slice should return ColumnInt64"),
        }))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn test_date_append_and_retrieve() {
        let mut col = ColumnDate::new(Type::date());
        col.append(19000); // Days since epoch
        col.append(19001);

        assert_eq!(col.len(), 2);
        assert_eq!(col.at(0), 19000);
        assert_eq!(col.at(1), 19001);
    }

    #[test]
    fn test_date_timestamp() {
        let mut col = ColumnDate::new(Type::date());
        col.append_timestamp(1640995200); // 2022-01-01 00:00:00

        assert_eq!(col.len(), 1);
        let days = col.at(0);
        assert_eq!(days, 18993);
    }

    #[test]
    fn test_date32() {
        let mut col = ColumnDate32::new(Type::date32());
        col.append(-25567); // 1900-01-01 (negative days)
        col.append(0); // 1970-01-01
        col.append(100000); // Future date

        assert_eq!(col.len(), 3);
        assert_eq!(col.at(0), -25567);
        assert_eq!(col.at(1), 0);
        assert_eq!(col.at(2), 100000);
    }

    #[test]
    fn test_datetime() {
        let mut col = ColumnDateTime::new(Type::datetime(None));
        col.append(1640995200); // 2022-01-01 00:00:00 UTC
        col.append(1640995201);

        assert_eq!(col.len(), 2);
        assert_eq!(col.at(0), 1640995200);
        assert_eq!(col.at(1), 1640995201);
    }

    #[test]
    fn test_datetime_with_timezone() {
        let mut col =
            ColumnDateTime::new(Type::datetime(Some("UTC".to_string())));
        col.append(1640995200);

        assert_eq!(col.timezone(), Some("UTC"));
        assert_eq!(col.at(0), 1640995200);
    }

    #[test]
    fn test_datetime64() {
        let mut col = ColumnDateTime64::new(Type::datetime64(3, None)); // millisecond precision
        col.append(1640995200000); // 2022-01-01 00:00:00.000 UTC
        col.append(1640995200123);

        assert_eq!(col.len(), 2);
        assert_eq!(col.precision(), 3);
        assert_eq!(col.at(0), 1640995200000);
        assert_eq!(col.at(1), 1640995200123);
    }
}