Skip to main content

rushdb_query/
datetime.rs

1//! Query-level datetime operators over the canonical Chrono-backed type
2//! implementation in `rushdb-types`.
3
4/// Build an epoch-millisecond timestamp from calendar components.
5#[must_use]
6pub fn components_to_epoch_ms(
7    year: i64,
8    month: i64,
9    day: i64,
10    hour: i64,
11    minute: i64,
12    second: i64,
13    millis: i64,
14) -> i64 {
15    rushdb_types::datetime::components_to_epoch_ms(year, month, day, hour, minute, second, millis)
16}
17
18/// Parse an ISO-8601 datetime string into epoch milliseconds, or `None` when
19/// the input is not a valid datetime.
20#[must_use]
21pub fn parse_iso_8601(value: &str) -> Option<i64> {
22    rushdb_types::datetime::parse_datetime(value)
23}
24
25/// Parse a `{$year, $month, ...}` component object into epoch milliseconds,
26/// or `None` when required components are missing or out of range.
27#[must_use]
28pub fn parse_components(map: &serde_json::Map<String, serde_json::Value>) -> Option<i64> {
29    let year = get(map, "$year")?;
30    let month = get(map, "$month").unwrap_or(1);
31    let day = get(map, "$day").unwrap_or(1);
32    let hour = get(map, "$hour").unwrap_or(0);
33    let minute = get(map, "$minute").unwrap_or(0);
34    let second = get(map, "$second").unwrap_or(0);
35    let millis = get(map, "$millisecond").unwrap_or(0);
36    rushdb_types::datetime::components_to_epoch_ms_checked(
37        year, month, day, hour, minute, second, millis,
38    )
39}
40
41/// Epoch milliseconds at the start of `year` (January 1st, 00:00:00.000).
42#[must_use]
43pub fn year_start(year: i64) -> i64 {
44    rushdb_types::datetime::components_to_epoch_ms(year, 1, 1, 0, 0, 0, 0)
45}
46
47/// Epoch milliseconds at the start of the year after `year` (exclusive end).
48#[must_use]
49pub fn year_end(year: i64) -> i64 {
50    rushdb_types::datetime::components_to_epoch_ms(year + 1, 1, 1, 0, 0, 0, 0)
51}
52
53fn get(map: &serde_json::Map<String, serde_json::Value>, key: &str) -> Option<i64> {
54    map.get(key).and_then(|value| {
55        value
56            .as_i64()
57            .or_else(|| value.as_u64().and_then(|v| v.try_into().ok()))
58    })
59}
60
61/// Extract one calendar component (`which`: 0=year .. 6=millisecond) from an
62/// epoch-millisecond timestamp.
63#[must_use]
64pub fn component_of(ms: i64, which: u8) -> i64 {
65    rushdb_types::datetime::component_of(ms, which)
66}