Skip to main content

interval_to_micros

Function interval_to_micros 

Source
pub fn interval_to_micros(iv: DuckInterval) -> Option<i64>
Expand description

Converts a DuckInterval to total microseconds with overflow checking.

Uses the approximation: 1 month = 30 days. DuckDB uses the same approximation in exactly two places (checked on DuckDB 1.4.4 and 1.5.5):

  • Comparing intervals — interval '1 month' = interval '30 days' is true (Interval::DAYS_PER_MONTH = 30 in interval.hpp). DuckDB normalises the fields (interval_t::Normalize: micros carry into days, days into months, with truncating division) and compares them in order, so this agrees with comparing total microseconds only when the fields do not mix signs: interval '1 month' - interval '1 day' equals interval '29 days' in microseconds but compares greater in SQL.
  • epoch_us(interval) — returns exactly what this function returns whenever it returns a value; epoch_us(interval '1 year') is 360 days. DuckDB adds the fields one at a time in i64 (Interval::GetMicro) and fails with “Could not convert Day to Microseconds” when one of them overflows on its own, as 106751992 days -86400000000 microseconds does; this function computes the exact total and returns it whenever the total fits.

It is not what DuckDB does elsewhere: interval + interval keeps months, days and micros separate (1 month 30 days), adding an interval to a date uses calendar months (2024-01-31 + 1 month is 2024-02-29), and epoch(interval '1 year') counts 365.25 days. Use this conversion for ordering or bucketing intervals, not for date arithmetic.

§Returns

None if the total does not fit in an i64. Intermediate results never overflow: the sum is computed exactly, so {months: 2770036, days: 31299404, micros: -2032753245989188716}, whose months and days alone exceed i64::MAX, converts to 7851448571610811284.

§Example

use quack_rs::interval::{interval_to_micros, DuckInterval};

// 2 hours 30 minutes = 9_000_000_000 microseconds
let iv = DuckInterval { months: 0, days: 0, micros: 9_000_000_000 };
assert_eq!(interval_to_micros(iv), Some(9_000_000_000_i64));

// 1 day
let iv = DuckInterval { months: 0, days: 1, micros: 0 };
assert_eq!(interval_to_micros(iv), Some(86_400_000_000_i64));

// Overflow returns None
let iv = DuckInterval { months: i32::MAX, days: i32::MAX, micros: i64::MAX };
assert_eq!(interval_to_micros(iv), None);