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
use super::column_data::expect_type;
use std::{borrow::Cow, fmt, ptr, sync::Arc};

use chrono::prelude::*;
use chrono_tz::Tz;
use either::Either;

use crate::{
    binary::{Encoder, ReadEx},
    errors::{DriverError, Error, Result},
    types::{
        column::time::time_fits,
        column::{
            array::ArrayColumnData,
            column_data::{ArcColumnData, BoxColumnData, ColumnData, LowCardinalityAccessor},
            datetime64::DEFAULT_TZ,
            list::List,
            nullable::NullableColumnData,
            numeric::save_data,
            ArcColumnWrapper, ColumnFrom, ColumnWrapper,
        },
        date_converter::{date_days, days_to_date},
        DateConverter, Marshal, SqlType, StatBuffer, Unmarshal, Value, ValueRef,
    },
};

pub struct DateColumnData<T>
where
    T: StatBuffer
        + Unmarshal<T>
        + Marshal
        + Copy
        + Into<Value>
        + From<Value>
        + fmt::Display
        + Sync
        + Default
        + 'static,
{
    data: List<T>,
    tz: Tz,
}

impl<T> DateColumnData<T>
where
    T: StatBuffer
        + Unmarshal<T>
        + Marshal
        + Copy
        + Into<Value>
        + From<Value>
        + fmt::Display
        + Sync
        + Default
        + 'static,
{
    pub(crate) fn with_capacity(capacity: usize, timezone: Tz) -> DateColumnData<T> {
        DateColumnData {
            data: List::with_capacity(capacity),
            tz: timezone,
        }
    }

    pub(crate) fn load<R: ReadEx>(
        reader: &mut R,
        size: usize,
        tz: Tz,
    ) -> Result<DateColumnData<T>> {
        let mut data = List::zeroed(size);
        reader.read_bytes(data.as_mut())?;
        Ok(DateColumnData { data, tz })
    }
}

/// Whether a Date column (days 0 to 65535, 1970-01-01 to 2149-06-06) holds
/// every one of `dates`; the others make a Date32 column.
fn fit_date<'a>(mut dates: impl Iterator<Item = &'a NaiveDate>) -> bool {
    dates.all(|date| u16::try_from(date_days(*date)).is_ok())
}

/// The value of `date` in a Date32 column when `wide`, else in a Date one.
fn date_value(date: NaiveDate, wide: bool) -> Value {
    let days = date_days(date);
    if wide {
        Value::Date32(days as i32)
    } else {
        Value::Date(days as u16)
    }
}

/// An empty column of dates, Date32 when `wide`.
fn date_column(wide: bool, capacity: usize) -> ArcColumnData {
    if wide {
        Arc::new(DateColumnData::<i32>::with_capacity(capacity, *DEFAULT_TZ))
    } else {
        Arc::new(DateColumnData::<u16>::with_capacity(capacity, *DEFAULT_TZ))
    }
}

impl DateColumnData<i32> {
    /// Loads Date32 days, which have to be dates chrono can hold: the
    /// iterators hand them out as `NaiveDate`s.
    pub(crate) fn load_date32<R: ReadEx>(reader: &mut R, size: usize, tz: Tz) -> Result<Self> {
        let column = Self::load(reader, size, tz)?;
        if (0..column.data.len()).any(|row| days_to_date(i64::from(column.data.at(row))).is_none())
        {
            return Err(Error::Driver(DriverError::Deserialize(Cow::from(
                "a Date32 value is outside the range of dates",
            ))));
        }
        Ok(column)
    }
}

/// Whether a column of `sql_type` can hold a date or a time.
pub(crate) fn has_date(sql_type: &SqlType) -> bool {
    match sql_type {
        SqlType::Date | SqlType::Date32 | SqlType::Time | SqlType::Time64(_) => true,
        SqlType::Nullable(inner)
        | SqlType::Array(inner)
        | SqlType::LowCardinality(inner)
        | SqlType::SimpleAggregateFunction(_, inner) => has_date(inner),
        SqlType::Map(keys, values) => has_date(keys) || has_date(values),
        SqlType::Tuple(elements) => elements.iter().any(|(_, element)| has_date(element)),
        _ => false,
    }
}

/// Whether the dates and times in a `value` pushed into a column of
/// `sql_type` can be stored there: a Date32 day fits a Date column only within
/// its range, and a Date32 column only when chrono can hold it; a time fits
/// a Time or Time64 column when it converts without a loss; also inside `Nullable`,
/// `Array`, `Map`, `Tuple`, `LowCardinality` and `SimpleAggregateFunction`.
pub(crate) fn dates_fit(sql_type: &SqlType, value: &Value) -> bool {
    match (sql_type, value) {
        (SqlType::Date, Value::Date32(days)) => u16::try_from(*days).is_ok(),
        (SqlType::Date32, Value::Date32(days)) => days_to_date(i64::from(*days)).is_some(),
        (SqlType::Time | SqlType::Time64(_), value) => time_fits(sql_type, value),
        (SqlType::Nullable(_), Value::Nullable(Either::Left(_))) => true,
        (SqlType::Nullable(inner), Value::Nullable(Either::Right(value))) => {
            dates_fit(inner, value)
        }
        (SqlType::Nullable(inner) | SqlType::LowCardinality(inner), value) => {
            dates_fit(inner, value)
        }
        (SqlType::SimpleAggregateFunction(_, inner), value) => dates_fit(inner, value),
        (SqlType::Array(inner), Value::Array(_, values)) => {
            values.iter().all(|value| dates_fit(inner, value))
        }
        (SqlType::Map(keys, values), Value::Map(_, _, entries)) => entries
            .iter()
            .all(|(key, value)| dates_fit(keys, key) && dates_fit(values, value)),
        (SqlType::Tuple(elements), Value::Tuple(values)) => elements
            .iter()
            .zip(values.iter())
            .all(|((_, element), value)| dates_fit(element, value)),
        _ => true,
    }
}

