1use std::fmt;
12
13use crate::types::LogicalType;
14
15#[derive(Debug, Clone, PartialEq)]
22#[non_exhaustive]
23pub enum Value {
24 Null,
26 Boolean(bool),
28 TinyInt(i8),
30 SmallInt(i16),
32 Integer(i32),
34 BigInt(i64),
36 HugeInt(i128),
38 UTinyInt(u8),
40 USmallInt(u16),
42 UInteger(u32),
44 UBigInt(u64),
46 UHugeInt(u128),
48 Float(f32),
50 Double(f64),
52 Decimal {
54 unscaled: i128,
56 width: u8,
58 scale: u8,
60 },
61 Varchar(String),
63 Blob(Vec<u8>),
65 Date(i32),
67 Time(i64),
69 Timestamp(i64),
71 Interval {
77 months: i32,
79 days: i32,
81 micros: i64,
83 },
84 List {
86 element: LogicalType,
88 values: Vec<Value>,
90 },
91 Struct(Vec<(String, Value)>),
93}
94
95impl Value {
96 #[must_use]
98 pub fn is_null(&self) -> bool {
99 matches!(self, Self::Null)
100 }
101
102 #[must_use]
104 pub fn logical_type(&self) -> LogicalType {
105 match self {
106 Self::Null => LogicalType::Null,
107 Self::Boolean(_) => LogicalType::Boolean,
108 Self::TinyInt(_) => LogicalType::TinyInt,
109 Self::SmallInt(_) => LogicalType::SmallInt,
110 Self::Integer(_) => LogicalType::Integer,
111 Self::BigInt(_) => LogicalType::BigInt,
112 Self::HugeInt(_) => LogicalType::HugeInt,
113 Self::UTinyInt(_) => LogicalType::UTinyInt,
114 Self::USmallInt(_) => LogicalType::USmallInt,
115 Self::UInteger(_) => LogicalType::UInteger,
116 Self::UBigInt(_) => LogicalType::UBigInt,
117 Self::UHugeInt(_) => LogicalType::UHugeInt,
118 Self::Float(_) => LogicalType::Float,
119 Self::Double(_) => LogicalType::Double,
120 Self::Decimal { width, scale, .. } => {
121 LogicalType::Decimal { width: *width, scale: *scale }
122 }
123 Self::Varchar(_) => LogicalType::Varchar,
124 Self::Blob(_) => LogicalType::Blob,
125 Self::Date(_) => LogicalType::Date,
126 Self::Time(_) => LogicalType::Time,
127 Self::Timestamp(_) => LogicalType::Timestamp,
128 Self::Interval { .. } => LogicalType::Interval,
129 Self::List { element, .. } => LogicalType::list(element.clone()),
130 Self::Struct(fields) => LogicalType::Struct(
131 fields
132 .iter()
133 .map(|(name, value)| crate::types::Field::new(name, value.logical_type()))
134 .collect(),
135 ),
136 }
137 }
138
139 #[must_use]
145 pub fn as_i64(&self) -> Option<i64> {
146 match *self {
147 Self::TinyInt(v) => Some(i64::from(v)),
148 Self::SmallInt(v) => Some(i64::from(v)),
149 Self::Integer(v) => Some(i64::from(v)),
150 Self::BigInt(v) => Some(v),
151 Self::UTinyInt(v) => Some(i64::from(v)),
152 Self::USmallInt(v) => Some(i64::from(v)),
153 Self::UInteger(v) => Some(i64::from(v)),
154 Self::UBigInt(v) => i64::try_from(v).ok(),
155 Self::HugeInt(v) => i64::try_from(v).ok(),
156 Self::UHugeInt(v) => i64::try_from(v).ok(),
157 _ => None,
158 }
159 }
160
161 #[must_use]
163 pub fn as_bool(&self) -> Option<bool> {
164 match *self {
165 Self::Boolean(v) => Some(v),
166 _ => None,
167 }
168 }
169
170 #[must_use]
172 pub fn as_str(&self) -> Option<&str> {
173 match self {
174 Self::Varchar(v) => Some(v),
175 _ => None,
176 }
177 }
178}
179
180impl fmt::Display for Value {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 match self {
183 Self::Null => f.write_str("NULL"),
184 Self::Boolean(v) => f.write_str(if *v { "true" } else { "false" }),
185 Self::TinyInt(v) => write!(f, "{v}"),
186 Self::SmallInt(v) => write!(f, "{v}"),
187 Self::Integer(v) => write!(f, "{v}"),
188 Self::BigInt(v) => write!(f, "{v}"),
189 Self::HugeInt(v) => write!(f, "{v}"),
190 Self::UTinyInt(v) => write!(f, "{v}"),
191 Self::USmallInt(v) => write!(f, "{v}"),
192 Self::UInteger(v) => write!(f, "{v}"),
193 Self::UBigInt(v) => write!(f, "{v}"),
194 Self::UHugeInt(v) => write!(f, "{v}"),
195 Self::Float(v) => write_float(f, *v),
196 Self::Double(v) => write_float(f, *v),
197 Self::Decimal { unscaled, scale, .. } => write_decimal(f, *unscaled, *scale),
198 Self::Varchar(v) => f.write_str(v),
199 Self::Blob(v) => write_blob(f, v),
200 Self::Date(v) => write_date(f, *v),
201 Self::Time(v) => write_time(f, *v),
202 Self::Timestamp(v) => write_timestamp(f, *v),
203 Self::Interval { months, days, micros } => write_interval(f, *months, *days, *micros),
204 Self::List { values, .. } => {
205 f.write_str("[")?;
206 for (index, value) in values.iter().enumerate() {
207 if index > 0 {
208 f.write_str(", ")?;
209 }
210 write!(f, "{value}")?;
211 }
212 f.write_str("]")
213 }
214 Self::Struct(fields) => {
215 f.write_str("{")?;
216 for (index, (name, value)) in fields.iter().enumerate() {
217 if index > 0 {
218 f.write_str(", ")?;
219 }
220 write!(f, "'{name}': {value}")?;
221 }
222 f.write_str("}")
223 }
224 }
225 }
226}
227
228trait Real: Copy + fmt::Display + fmt::LowerExp {
235 fn is_nan(self) -> bool;
236 fn is_infinite(self) -> bool;
237 fn is_sign_negative(self) -> bool;
238}
239
240impl Real for f32 {
241 fn is_nan(self) -> bool {
242 Self::is_nan(self)
243 }
244
245 fn is_infinite(self) -> bool {
246 Self::is_infinite(self)
247 }
248
249 fn is_sign_negative(self) -> bool {
250 Self::is_sign_negative(self)
251 }
252}
253
254impl Real for f64 {
255 fn is_nan(self) -> bool {
256 Self::is_nan(self)
257 }
258
259 fn is_infinite(self) -> bool {
260 Self::is_infinite(self)
261 }
262
263 fn is_sign_negative(self) -> bool {
264 Self::is_sign_negative(self)
265 }
266}
267
268fn write_float<T: Real>(f: &mut fmt::Formatter<'_>, value: T) -> fmt::Result {
278 if value.is_nan() {
279 return f.write_str("nan");
280 }
281 if value.is_infinite() {
282 return f.write_str(if value.is_sign_negative() { "-inf" } else { "inf" });
283 }
284 let scientific = format!("{value:e}");
285 let (mantissa, exponent) = scientific.split_once('e').unwrap_or((scientific.as_str(), "0"));
286 let exponent: i32 = exponent.parse().unwrap_or(0);
287 if (-4..16).contains(&exponent) {
288 let text = format!("{value}");
289 if text.contains('.') {
290 return f.write_str(&text);
291 }
292 return write!(f, "{text}.0");
293 }
294 let sign = if exponent < 0 { '-' } else { '+' };
295 write!(f, "{mantissa}e{sign}{:02}", exponent.abs())
296}
297
298fn write_decimal(f: &mut fmt::Formatter<'_>, unscaled: i128, scale: u8) -> fmt::Result {
299 if scale == 0 {
300 return write!(f, "{unscaled}");
301 }
302 let negative = unscaled < 0;
303 let digits = unscaled.unsigned_abs().to_string();
305 let scale = usize::from(scale);
306 let (whole, fraction) = if digits.len() > scale {
307 let split = digits.len() - scale;
308 (digits[..split].to_string(), digits[split..].to_string())
309 } else {
310 ("0".to_string(), format!("{:0>scale$}", digits))
311 };
312 if negative {
313 f.write_str("-")?;
314 }
315 write!(f, "{whole}.{fraction}")
316}
317
318fn write_blob(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
325 for &byte in bytes {
326 if (byte.is_ascii_graphic() || byte == b' ') && !matches!(byte, b'\\' | b'\'' | b'"') {
327 write!(f, "{}", byte as char)?;
328 } else {
329 write!(f, "\\x{byte:02X}")?;
330 }
331 }
332 Ok(())
333}
334
335#[must_use]
342pub fn civil_from_days(days: i32) -> (i32, u32, u32) {
343 let z = i64::from(days) + 719_468;
344 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
345 let day_of_era = z - era * 146_097;
346 let year_of_era =
347 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
348 let year = year_of_era + era * 400;
349 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
350 let shifted_month = (5 * day_of_year + 2) / 153;
351 let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
352 let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
353 let year = if month <= 2 { year + 1 } else { year };
354 #[expect(clippy::cast_possible_truncation, reason = "the ranges are 1 to 12 and 1 to 31")]
355 (year as i32, month as u32, day as u32)
356}
357
358#[must_use]
360pub fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
361 let year = i64::from(year) - i64::from(month <= 2);
362 let era = if year >= 0 { year } else { year - 399 } / 400;
363 let year_of_era = year - era * 400;
364 let month = i64::from(month);
365 let shifted_month = if month > 2 { month - 3 } else { month + 9 };
366 let day_of_year = (153 * shifted_month + 2) / 5 + i64::from(day) - 1;
367 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
368 #[expect(clippy::cast_possible_truncation, reason = "a date in i32 range stays in i32 range")]
369 ((era * 146_097 + day_of_era - 719_468) as i32)
370}
371
372fn write_date(f: &mut fmt::Formatter<'_>, days: i32) -> fmt::Result {
373 let (year, month, day) = civil_from_days(days);
374 if year < 0 {
375 write!(f, "{:04}-{month:02}-{day:02} (BC)", -year + 1)
376 } else {
377 write!(f, "{year:04}-{month:02}-{day:02}")
378 }
379}
380
381fn write_time(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
382 let seconds = micros.div_euclid(1_000_000);
383 let fraction = micros.rem_euclid(1_000_000);
384 let (hours, minutes, seconds) = (seconds / 3600, (seconds / 60) % 60, seconds % 60);
385 write!(f, "{hours:02}:{minutes:02}:{seconds:02}")?;
386 if fraction != 0 {
387 let text = format!("{fraction:06}");
389 write!(f, ".{}", text.trim_end_matches('0'))?;
390 }
391 Ok(())
392}
393
394fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
395 const MICROS_PER_DAY: i64 = 86_400 * 1_000_000;
396 let days = micros.div_euclid(MICROS_PER_DAY);
397 let within_day = micros.rem_euclid(MICROS_PER_DAY);
398 let Ok(days) = i32::try_from(days) else {
399 return f.write_str("timestamp out of range");
400 };
401 write_date(f, days)?;
402 f.write_str(" ")?;
403 write_time(f, within_day)
404}
405
406fn write_interval(f: &mut fmt::Formatter<'_>, months: i32, days: i32, micros: i64) -> fmt::Result {
407 let mut wrote = false;
408 let space = |f: &mut fmt::Formatter<'_>, wrote: &mut bool| -> fmt::Result {
409 if *wrote {
410 f.write_str(" ")?;
411 }
412 *wrote = true;
413 Ok(())
414 };
415 let (years, rest_months) = (months / 12, months % 12);
416 if years != 0 {
417 space(f, &mut wrote)?;
418 write!(f, "{years} year{}", plural(years))?;
419 }
420 if rest_months != 0 {
421 space(f, &mut wrote)?;
422 write!(f, "{rest_months} month{}", plural(rest_months))?;
423 }
424 if days != 0 {
425 space(f, &mut wrote)?;
426 write!(f, "{days} day{}", plural(days))?;
427 }
428 if micros != 0 || !wrote {
429 space(f, &mut wrote)?;
430 if micros < 0 {
431 f.write_str("-")?;
432 }
433 write_time(f, micros.abs())?;
434 }
435 Ok(())
436}
437
438fn plural(n: i32) -> &'static str {
439 if n == 1 || n == -1 { "" } else { "s" }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::{Value, civil_from_days, days_from_civil};
445 use crate::types::LogicalType;
446
447 #[test]
448 fn a_value_knows_its_own_type() {
449 assert_eq!(Value::Integer(1).logical_type(), LogicalType::Integer);
450 assert_eq!(Value::Null.logical_type(), LogicalType::Null);
451 let list = Value::List { element: LogicalType::Varchar, values: Vec::new() };
452 assert_eq!(list.logical_type(), LogicalType::list(LogicalType::Varchar));
455 }
456
457 #[test]
458 fn the_date_conversion_is_its_own_inverse() {
459 for days in days_from_civil(1600, 1, 1)..days_from_civil(2400, 1, 1) {
462 let (year, month, day) = civil_from_days(days);
463 assert_eq!(days_from_civil(year, month, day), days, "{year}-{month}-{day}");
464 }
465 }
466
467 #[test]
468 fn the_epoch_is_where_it_should_be() {
469 assert_eq!(days_from_civil(1970, 1, 1), 0);
470 assert_eq!(civil_from_days(0), (1970, 1, 1));
471 assert_eq!(Value::Date(0).to_string(), "1970-01-01");
472 assert_eq!(Value::Date(19_723).to_string(), "2024-01-01");
473 assert_eq!(Value::Date(19_737).to_string(), "2024-01-15");
474 }
475
476 #[test]
477 fn a_leap_day_is_a_day() {
478 assert_eq!(civil_from_days(days_from_civil(2024, 2, 29)), (2024, 2, 29));
479 assert_eq!(days_from_civil(1900, 3, 1) - days_from_civil(1900, 2, 28), 1);
482 assert_eq!(days_from_civil(2000, 3, 1) - days_from_civil(2000, 2, 28), 2);
483 }
484
485 #[test]
486 fn times_print_with_the_trailing_zeros_trimmed() {
487 assert_eq!(Value::Time(0).to_string(), "00:00:00");
488 assert_eq!(Value::Time(3_723_000_000).to_string(), "01:02:03");
489 assert_eq!(Value::Time(3_723_500_000).to_string(), "01:02:03.5");
490 assert_eq!(Value::Time(3_723_000_001).to_string(), "01:02:03.000001");
491 }
492
493 #[test]
494 fn a_timestamp_before_the_epoch_borrows_from_the_day() {
495 assert_eq!(Value::Timestamp(-1).to_string(), "1969-12-31 23:59:59.999999");
498 assert_eq!(Value::Timestamp(0).to_string(), "1970-01-01 00:00:00");
499 }
500
501 #[test]
502 fn a_decimal_prints_at_its_scale() {
503 let d = |unscaled, scale| Value::Decimal { unscaled, width: 18, scale }.to_string();
504 assert_eq!(d(1234, 2), "12.34");
505 assert_eq!(d(-1234, 2), "-12.34");
506 assert_eq!(d(5, 3), "0.005");
507 assert_eq!(d(-5, 3), "-0.005");
508 assert_eq!(d(1234, 0), "1234");
509 assert_eq!(d(1_000_000, 6), "1.000000");
510 }
511
512 #[test]
513 fn a_float_keeps_the_point_that_says_it_is_one() {
514 assert_eq!(Value::Double(1.0).to_string(), "1.0");
515 assert_eq!(Value::Double(-3.0).to_string(), "-3.0");
516 assert_eq!(Value::Double(1.5).to_string(), "1.5");
517 assert_eq!(Value::Double(-0.0).to_string(), "-0.0");
518 assert_eq!(Value::Float(0.5).to_string(), "0.5");
519 }
520
521 #[test]
522 fn a_float_is_printed_from_its_own_width_rather_than_widened_first() {
523 assert_eq!(Value::Float(0.1).to_string(), "0.1");
526 assert_eq!(Value::Float(1.0).to_string(), "1.0");
527 }
528
529 #[test]
530 fn a_float_switches_to_an_exponent_where_duckdb_switches() {
531 assert_eq!(Value::Double(1e15).to_string(), "1000000000000000.0");
532 assert_eq!(Value::Double(1e16).to_string(), "1e+16");
533 assert_eq!(Value::Double(1e20).to_string(), "1e+20");
534 assert_eq!(Value::Double(1e-4).to_string(), "0.0001");
535 assert_eq!(Value::Double(1e-5).to_string(), "1e-05");
536 assert_eq!(Value::Double(1.234_567_890_123_456_8e17).to_string(), "1.2345678901234568e+17");
537 }
538
539 #[test]
540 fn a_float_that_is_not_a_number_says_so_the_way_duckdb_says_it() {
541 assert_eq!(Value::Double(f64::INFINITY).to_string(), "inf");
542 assert_eq!(Value::Double(f64::NEG_INFINITY).to_string(), "-inf");
543 assert_eq!(Value::Double(f64::NAN).to_string(), "nan");
544 }
545
546 #[test]
547 fn an_interval_keeps_months_days_and_micros_apart() {
548 let i = |months, days, micros| Value::Interval { months, days, micros }.to_string();
549 assert_eq!(i(14, 3, 3_723_000_000), "1 year 2 months 3 days 01:02:03");
550 assert_eq!(i(1, 0, 0), "1 month");
551 assert_eq!(i(0, 0, 0), "00:00:00");
552 assert_eq!(i(0, 0, -1_000_000), "-00:00:01");
553 }
554
555 #[test]
556 fn a_blob_escapes_what_is_not_printable() {
557 assert_eq!(Value::Blob(b"ok".to_vec()).to_string(), "ok");
558 assert_eq!(Value::Blob(vec![0, 1, b'a']).to_string(), "\\x00\\x01a");
559 assert_eq!(Value::Blob(vec![0x7f, 0xff]).to_string(), "\\x7F\\xFF");
560 assert_eq!(Value::Blob(br#"'"\"#.to_vec()).to_string(), "\\x27\\x22\\x5C");
562 assert_eq!(Value::Blob(b" &`~".to_vec()).to_string(), " &`~");
563 }
564
565 #[test]
566 fn a_limit_that_does_not_fit_is_none_rather_than_clamped() {
567 assert_eq!(Value::Integer(5).as_i64(), Some(5));
568 assert_eq!(Value::UBigInt(u64::MAX).as_i64(), None);
569 assert_eq!(Value::Varchar("5".into()).as_i64(), None);
570 }
571}