1use std::fmt::Write as _;
5use std::net::{Ipv4Addr, Ipv6Addr};
6use std::sync::Arc;
7
8use chrono::{DateTime, NaiveDate, Utc};
9use uuid::Uuid;
10
11#[derive(Debug, Clone, PartialEq)]
14pub enum Value {
15 Null,
16 Bool(bool),
17 Int(i64),
19 UInt(u64),
21 Int128(i128),
22 UInt128(u128),
23 BigInt(String),
25 Float32(f32),
26 Float64(f64),
27 Decimal(String),
29 String(Vec<u8>),
31 Uuid(Uuid),
32 Date(i32),
34 DateTime {
36 secs: i64,
37 tz: Option<Arc<str>>,
38 },
39 DateTime64 {
41 ticks: i64,
42 precision: u8,
43 tz: Option<Arc<str>>,
44 },
45 Time(i64),
47 Time64 {
49 ticks: i64,
50 precision: u8,
51 },
52 Enum(String),
54 Ipv4(Ipv4Addr),
55 Ipv6(Ipv6Addr),
56 Array(Vec<Value>),
57 Tuple(Vec<Value>),
58 Map(Vec<(Value, Value)>),
59 Json(String),
61}
62
63impl From<&str> for Value {
64 fn from(s: &str) -> Self {
65 Value::String(s.as_bytes().to_vec())
66 }
67}
68impl From<String> for Value {
69 fn from(s: String) -> Self {
70 Value::String(s.into_bytes())
71 }
72}
73impl From<bool> for Value {
74 fn from(b: bool) -> Self {
75 Value::Bool(b)
76 }
77}
78impl From<i64> for Value {
79 fn from(i: i64) -> Self {
80 Value::Int(i)
81 }
82}
83impl From<u64> for Value {
84 fn from(i: u64) -> Self {
85 Value::UInt(i)
86 }
87}
88impl From<f64> for Value {
89 fn from(f: f64) -> Self {
90 Value::Float64(f)
91 }
92}
93impl From<Uuid> for Value {
94 fn from(u: Uuid) -> Self {
95 Value::Uuid(u)
96 }
97}
98impl From<DateTime<Utc>> for Value {
99 fn from(t: DateTime<Utc>) -> Self {
100 Value::timestamp_micros(t.timestamp_micros())
101 }
102}
103impl<T: Into<Value>> From<Option<T>> for Value {
104 fn from(o: Option<T>) -> Self {
105 o.map_or(Value::Null, Into::into)
106 }
107}
108impl<T: Into<Value>> From<Vec<T>> for Value {
109 fn from(v: Vec<T>) -> Self {
110 Value::Array(v.into_iter().map(Into::into).collect())
111 }
112}
113
114const UNIX_EPOCH_DAYS_FROM_CE: i32 = 719_163;
115
116impl Value {
117 pub fn timestamp_micros(micros: i64) -> Value {
119 Value::DateTime64 {
120 ticks: micros,
121 precision: 6,
122 tz: Some(Arc::from("UTC")),
123 }
124 }
125
126 pub fn date(d: NaiveDate) -> Value {
128 Value::Date(d.num_days_from_ce_compat() - UNIX_EPOCH_DAYS_FROM_CE)
129 }
130
131 pub fn as_naive_date(days: i32) -> Option<NaiveDate> {
133 NaiveDate::from_num_days_from_ce_opt(days.checked_add(UNIX_EPOCH_DAYS_FROM_CE)?)
134 }
135
136 pub fn epoch(&self) -> Option<(i64, u32)> {
138 match self {
139 Value::DateTime { secs, .. } => Some((*secs, 0)),
140 Value::DateTime64 {
141 ticks, precision, ..
142 } => {
143 let scale = 10i64.checked_pow(u32::from(*precision))?;
144 let secs = ticks.div_euclid(scale);
145 let frac = ticks.rem_euclid(scale);
146 let nanos = if *precision <= 9 {
147 frac * 10i64.pow(9 - u32::from(*precision))
148 } else {
149 frac / 10i64.pow(u32::from(*precision) - 9)
150 };
151 Some((secs, nanos as u32))
152 }
153 _ => None,
154 }
155 }
156
157 pub fn to_param_text(&self) -> Vec<u8> {
160 let mut out = Vec::new();
161 self.write_param(&mut out, true);
162 out
163 }
164
165 fn write_param(&self, out: &mut Vec<u8>, top: bool) {
166 match self {
167 Value::Null => out.extend_from_slice(if top { b"\\N" } else { b"NULL" }),
168 Value::String(b) => {
169 if top {
170 escape_tsv(out, b)
171 } else {
172 quote(out, b)
173 }
174 }
175 Value::Enum(s) | Value::Json(s) => {
176 if top {
177 escape_tsv(out, s.as_bytes())
178 } else {
179 quote(out, s.as_bytes())
180 }
181 }
182 Value::Array(items) => {
183 out.push(b'[');
184 for (i, v) in items.iter().enumerate() {
185 if i > 0 {
186 out.push(b',');
187 }
188 v.write_param(out, false);
189 }
190 out.push(b']');
191 }
192 Value::Tuple(items) => {
193 out.push(b'(');
194 for (i, v) in items.iter().enumerate() {
195 if i > 0 {
196 out.push(b',');
197 }
198 v.write_param(out, false);
199 }
200 out.push(b')');
201 }
202 Value::Map(entries) => {
203 out.push(b'{');
204 for (i, (k, v)) in entries.iter().enumerate() {
205 if i > 0 {
206 out.push(b',');
207 }
208 k.write_param(out, false);
209 out.push(b':');
210 v.write_param(out, false);
211 }
212 out.push(b'}');
213 }
214 other => {
215 let text = other.scalar_text();
218 let quoted = !top && other.needs_quotes();
219 if quoted {
220 quote(out, text.as_bytes());
221 } else {
222 out.extend_from_slice(text.as_bytes());
223 }
224 }
225 }
226 }
227
228 fn needs_quotes(&self) -> bool {
229 matches!(
230 self,
231 Value::Uuid(_)
232 | Value::Date(_)
233 | Value::DateTime { .. }
234 | Value::DateTime64 { .. }
235 | Value::Time(_)
236 | Value::Time64 { .. }
237 | Value::Ipv4(_)
238 | Value::Ipv6(_)
239 )
240 }
241
242 fn scalar_text(&self) -> String {
244 match self {
245 Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
246 Value::Int(i) => i.to_string(),
247 Value::UInt(i) => i.to_string(),
248 Value::Int128(i) => i.to_string(),
249 Value::UInt128(i) => i.to_string(),
250 Value::BigInt(s) | Value::Decimal(s) => s.clone(),
251 Value::Float32(f) => float_text(f64::from(*f)),
252 Value::Float64(f) => float_text(*f),
253 Value::Uuid(u) => u.hyphenated().to_string(),
254 Value::Date(d) => match Value::as_naive_date(*d) {
255 Some(d) => d.format("%Y-%m-%d").to_string(),
256 None => d.to_string(),
257 },
258 Value::DateTime { .. } | Value::DateTime64 { .. } => self.timestamp_text(),
259 Value::Time(s) => time_text(i128::from(*s), 0),
260 Value::Time64 { ticks, precision } => time_text(i128::from(*ticks), *precision),
261 Value::Ipv4(ip) => ip.to_string(),
262 Value::Ipv6(ip) => ip.to_string(),
263 Value::Null => "NULL".to_string(),
264 Value::String(b) => String::from_utf8_lossy(b).into_owned(),
265 Value::Enum(s) | Value::Json(s) => s.clone(),
266 Value::Array(_) | Value::Tuple(_) | Value::Map(_) => {
267 String::from_utf8_lossy(&self.to_param_text()).into_owned()
268 }
269 }
270 }
271
272 fn timestamp_text(&self) -> String {
276 match self {
277 Value::DateTime { secs, .. } => secs.to_string(),
278 Value::DateTime64 {
279 ticks, precision, ..
280 } => fixed_point(*ticks, *precision),
281 _ => unreachable!(),
282 }
283 }
284
285 pub fn write_json(&self, out: &mut String) {
287 match self {
288 Value::Null => out.push_str("null"),
289 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
290 Value::Int(i) => {
291 let _ = write!(out, "{i}");
292 }
293 Value::UInt(i) => {
294 let _ = write!(out, "{i}");
295 }
296 Value::Int128(i) => {
297 let _ = write!(out, "{i}");
298 }
299 Value::UInt128(i) => {
300 let _ = write!(out, "{i}");
301 }
302 Value::BigInt(s) => out.push_str(s),
303 Value::Float32(f) => json_float(out, f64::from(*f)),
304 Value::Float64(f) => json_float(out, *f),
305 Value::Decimal(s) => json_string(out, s),
306 Value::String(b) => json_string(out, &String::from_utf8_lossy(b)),
307 Value::Enum(s) => json_string(out, s),
308 Value::Json(s) => out.push_str(s),
309 Value::Array(items) | Value::Tuple(items) => {
310 out.push('[');
311 for (i, v) in items.iter().enumerate() {
312 if i > 0 {
313 out.push(',');
314 }
315 v.write_json(out);
316 }
317 out.push(']');
318 }
319 Value::DateTime { .. } | Value::DateTime64 { .. } => {
323 let text = self.calendar_text().replacen(' ', "T", 1) + "Z";
324 json_string(out, &text);
325 }
326 Value::Map(entries) => {
327 out.push('{');
328 for (i, (k, v)) in entries.iter().enumerate() {
329 if i > 0 {
330 out.push(',');
331 }
332 let key = match k {
333 Value::String(b) => String::from_utf8_lossy(b).into_owned(),
334 other => other.scalar_text(),
335 };
336 json_string(out, &key);
337 out.push(':');
338 v.write_json(out);
339 }
340 out.push('}');
341 }
342 other => json_string(out, &other.scalar_text()),
343 }
344 }
345
346 pub fn display_text(&self) -> String {
349 match self {
350 Value::Null => "NULL".to_string(),
351 Value::DateTime { .. } | Value::DateTime64 { .. } => self.calendar_text(),
352 Value::Array(_) | Value::Tuple(_) | Value::Map(_) => {
353 let mut out = Vec::new();
354 self.write_param(&mut out, false);
355 String::from_utf8_lossy(&out).into_owned()
356 }
357 other => other.scalar_text(),
358 }
359 }
360
361 pub fn calendar_text(&self) -> String {
363 let precision = match self {
364 Value::DateTime64 { precision, .. } => *precision,
365 _ => 0,
366 };
367 let Some((secs, nanos)) = self.epoch() else {
368 return self.scalar_text();
369 };
370 match DateTime::<Utc>::from_timestamp(secs, nanos) {
371 Some(t) if precision == 0 => t.format("%Y-%m-%d %H:%M:%S").to_string(),
372 Some(t) => {
373 let frac = format!("{:09}", nanos);
374 let digits = usize::from(precision.min(9));
375 format!("{}.{}", t.format("%Y-%m-%d %H:%M:%S"), &frac[..digits])
376 }
377 None => secs.to_string(),
378 }
379 }
380
381 pub fn to_display_json(&self) -> serde_json::Value {
385 use serde_json::Value as J;
386 const SAFE: u64 = 1 << 53;
387 match self {
388 Value::Null => J::Null,
389 Value::Bool(b) => J::Bool(*b),
390 Value::Int(i) if i.unsigned_abs() <= SAFE => J::from(*i),
391 Value::UInt(i) if *i <= SAFE => J::from(*i),
392 Value::Float32(f) => serde_json::Number::from_f64(f64::from(*f))
393 .map(J::Number)
394 .unwrap_or_else(|| J::String(float_text(f64::from(*f)))),
395 Value::Float64(f) => serde_json::Number::from_f64(*f)
396 .map(J::Number)
397 .unwrap_or_else(|| J::String(float_text(*f))),
398 Value::Json(s) => serde_json::from_str(s).unwrap_or_else(|_| J::String(s.clone())),
399 Value::Array(items) | Value::Tuple(items) => {
400 J::Array(items.iter().map(Value::to_display_json).collect())
401 }
402 Value::Map(entries) => J::Object(
403 entries
404 .iter()
405 .map(|(k, v)| (k.display_text(), v.to_display_json()))
406 .collect(),
407 ),
408 other => J::String(other.display_text()),
409 }
410 }
411}
412
413trait CeDays {
414 fn num_days_from_ce_compat(&self) -> i32;
415}
416impl CeDays for NaiveDate {
417 fn num_days_from_ce_compat(&self) -> i32 {
418 use chrono::Datelike;
419 self.num_days_from_ce()
420 }
421}
422
423fn time_text(ticks: i128, precision: u8) -> String {
426 let scale = 10i128.pow(u32::from(precision));
427 let sign = if ticks < 0 { "-" } else { "" };
428 let abs = ticks.abs();
429 let secs = abs / scale;
430 let frac = abs % scale;
431 let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
432 if precision == 0 {
433 format!("{sign}{h:02}:{m:02}:{s:02}")
434 } else {
435 format!(
436 "{sign}{h:02}:{m:02}:{s:02}.{frac:0width$}",
437 width = usize::from(precision)
438 )
439 }
440}
441
442fn fixed_point(ticks: i64, precision: u8) -> String {
444 if precision == 0 {
445 return ticks.to_string();
446 }
447 let scale = 10u128.pow(u32::from(precision));
448 let abs = u128::from(ticks.unsigned_abs());
449 let sign = if ticks < 0 { "-" } else { "" };
450 format!(
451 "{sign}{}.{:0width$}",
452 abs / scale,
453 abs % scale,
454 width = usize::from(precision)
455 )
456}
457
458fn float_text(f: f64) -> String {
459 if f.is_nan() {
460 "nan".to_string()
461 } else if f.is_infinite() {
462 if f > 0.0 { "inf" } else { "-inf" }.to_string()
463 } else {
464 format!("{f:?}")
466 }
467}
468
469fn json_float(out: &mut String, f: f64) {
470 if f.is_finite() {
471 let _ = write!(out, "{f:?}");
472 } else {
473 json_string(out, &float_text(f));
474 }
475}
476
477fn json_string(out: &mut String, s: &str) {
478 out.push_str(&serde_json::Value::String(s.to_string()).to_string());
479}
480
481fn escape_tsv(out: &mut Vec<u8>, b: &[u8]) {
483 for &c in b {
484 match c {
485 b'\\' => out.extend_from_slice(b"\\\\"),
486 b'\t' => out.extend_from_slice(b"\\t"),
487 b'\n' => out.extend_from_slice(b"\\n"),
488 b'\r' => out.extend_from_slice(b"\\r"),
489 0 => out.extend_from_slice(b"\\0"),
490 8 => out.extend_from_slice(b"\\b"),
491 12 => out.extend_from_slice(b"\\f"),
492 c => out.push(c),
493 }
494 }
495}
496
497fn quote(out: &mut Vec<u8>, b: &[u8]) {
499 out.push(b'\'');
500 for &c in b {
501 match c {
502 b'\'' => out.extend_from_slice(b"\\'"),
503 b'\\' => out.extend_from_slice(b"\\\\"),
504 b'\t' => out.extend_from_slice(b"\\t"),
505 b'\n' => out.extend_from_slice(b"\\n"),
506 b'\r' => out.extend_from_slice(b"\\r"),
507 0 => out.extend_from_slice(b"\\0"),
508 c => out.push(c),
509 }
510 }
511 out.push(b'\'');
512}
513
514pub fn infer_type(v: &Value) -> String {
517 match v {
518 Value::Null => "Nullable(String)".into(),
519 Value::Bool(_) => "Bool".into(),
520 Value::Int(_) => "Int64".into(),
521 Value::UInt(_) => "UInt64".into(),
522 Value::Int128(_) => "Int128".into(),
523 Value::UInt128(_) => "UInt128".into(),
524 Value::BigInt(s) if s.starts_with('-') => "Int256".into(),
525 Value::BigInt(_) => "UInt256".into(),
526 Value::Float32(_) => "Float32".into(),
527 Value::Float64(_) => "Float64".into(),
528 Value::Decimal(s) => {
529 let scale = s.split_once('.').map_or(0, |(_, f)| f.len()).min(76);
530 format!("Decimal(76, {scale})")
531 }
532 Value::String(_) | Value::Json(_) | Value::Enum(_) => "String".into(),
533 Value::Uuid(_) => "UUID".into(),
534 Value::Date(_) => "Date32".into(),
535 Value::DateTime { tz, .. } => match tz {
536 Some(tz) => format!("DateTime('{}')", tz.replace('\'', "\\'")),
537 None => "DateTime".into(),
538 },
539 Value::DateTime64 { precision, tz, .. } => match tz {
540 Some(tz) => format!("DateTime64({precision}, '{}')", tz.replace('\'', "\\'")),
541 None => format!("DateTime64({precision})"),
542 },
543 Value::Time(_) => "Time".into(),
544 Value::Time64 { precision, .. } => format!("Time64({precision})"),
545 Value::Ipv4(_) => "IPv4".into(),
546 Value::Ipv6(_) => "IPv6".into(),
547 Value::Array(items) => {
548 let elem = element_type(items.iter());
549 format!("Array({elem})")
550 }
551 Value::Tuple(items) => {
552 let parts: Vec<String> = items.iter().map(infer_type).collect();
553 format!("Tuple({})", parts.join(", "))
554 }
555 Value::Map(entries) => {
556 let k = element_type(entries.iter().map(|(k, _)| k));
557 let v = element_type(entries.iter().map(|(_, v)| v));
558 format!("Map({k}, {v})")
559 }
560 }
561}
562
563fn element_type<'a>(items: impl Iterator<Item = &'a Value>) -> String {
566 let mut nullable = false;
567 let mut ty = None;
568 for v in items {
569 if matches!(v, Value::Null) {
570 nullable = true;
571 } else if ty.is_none() {
572 ty = Some(infer_type(v));
573 }
574 }
575 match ty {
576 None => "Nullable(String)".into(),
577 Some(t) if nullable && can_be_nullable(&t) => format!("Nullable({t})"),
578 Some(t) => t,
579 }
580}
581
582fn can_be_nullable(t: &str) -> bool {
584 !(t.starts_with("Array(") || t.starts_with("Map(") || t.starts_with("Tuple("))
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590
591 fn text(v: &Value) -> String {
592 String::from_utf8(v.to_param_text()).unwrap()
593 }
594
595 #[test]
596 fn param_text() {
597 assert_eq!(text(&Value::from("a\tb\\c'")), "a\\tb\\\\c'");
598 assert_eq!(text(&Value::from(vec!["a'b", "c"])), "['a\\'b','c']");
599 assert_eq!(text(&Value::Null), "\\N");
600 assert_eq!(
601 text(&Value::Array(vec![Value::Int(1), Value::Null])),
602 "[1,NULL]"
603 );
604 assert_eq!(
605 text(&Value::timestamp_micros(1_700_000_000_123_456)),
606 "1700000000.123456"
607 );
608 assert_eq!(
609 text(&Value::Array(vec![Value::timestamp_micros(1_000_000)])),
610 "['1.000000']"
611 );
612 assert_eq!(text(&Value::timestamp_micros(-1_500_000)), "-1.500000");
613 assert_eq!(text(&Value::Time(-3601)), "-01:00:01");
614 assert_eq!(
615 text(&Value::Time64 {
616 ticks: 360_001_500,
617 precision: 3
618 }),
619 "100:00:01.500"
620 );
621 assert_eq!(text(&Value::Date(0)), "1970-01-01");
622 assert_eq!(
623 text(&Value::Map(vec![(Value::from("k"), Value::Int(2))])),
624 "{'k':2}"
625 );
626 assert_eq!(
627 text(&Value::Tuple(vec![Value::Int(1), Value::from("x")])),
628 "(1,'x')"
629 );
630 assert_eq!(text(&Value::Float64(0.5)), "0.5");
631 assert_eq!(text(&Value::Float64(f64::NAN)), "nan");
632 }
633
634 #[test]
635 fn inferred_types() {
636 assert_eq!(infer_type(&Value::from("x")), "String");
637 assert_eq!(infer_type(&Value::Int(1)), "Int64");
638 assert_eq!(
639 infer_type(&Value::Array(vec![Value::Null, Value::Int(1)])),
640 "Array(Nullable(Int64))"
641 );
642 assert_eq!(infer_type(&Value::Array(vec![])), "Array(Nullable(String))");
643 assert_eq!(
644 infer_type(&Value::timestamp_micros(0)),
645 "DateTime64(6, 'UTC')"
646 );
647 assert_eq!(
648 infer_type(&Value::Decimal("1.250".into())),
649 "Decimal(76, 3)"
650 );
651 assert_eq!(
652 infer_type(&Value::Map(vec![(
653 Value::from("a"),
654 Value::Array(vec![Value::Int(1)])
655 )])),
656 "Map(String, Array(Int64))"
657 );
658 }
659
660 #[test]
661 fn json() {
662 let mut s = String::new();
663 Value::Tuple(vec![
664 Value::UInt(u64::MAX),
665 Value::Decimal("1.5".into()),
666 Value::from("a\"b"),
667 Value::timestamp_micros(2_500_000),
668 Value::Json("{\"x\":1}".into()),
669 ])
670 .write_json(&mut s);
671 assert_eq!(
672 s,
673 "[18446744073709551615,\"1.5\",\"a\\\"b\",\"1970-01-01T00:00:02.500000Z\",{\"x\":1}]"
674 );
675 }
676
677 #[test]
678 fn epoch_and_calendar() {
679 let v = Value::DateTime64 {
680 ticks: -1,
681 precision: 3,
682 tz: None,
683 };
684 assert_eq!(v.epoch(), Some((-1, 999_000_000)));
685 assert_eq!(v.calendar_text(), "1969-12-31 23:59:59.999");
686 assert_eq!(
687 Value::as_naive_date(19_000).unwrap().to_string(),
688 "2022-01-08"
689 );
690 }
691}