impl ColumnFrom for Vec<NaiveDate> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let tz = *DEFAULT_TZ;
        if fit_date(source.iter()) {
            let data = source.into_iter().map(|d| date_days(d) as u16).collect();
            W::wrap(DateColumnData::<u16> {
                data: List::from_vec(data),
                tz,
            })
        } else {
            let data = source.into_iter().map(|d| date_days(d) as i32).collect();
            W::wrap(DateColumnData::<i32> {
                data: List::from_vec(data),
                tz,
            })
        }
    }
}

impl ColumnFrom for Vec<Vec<NaiveDate>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let wide = !fit_date(source.iter().flatten());
        let inner = date_column(wide, source.len());
        let sql_type = inner.sql_type();

        let mut data = ArrayColumnData {
            inner,
            offsets: List::with_capacity(source.len()),
        };

        for vs in source {
            let inner: Vec<Value> = vs.into_iter().map(|v| date_value(v, wide)).collect();
            data.push(Value::Array(sql_type.clone().into(), Arc::new(inner)));
        }

        W::wrap(data)
    }
}

impl ColumnFrom for Vec<Vec<DateTime<Tz>>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let fake: Vec<DateTime<Tz>> = Vec::with_capacity(source.len());
        let inner = ColumnFrom::column_from::<ArcColumnWrapper>(fake);
        let sql_type = inner.sql_type();

        let mut data = ArrayColumnData {
            inner,
            offsets: List::with_capacity(source.len()),
        };

        for vs in source {
            let mut inner = Vec::with_capacity(vs.len());
            for v in vs {
                let value: Value = Value::DateTime(v.timestamp() as u32, v.timezone());
                inner.push(value);
            }
            data.push(Value::Array(sql_type.clone().into(), Arc::new(inner)));
        }

        W::wrap(data)
    }
}

impl ColumnFrom for Vec<Option<NaiveDate>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> <W as ColumnWrapper>::Wrapper {
        let wide = !fit_date(source.iter().flatten());
        let inner = date_column(wide, source.len());
        let null_type: &'static SqlType = inner.sql_type().into();

        let mut data = NullableColumnData {
            inner,
            nulls: Vec::with_capacity(source.len()),
        };

        for value in source {
            match value {
                None => data.push(Value::Nullable(Either::Left(null_type))),
                Some(d) => {
                    let value = date_value(d, wide);
                    data.push(Value::Nullable(Either::Right(Box::new(value))))
                }
            }
        }

        W::wrap(data)
    }
}

impl<T> LowCardinalityAccessor for DateColumnData<T> where
    T: StatBuffer
        + Unmarshal<T>
        + Marshal
        + Copy
        + Into<Value>
        + From<Value>
        + fmt::Display
        + Sync
        + Send
        + DateConverter
        + Default
        + 'static
{
}

impl<T> ColumnData for DateColumnData<T>
where
    T: StatBuffer
        + Unmarshal<T>
        + Marshal
        + Copy
        + Into<Value>
        + From<Value>
        + fmt::Display
        + Sync
        + Send
        + DateConverter
        + Default
        + 'static,
{
    fn sql_type(&self) -> SqlType {
        T::date_type()
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        save_data::<T>(self.data.as_ref(), encoder, start, end);
    }

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

    fn push(&mut self, value: Value) {
        self.data.push(T::get_stamp(value));
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        self.data.at(index).to_date(self.tz)
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(Self {
            data: self.data.clone(),
            tz: self.tz,
        })
    }

    unsafe fn get_internal(
        &self,
        pointers: &[*mut *const u8],
        level: u8,
        _props: u32,
        expected: &SqlType,
    ) -> Result<()> {
        expect_type(self.sql_type(), expected)?;
        assert_eq!(level, 0);
        *pointers[0] = self.data.as_ptr() as *const u8;
        *pointers[1] = &self.tz as *const Tz as *const u8;
        *(pointers[2] as *mut usize) = self.len();
        Ok(())
    }

    unsafe fn get_internals(
        &self,
        data_ptr: *mut (),
        _level: u8,
        _props: u32,
        expected: &SqlType,
    ) -> Result<()> {
        expect_type(self.sql_type(), expected)?;
        unsafe {
            let data_ref = &mut *(data_ptr as *mut DateTimeInternals);
            data_ref.begin = self.data.as_ptr().cast();
            data_ref.len = self.data.len();
            data_ref.tz = self.tz;
            Ok(())
        }
    }

    /// Date widens to Date32, and Date32 narrows to Date when every date fits.
    fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
        let days = (0..self.len()).map(|i| match self.at(i) {
            ValueRef::Date(days) => Some(i64::from(days)),
            ValueRef::Date32(days) => Some(i64::from(days)),
            _ => None,
        });
        match (T::date_type(), target) {
            (SqlType::Date, SqlType::Date32) => {
                let data = days.map(|d| d.map(|d| d as i32)).collect::<Option<_>>()?;
                Some(Arc::new(DateColumnData::<i32> {
                    data: List::from_vec(data),
                    tz: self.tz,
                }))
            }
            (SqlType::Date32, SqlType::Date) => {
                let data = days
                    .map(|d| d.and_then(|d| u16::try_from(d).ok()))
                    .collect::<Option<_>>()?;
                Some(Arc::new(DateColumnData::<u16> {
                    data: List::from_vec(data),
                    tz: self.tz,
                }))
            }
            _ => None,
        }
    }

    fn get_timezone(&self) -> Option<Tz> {
        Some(self.tz)
    }

    fn get_low_cardinality_accessor(&self) -> Option<&dyn LowCardinalityAccessor> {
        Some(self)
    }
}

