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::Text(value) => Decimal::from_str(value).ok(),
164 _ => None,
165 }
166 }
167
168 pub fn try_f64(&self) -> Option<f64> {
169 match self {
170 Self::F64(value) => Some(*value),
171 Self::I64(value) => Some(*value as f64),
172 Self::U64(value) => Some(*value as f64),
173 Self::Decimal(value) => value.to_f64(),
174 _ => None,
175 }
176 }
177
178 pub fn try_text(&self) -> Option<&str> {
179 match self {
180 Self::Text(value) => Some(value),
181 _ => None,
182 }
183 }
184
185 pub fn try_bool(&self) -> Option<bool> {
186 match self {
187 Self::Bool(value) => Some(*value),
188 _ => None,
189 }
190 }
191
192 pub fn try_date(&self) -> Option<NaiveDate> {
193 match self {
194 Self::Date(value) => Some(*value),
195 Self::Text(value) => {
196 if let Ok(nd) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") {
197 return Some(nd);
198 }
199 None
200 }
201 Self::I64(value) => {
202 chrono::DateTime::from_timestamp_millis(*value).map(|dt| dt.naive_utc().date())
203 }
204 Self::U64(value) => i64::try_from(*value)
205 .ok()
206 .and_then(chrono::DateTime::from_timestamp_millis)
207 .map(|dt| dt.naive_utc().date()),
208 _ => None,
209 }
210 }
211
212 pub fn try_timestamp(&self) -> Option<crate::time::Timestamp> {
213 match self {
214 Self::Timestamp(value) => Some(*value),
215 Self::Text(value) => {
216 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(value) {
217 return Some(crate::time::Timestamp(dt.timestamp_millis()));
218 }
219 if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S") {
220 return Some(crate::time::Timestamp(
221 chrono::DateTime::<Utc>::from_naive_utc_and_offset(ndt, chrono::Utc)
222 .timestamp_millis(),
223 ));
224 }
225 if let Ok(nd) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") {
226 let ndt = nd.and_hms_opt(0, 0, 0)?;
227 return Some(crate::time::Timestamp(
228 chrono::DateTime::<Utc>::from_naive_utc_and_offset(ndt, chrono::Utc)
229 .timestamp_millis(),
230 ));
231 }
232 None
233 }
234 Self::I64(value) => Some(crate::time::Timestamp(*value)),
235 Self::U64(value) => i64::try_from(*value).ok().map(crate::time::Timestamp),
236 _ => None,
237 }
238 }
239
240 pub fn to_json_value(&self) -> serde_json::Value {
241 match self {
242 Self::Null => serde_json::Value::Null,
243 Self::Bool(value) => serde_json::Value::Bool(*value),
244 Self::I64(value) => serde_json::Value::from(*value),
245 Self::U64(value) => serde_json::Value::from(*value),
246 Self::F64(value) => serde_json::Number::from_f64(*value)
247 .map(serde_json::Value::Number)
248 .unwrap_or(serde_json::Value::Null),
249 Self::Decimal(value) => serde_json::Value::String(value.to_string()),
250 Self::Text(value) => serde_json::Value::String(value.clone()),
251 Self::Json(value) => value.clone(),
252 Self::Date(value) => serde_json::Value::String(value.to_string()),
253 Self::Timestamp(value) => serde_json::Value::from(value.0),
254 Self::Object(record) => crate::record_to_json_value(record),
255 Self::List(values) => {
256 serde_json::Value::Array(values.iter().map(Value::to_json_value).collect())
257 }
258 Self::TypedNull(_) => serde_json::Value::Null,
259 }
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn value_try_i64_accepts_representable_numeric_variants() {
269 assert_eq!(Value::I64(i64::MIN).try_i64(), Some(i64::MIN));
270 assert_eq!(Value::I64(i64::MAX).try_i64(), Some(i64::MAX));
271 assert_eq!(Value::U64(i64::MAX as u64).try_i64(), Some(i64::MAX));
272 assert_eq!(Value::Decimal(Decimal::from(-42)).try_i64(), Some(-42));
273 }
274
275 #[test]
276 fn value_try_i64_rejects_unsigned_overflow_and_unrelated_variants() {
277 assert_eq!(Value::U64(i64::MAX as u64 + 1).try_i64(), None);
278 assert_eq!(Value::U64(u64::MAX).try_i64(), None);
279 assert_eq!(Value::F64(42.0).try_i64(), None);
280 assert_eq!(Value::Text("42".to_owned()).try_i64(), None);
281 assert_eq!(Value::Null.try_i64(), None);
282 }
283
284 #[test]
285 fn value_try_u64_accepts_representable_numeric_variants() {
286 assert_eq!(Value::U64(0).try_u64(), Some(0));
287 assert_eq!(Value::U64(u64::MAX).try_u64(), Some(u64::MAX));
288 assert_eq!(Value::I64(i64::MAX).try_u64(), Some(i64::MAX as u64));
289 assert_eq!(Value::Decimal(Decimal::from(42)).try_u64(), Some(42));
290 }
291
292 #[test]
293 fn value_try_u64_rejects_negative_and_unrelated_variants() {
294 assert_eq!(Value::I64(-1).try_u64(), None);
295 assert_eq!(Value::Decimal(Decimal::from(-1)).try_u64(), None);
296 assert_eq!(Value::F64(42.0).try_u64(), None);
297 assert_eq!(Value::Text("42".to_owned()).try_u64(), None);
298 assert_eq!(Value::Null.try_u64(), None);
299 }
300
301 #[test]
302 fn value_try_decimal_accepts_decimal_integer_and_text_variants() {
303 let decimal = Decimal::from_str("123.450").expect("valid decimal");
304
305 assert_eq!(Value::Decimal(decimal).try_decimal(), Some(decimal));
306 assert_eq!(
307 Value::I64(i64::MIN).try_decimal(),
308 Some(Decimal::from(i64::MIN))
309 );
310 assert_eq!(
311 Value::U64(u64::MAX).try_decimal(),
312 Some(Decimal::from(u64::MAX))
313 );
314 assert_eq!(
315 Value::Text("123.450".to_owned()).try_decimal(),
316 Some(decimal)
317 );
318 }
319
320 #[test]
321 fn value_try_decimal_rejects_invalid_text_and_unrelated_variants() {
322 assert_eq!(Value::Text("not-a-decimal".to_owned()).try_decimal(), None);
323 assert_eq!(Value::Bool(true).try_decimal(), None);
324 assert_eq!(Value::F64(1.5).try_decimal(), None);
325 assert_eq!(Value::Null.try_decimal(), None);
326 }
327
328 #[test]
329 fn value_try_f64_accepts_supported_numeric_variants() {
330 assert_eq!(Value::F64(1.25).try_f64(), Some(1.25));
331 assert_eq!(Value::I64(-2).try_f64(), Some(-2.0));
332 assert_eq!(Value::U64(2).try_f64(), Some(2.0));
333 assert_eq!(
334 Value::Decimal(Decimal::from_str("1.5").expect("valid decimal")).try_f64(),
335 Some(1.5)
336 );
337 }
338
339 #[test]
340 fn value_try_f64_rejects_unrelated_variants() {
341 assert_eq!(Value::Text("1.5".to_owned()).try_f64(), None);
342 assert_eq!(Value::Bool(true).try_f64(), None);
343 assert_eq!(Value::Null.try_f64(), None);
344 }
345
346 #[test]
347 fn value_try_date_accepts_date_and_iso_date_text() {
348 let leap_day = NaiveDate::from_ymd_opt(2024, 2, 29).expect("valid leap day");
349
350 assert_eq!(Value::Date(leap_day).try_date(), Some(leap_day));
351 assert_eq!(
352 Value::Text("2024-02-29".to_owned()).try_date(),
353 Some(leap_day)
354 );
355 let millis = leap_day
356 .and_hms_opt(0, 0, 0)
357 .unwrap()
358 .and_utc()
359 .timestamp_millis();
360 assert_eq!(Value::I64(millis).try_date(), Some(leap_day));
361 assert_eq!(Value::U64(millis as u64).try_date(), Some(leap_day));
362 }
363
364 #[test]
365 fn value_try_date_rejects_invalid_dates_and_unrelated_variants() {
366 assert_eq!(Value::Text("2023-02-29".to_owned()).try_date(), None);
367 assert_eq!(
368 Value::Text("2024-02-29T00:00:00Z".to_owned()).try_date(),
369 None
370 );
371 assert_eq!(Value::Null.try_date(), None);
372 }
373
374 #[test]
375 fn value_try_timestamp_accepts_timestamp_and_supported_text_formats() {
376 let utc_timestamp = crate::time::Timestamp(
377 DateTime::parse_from_rfc3339("2024-01-02T03:04:05Z")
378 .expect("valid RFC 3339 timestamp")
379 .with_timezone(&Utc)
380 .timestamp_millis(),
381 );
382 let offset_timestamp = crate::time::Timestamp(
383 DateTime::parse_from_rfc3339("2024-01-02T03:04:05+08:00")
384 .expect("valid RFC 3339 timestamp")
385 .with_timezone(&Utc)
386 .timestamp_millis(),
387 );
388 let naive_timestamp = NaiveDate::from_ymd_opt(2024, 1, 2)
389 .expect("valid date")
390 .and_hms_opt(3, 4, 5)
391 .expect("valid time");
392 let midnight = NaiveDate::from_ymd_opt(2024, 1, 2)
393 .expect("valid date")
394 .and_hms_opt(0, 0, 0)
395 .expect("valid time");
396
397 assert_eq!(
398 Value::Timestamp(utc_timestamp).try_timestamp(),
399 Some(utc_timestamp)
400 );
401 assert_eq!(
402 Value::Text("2024-01-02T03:04:05+08:00".to_owned()).try_timestamp(),
403 Some(offset_timestamp)
404 );
405 assert_eq!(
406 Value::Text("2024-01-02 03:04:05".to_owned()).try_timestamp(),
407 Some(crate::time::Timestamp(
408 DateTime::<Utc>::from_naive_utc_and_offset(naive_timestamp, Utc).timestamp_millis()
409 ))
410 );
411 assert_eq!(
412 Value::Text("2024-01-02".to_owned()).try_timestamp(),
413 Some(crate::time::Timestamp(
414 DateTime::<Utc>::from_naive_utc_and_offset(midnight, Utc).timestamp_millis()
415 ))
416 );
417
418 let millis = utc_timestamp.0;
419 assert_eq!(Value::I64(millis).try_timestamp(), Some(utc_timestamp));
420 assert_eq!(
421 Value::U64(millis as u64).try_timestamp(),
422 Some(utc_timestamp)
423 );
424 }
425
426 #[test]
427 fn value_try_timestamp_normalizes_offsets_and_rejects_invalid_input() {
428 let expected_utc = crate::time::Timestamp(
429 DateTime::parse_from_rfc3339("2024-01-01T19:04:05Z")
430 .expect("valid RFC 3339 timestamp")
431 .with_timezone(&Utc)
432 .timestamp_millis(),
433 );
434
435 assert_eq!(
436 Value::Text("2024-01-02T03:04:05+08:00".to_owned()).try_timestamp(),
437 Some(expected_utc)
438 );
439 assert_eq!(
440 Value::Text("2024-13-40 25:61:61".to_owned()).try_timestamp(),
441 None
442 );
443 assert_eq!(Value::Bool(true).try_timestamp(), None);
444 assert_eq!(Value::Null.try_timestamp(), None);
445 }
446}