Skip to main content

teaql_core/
value.rs

1use std::collections::BTreeMap;
2use std::str::FromStr;
3
4use chrono::{DateTime, NaiveDate, Utc};
5pub use rust_decimal::Decimal;
6use rust_decimal::prelude::ToPrimitive;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum DataType {
10    Bool,
11    I64,
12    U64,
13    F64,
14    Decimal,
15    Text,
16    LargeText,
17    Json,
18    Date,
19    Timestamp,
20}
21
22#[derive(Debug, Clone, PartialEq)]
23pub enum Value {
24    Null,
25    Bool(bool),
26    I64(i64),
27    U64(u64),
28    F64(f64),
29    Decimal(Decimal),
30    Text(String),
31    Json(serde_json::Value),
32    Date(NaiveDate),
33    Timestamp(crate::time::Timestamp),
34    Object(BTreeMap<String, Value>),
35    List(Vec<Value>),
36    TypedNull(DataType),
37}
38
39impl From<&str> for Value {
40    fn from(value: &str) -> Self {
41        Self::Text(value.to_owned())
42    }
43}
44
45impl From<String> for Value {
46    fn from(value: String) -> Self {
47        Self::Text(value)
48    }
49}
50
51impl From<i64> for Value {
52    fn from(value: i64) -> Self {
53        Self::I64(value)
54    }
55}
56
57impl From<i32> for Value {
58    fn from(value: i32) -> Self {
59        Self::I64(i64::from(value))
60    }
61}
62
63impl From<i16> for Value {
64    fn from(value: i16) -> Self {
65        Self::I64(i64::from(value))
66    }
67}
68
69impl From<u64> for Value {
70    fn from(value: u64) -> Self {
71        Self::U64(value)
72    }
73}
74
75impl From<u32> for Value {
76    fn from(value: u32) -> Self {
77        Self::U64(u64::from(value))
78    }
79}
80
81impl From<u16> for Value {
82    fn from(value: u16) -> Self {
83        Self::U64(u64::from(value))
84    }
85}
86
87impl From<f64> for Value {
88    fn from(value: f64) -> Self {
89        Self::F64(value)
90    }
91}
92
93impl From<f32> for Value {
94    fn from(value: f32) -> Self {
95        Self::F64(f64::from(value))
96    }
97}
98
99impl From<bool> for Value {
100    fn from(value: bool) -> Self {
101        Self::Bool(value)
102    }
103}
104
105impl From<Decimal> for Value {
106    fn from(value: Decimal) -> Self {
107        Self::Decimal(value)
108    }
109}
110
111impl From<serde_json::Value> for Value {
112    fn from(value: serde_json::Value) -> Self {
113        Self::Json(value)
114    }
115}
116
117impl From<NaiveDate> for Value {
118    fn from(value: NaiveDate) -> Self {
119        Self::Date(value)
120    }
121}
122
123impl From<crate::time::Timestamp> for Value {
124    fn from(value: crate::time::Timestamp) -> Self {
125        Self::Timestamp(value)
126    }
127}
128
129impl From<DateTime<Utc>> for Value {
130    fn from(value: DateTime<Utc>) -> Self {
131        Self::Timestamp(crate::time::Timestamp(value.timestamp_millis()))
132    }
133}
134
135impl Value {
136    pub fn object(record: crate::Record) -> Self {
137        Self::Object(record)
138    }
139
140    pub fn try_i64(&self) -> Option<i64> {
141        match self {
142            Self::I64(value) => Some(*value),
143            Self::U64(value) => i64::try_from(*value).ok(),
144            Self::Decimal(value) => value.to_i64(),
145            _ => None,
146        }
147    }
148
149    pub fn try_u64(&self) -> Option<u64> {
150        match self {
151            Self::U64(value) => Some(*value),
152            Self::I64(value) => u64::try_from(*value).ok(),
153            Self::Decimal(value) => value.to_u64(),
154            _ => None,
155        }
156    }
157
158    pub fn try_decimal(&self) -> Option<Decimal> {
159        match self {
160            Self::Decimal(value) => Some(*value),
161            Self::I64(value) => Some(Decimal::from(*value)),
162            Self::U64(value) => Some(Decimal::from(*value)),
163            Self::F64(value) if value.is_finite() => Decimal::from_f64_retain(*value),
164            Self::Text(value) => Decimal::from_str(value).ok(),
165            _ => None,
166        }
167    }
168
169    pub fn try_f64(&self) -> Option<f64> {
170        match self {
171            Self::F64(value) => Some(*value),
172            Self::I64(value) => Some(*value as f64),
173            Self::U64(value) => Some(*value as f64),
174            Self::Decimal(value) => value.to_f64(),
175            _ => None,
176        }
177    }
178
179    pub fn try_text(&self) -> Option<&str> {
180        match self {
181            Self::Text(value) => Some(value),
182            _ => None,
183        }
184    }
185
186    pub fn try_bool(&self) -> Option<bool> {
187        match self {
188            Self::Bool(value) => Some(*value),
189            _ => None,
190        }
191    }
192
193    pub fn try_date(&self) -> Option<NaiveDate> {
194        match self {
195            Self::Date(value) => Some(*value),
196            Self::Text(value) => {
197                if let Ok(nd) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") {
198                    return Some(nd);
199                }
200                None
201            }
202            Self::I64(value) => {
203                chrono::DateTime::from_timestamp_millis(*value).map(|dt| dt.naive_utc().date())
204            }
205            Self::U64(value) => i64::try_from(*value)
206                .ok()
207                .and_then(chrono::DateTime::from_timestamp_millis)
208                .map(|dt| dt.naive_utc().date()),
209            _ => None,
210        }
211    }
212
213    pub fn try_timestamp(&self) -> Option<crate::time::Timestamp> {
214        match self {
215            Self::Timestamp(value) => Some(*value),
216            Self::Text(value) => {
217                if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(value) {
218                    return Some(crate::time::Timestamp(dt.timestamp_millis()));
219                }
220                if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S") {
221                    return Some(crate::time::Timestamp(
222                        chrono::DateTime::<Utc>::from_naive_utc_and_offset(ndt, chrono::Utc)
223                            .timestamp_millis(),
224                    ));
225                }
226                if let Ok(nd) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") {
227                    let ndt = nd.and_hms_opt(0, 0, 0)?;
228                    return Some(crate::time::Timestamp(
229                        chrono::DateTime::<Utc>::from_naive_utc_and_offset(ndt, chrono::Utc)
230                            .timestamp_millis(),
231                    ));
232                }
233                None
234            }
235            Self::I64(value) => Some(crate::time::Timestamp(*value)),
236            Self::U64(value) => i64::try_from(*value).ok().map(crate::time::Timestamp),
237            _ => None,
238        }
239    }
240
241    pub fn to_json_value(&self) -> serde_json::Value {
242        match self {
243            Self::Null => serde_json::Value::Null,
244            Self::Bool(value) => serde_json::Value::Bool(*value),
245            Self::I64(value) => serde_json::Value::from(*value),
246            Self::U64(value) => serde_json::Value::from(*value),
247            Self::F64(value) => serde_json::Number::from_f64(*value)
248                .map(serde_json::Value::Number)
249                .unwrap_or(serde_json::Value::Null),
250            Self::Decimal(value) => serde_json::Value::String(value.to_string()),
251            Self::Text(value) => serde_json::Value::String(value.clone()),
252            Self::Json(value) => value.clone(),
253            Self::Date(value) => serde_json::Value::String(value.to_string()),
254            Self::Timestamp(value) => serde_json::Value::from(value.0),
255            Self::Object(record) => crate::record_to_json_value(record),
256            Self::List(values) => {
257                serde_json::Value::Array(values.iter().map(Value::to_json_value).collect())
258            }
259            Self::TypedNull(_) => serde_json::Value::Null,
260        }
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn value_try_i64_accepts_representable_numeric_variants() {
270        assert_eq!(Value::I64(i64::MIN).try_i64(), Some(i64::MIN));
271        assert_eq!(Value::I64(i64::MAX).try_i64(), Some(i64::MAX));
272        assert_eq!(Value::U64(i64::MAX as u64).try_i64(), Some(i64::MAX));
273        assert_eq!(Value::Decimal(Decimal::from(-42)).try_i64(), Some(-42));
274    }
275
276    #[test]
277    fn value_try_i64_rejects_unsigned_overflow_and_unrelated_variants() {
278        assert_eq!(Value::U64(i64::MAX as u64 + 1).try_i64(), None);
279        assert_eq!(Value::U64(u64::MAX).try_i64(), None);
280        assert_eq!(Value::F64(42.0).try_i64(), None);
281        assert_eq!(Value::Text("42".to_owned()).try_i64(), None);
282        assert_eq!(Value::Null.try_i64(), None);
283    }
284
285    #[test]
286    fn value_try_u64_accepts_representable_numeric_variants() {
287        assert_eq!(Value::U64(0).try_u64(), Some(0));
288        assert_eq!(Value::U64(u64::MAX).try_u64(), Some(u64::MAX));
289        assert_eq!(Value::I64(i64::MAX).try_u64(), Some(i64::MAX as u64));
290        assert_eq!(Value::Decimal(Decimal::from(42)).try_u64(), Some(42));
291    }
292
293    #[test]
294    fn value_try_u64_rejects_negative_and_unrelated_variants() {
295        assert_eq!(Value::I64(-1).try_u64(), None);
296        assert_eq!(Value::Decimal(Decimal::from(-1)).try_u64(), None);
297        assert_eq!(Value::F64(42.0).try_u64(), None);
298        assert_eq!(Value::Text("42".to_owned()).try_u64(), None);
299        assert_eq!(Value::Null.try_u64(), None);
300    }
301
302    #[test]
303    fn value_try_decimal_accepts_decimal_numeric_and_text_variants() {
304        let decimal = Decimal::from_str("123.450").expect("valid decimal");
305
306        assert_eq!(Value::Decimal(decimal).try_decimal(), Some(decimal));
307        assert_eq!(
308            Value::I64(i64::MIN).try_decimal(),
309            Some(Decimal::from(i64::MIN))
310        );
311        assert_eq!(
312            Value::U64(u64::MAX).try_decimal(),
313            Some(Decimal::from(u64::MAX))
314        );
315        assert_eq!(
316            Value::Text("123.450".to_owned()).try_decimal(),
317            Some(decimal)
318        );
319        assert_eq!(
320            Value::F64(136.25).try_decimal(),
321            Decimal::from_f64_retain(136.25)
322        );
323    }
324
325    #[test]
326    fn value_try_decimal_rejects_invalid_text_and_unrelated_variants() {
327        assert_eq!(Value::Text("not-a-decimal".to_owned()).try_decimal(), None);
328        assert_eq!(Value::Bool(true).try_decimal(), None);
329        assert_eq!(Value::F64(f64::NAN).try_decimal(), None);
330        assert_eq!(Value::Null.try_decimal(), None);
331    }
332
333    #[test]
334    fn value_try_f64_accepts_supported_numeric_variants() {
335        assert_eq!(Value::F64(1.25).try_f64(), Some(1.25));
336        assert_eq!(Value::I64(-2).try_f64(), Some(-2.0));
337        assert_eq!(Value::U64(2).try_f64(), Some(2.0));
338        assert_eq!(
339            Value::Decimal(Decimal::from_str("1.5").expect("valid decimal")).try_f64(),
340            Some(1.5)
341        );
342    }
343
344    #[test]
345    fn value_try_f64_rejects_unrelated_variants() {
346        assert_eq!(Value::Text("1.5".to_owned()).try_f64(), None);
347        assert_eq!(Value::Bool(true).try_f64(), None);
348        assert_eq!(Value::Null.try_f64(), None);
349    }
350
351    #[test]
352    fn value_try_date_accepts_date_and_iso_date_text() {
353        let leap_day = NaiveDate::from_ymd_opt(2024, 2, 29).expect("valid leap day");
354
355        assert_eq!(Value::Date(leap_day).try_date(), Some(leap_day));
356        assert_eq!(
357            Value::Text("2024-02-29".to_owned()).try_date(),
358            Some(leap_day)
359        );
360        let millis = leap_day
361            .and_hms_opt(0, 0, 0)
362            .unwrap()
363            .and_utc()
364            .timestamp_millis();
365        assert_eq!(Value::I64(millis).try_date(), Some(leap_day));
366        assert_eq!(Value::U64(millis as u64).try_date(), Some(leap_day));
367    }
368
369    #[test]
370    fn value_try_date_rejects_invalid_dates_and_unrelated_variants() {
371        assert_eq!(Value::Text("2023-02-29".to_owned()).try_date(), None);
372        assert_eq!(
373            Value::Text("2024-02-29T00:00:00Z".to_owned()).try_date(),
374            None
375        );
376        assert_eq!(Value::Null.try_date(), None);
377    }
378
379    #[test]
380    fn value_try_timestamp_accepts_timestamp_and_supported_text_formats() {
381        let utc_timestamp = crate::time::Timestamp(
382            DateTime::parse_from_rfc3339("2024-01-02T03:04:05Z")
383                .expect("valid RFC 3339 timestamp")
384                .with_timezone(&Utc)
385                .timestamp_millis(),
386        );
387        let offset_timestamp = crate::time::Timestamp(
388            DateTime::parse_from_rfc3339("2024-01-02T03:04:05+08:00")
389                .expect("valid RFC 3339 timestamp")
390                .with_timezone(&Utc)
391                .timestamp_millis(),
392        );
393        let naive_timestamp = NaiveDate::from_ymd_opt(2024, 1, 2)
394            .expect("valid date")
395            .and_hms_opt(3, 4, 5)
396            .expect("valid time");
397        let midnight = NaiveDate::from_ymd_opt(2024, 1, 2)
398            .expect("valid date")
399            .and_hms_opt(0, 0, 0)
400            .expect("valid time");
401
402        assert_eq!(
403            Value::Timestamp(utc_timestamp).try_timestamp(),
404            Some(utc_timestamp)
405        );
406        assert_eq!(
407            Value::Text("2024-01-02T03:04:05+08:00".to_owned()).try_timestamp(),
408            Some(offset_timestamp)
409        );
410        assert_eq!(
411            Value::Text("2024-01-02 03:04:05".to_owned()).try_timestamp(),
412            Some(crate::time::Timestamp(
413                DateTime::<Utc>::from_naive_utc_and_offset(naive_timestamp, Utc).timestamp_millis()
414            ))
415        );
416        assert_eq!(
417            Value::Text("2024-01-02".to_owned()).try_timestamp(),
418            Some(crate::time::Timestamp(
419                DateTime::<Utc>::from_naive_utc_and_offset(midnight, Utc).timestamp_millis()
420            ))
421        );
422
423        let millis = utc_timestamp.0;
424        assert_eq!(Value::I64(millis).try_timestamp(), Some(utc_timestamp));
425        assert_eq!(
426            Value::U64(millis as u64).try_timestamp(),
427            Some(utc_timestamp)
428        );
429    }
430
431    #[test]
432    fn value_try_timestamp_normalizes_offsets_and_rejects_invalid_input() {
433        let expected_utc = crate::time::Timestamp(
434            DateTime::parse_from_rfc3339("2024-01-01T19:04:05Z")
435                .expect("valid RFC 3339 timestamp")
436                .with_timezone(&Utc)
437                .timestamp_millis(),
438        );
439
440        assert_eq!(
441            Value::Text("2024-01-02T03:04:05+08:00".to_owned()).try_timestamp(),
442            Some(expected_utc)
443        );
444        assert_eq!(
445            Value::Text("2024-13-40 25:61:61".to_owned()).try_timestamp(),
446            None
447        );
448        assert_eq!(Value::Bool(true).try_timestamp(), None);
449        assert_eq!(Value::Null.try_timestamp(), None);
450    }
451}