#[derive(Debug)]
pub(crate) struct DateTimeInternals {
    pub(crate) begin: *const (),
    pub(crate) len: usize,
    pub(crate) tz: Tz,
    pub(crate) precision: Option<u32>,
}

impl Default for DateTimeInternals {
    fn default() -> Self {
        Self {
            begin: ptr::null(),
            len: 0,
            tz: Tz::Zulu,
            precision: None,
        }
    }
}

#[cfg(test)]
mod test {
    use chrono::TimeZone;

    use crate::types::column::{datetime64::DEFAULT_TZ, ArcColumnWrapper};

    use super::*;

    #[test]
    fn test_create_date() {
        let column = ColumnFrom::column_from::<ArcColumnWrapper>(vec![NaiveDate::from_ymd_opt(
            2016, 10, 22,
        )
        .unwrap()]);
        assert_eq!("2016-10-22", format!("{:#}", column.at(0)));
        assert_eq!(SqlType::Date, column.sql_type());
    }

    #[test]
    fn test_create_date_time() {
        let tz = *DEFAULT_TZ;
        let column = ColumnFrom::column_from::<ArcColumnWrapper>(vec![tz
            .with_ymd_and_hms(2016, 10, 22, 12, 0, 0)
            .unwrap()]);
        assert_eq!(format!("{}", column.at(0)), "2016-10-22 12:00:00");
    }

    #[test]
    fn test_dates_are_calendar_days() {
        use crate::types::{column::Column, Simple};

        // A Date read from a server west of UTC is still the same day.
        let column: Column<Simple> = Column {
            name: String::new(),
            data: Arc::new(DateColumnData::<u16> {
                data: List::from_vec(vec![0, 20_420]),
                tz: chrono_tz::America::New_York,
            }),
            _marker: std::marker::PhantomData,
        };
        let dates: Vec<NaiveDate> = column.iter::<NaiveDate>().unwrap().collect();
        assert_eq!(
            dates,
            [
                NaiveDate::from_ymd_opt(1970, 1, 1).unwrap(),
                NaiveDate::from_ymd_opt(2025, 11, 28).unwrap()
            ]
        );
    }

    #[test]
    fn test_dates_that_do_not_fit() {
        use crate::{
            row,
            types::{Block, FromSql, Simple},
        };

        // An array element chrono cannot hold is an error, not a panic.
        let array = ValueRef::Array(&SqlType::Date32, Arc::new(vec![ValueRef::Date32(i32::MAX)]));
        assert!(Vec::<NaiveDate>::from_sql(array).is_err());

        // A Date column made by a first row does not take a date before 1970.
        let mut block = Block::<Simple>::new();
        let date = |y| NaiveDate::from_ymd_opt(y, 1, 1).unwrap();
        block.push(row! { d: date(2000) }).unwrap();
        assert!(block.push(row! { d: date(1969) }).is_err());
        // A Date32 value that fits goes into it.
        block
            .push(vec![("d".to_string(), Value::Date32(0))])
            .unwrap();
        assert_eq!(block.row_count(), 2);

        // Nested too: a tuple element, and a map of dates, whose type says Date.
        let mut block = Block::<Simple>::new();
        block.push(row! { t: (date(2000), 1_u8) }).unwrap();
        assert!(block.push(row! { t: (date(1969), 2_u8) }).is_err());
        let map = std::collections::HashMap::from([("k".to_string(), date(1969))]);
        assert!(Block::<Simple>::new().push(row! { m: map }).is_err());

        // A Date32 day chrono cannot hold does not go in at all.
        let mut block = Block::<Simple>::new();
        block.push(row! { d: date(1960) }).unwrap();
        assert!(block
            .push(vec![("d".to_string(), Value::Date32(i32::MAX))])
            .is_err());
    }
}