hamelin_lib 0.24.1

Core library for Hamelin query language
Documentation
use std::sync::Arc;

use chrono::{DateTime, SecondsFormat, Utc};

use crate::tree::ast::expression::{Expression, NullLiteral};
use crate::tree::ast::ops::BinaryOp;
use crate::tree::builder::{call, null, BinaryOperatorBuilder, ExpressionBuilder};

/// A time range with optional start and end bounds.
///
/// Used for resolving dynamic time ranges in queries (e.g., `[-1h..]`).
/// Converts to an AST [`Expression`] via [`From`], producing a range expression
/// like `ts('2024-01-01T00:00:00.000000Z')..ts('2024-01-02T00:00:00.000000Z')`.
#[derive(Debug, Clone, Default)]
pub struct TimeRange {
    pub start: Option<DateTime<Utc>>,
    pub end: Option<DateTime<Utc>>,
    /// Whether the end bound is inclusive (`..=`). Defaults to exclusive (`..`).
    pub end_inclusive: bool,
}

impl From<TimeRange> for Expression {
    fn from(range: TimeRange) -> Self {
        let ts_call =
            |dt: DateTime<Utc>| call("ts").arg(dt.to_rfc3339_opts(SecondsFormat::Micros, true));
        let range_op = if range.end_inclusive {
            BinaryOp::RangeInclusive
        } else {
            BinaryOp::Range
        };
        match (range.start, range.end) {
            (Some(start), Some(end)) => {
                BinaryOperatorBuilder::new(range_op, ts_call(start), ts_call(end)).build()
            }
            (Some(start), None) => {
                BinaryOperatorBuilder::new(range_op, ts_call(start), null()).build()
            }
            (None, Some(end)) => BinaryOperatorBuilder::new(range_op, null(), ts_call(end)).build(),
            (None, None) => Expression::from_kind(NullLiteral),
        }
    }
}

impl From<TimeRange> for Arc<Expression> {
    fn from(range: TimeRange) -> Self {
        Arc::new(Expression::from(range))
    }
}

#[cfg(test)]
mod tests {
    use chrono::{TimeZone, Utc};
    use pretty_assertions::assert_eq;
    use rstest::rstest;

    use super::*;
    use crate::tree::ast::ParseWithErrors;

    fn timestamp(hour: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2024, 1, 1, hour, 0, 0)
            .single()
            .expect("valid test timestamp")
    }

    fn assert_expression(range: TimeRange, expected: &str) {
        let actual = Expression::from(range);
        let expected = Expression::parse_result(expected).expect("valid expected expression");
        assert_eq!(actual, expected);
    }

    #[test]
    fn exclusive_range_uses_exclusive_operator_by_default() {
        assert_expression(
            TimeRange {
                start: Some(timestamp(1)),
                end: Some(timestamp(2)),
                ..Default::default()
            },
            "ts('2024-01-01T01:00:00.000000Z')..ts('2024-01-01T02:00:00.000000Z')",
        );
    }

    #[test]
    fn inclusive_range_uses_inclusive_operator() {
        assert_expression(
            TimeRange {
                start: Some(timestamp(1)),
                end: Some(timestamp(2)),
                end_inclusive: true,
            },
            "ts('2024-01-01T01:00:00.000000Z')..=ts('2024-01-01T02:00:00.000000Z')",
        );
    }

    #[test]
    fn zero_width_inclusive_range_is_preserved() {
        assert_expression(
            TimeRange {
                start: Some(timestamp(1)),
                end: Some(timestamp(1)),
                end_inclusive: true,
            },
            "ts('2024-01-01T01:00:00.000000Z')..=ts('2024-01-01T01:00:00.000000Z')",
        );
    }

    #[rstest]
    #[case::exclusive(
        Some("2024-01-01T00:00:00.123456Z"),
        Some("2024-01-01T00:00:00.654321Z"),
        false,
        "ts('2024-01-01T00:00:00.123456Z')..ts('2024-01-01T00:00:00.654321Z')"
    )]
    #[case::inclusive(
        Some("2024-01-01T00:00:00.123456Z"),
        Some("2024-01-01T00:00:00.654321Z"),
        true,
        "ts('2024-01-01T00:00:00.123456Z')..=ts('2024-01-01T00:00:00.654321Z')"
    )]
    #[case::point(
        Some("2024-01-01T00:00:00.123456Z"),
        Some("2024-01-01T00:00:00.123456Z"),
        true,
        "ts('2024-01-01T00:00:00.123456Z')..=ts('2024-01-01T00:00:00.123456Z')"
    )]
    #[case::start_only(
        Some("2024-01-01T00:00:00.123456Z"),
        None,
        false,
        "ts('2024-01-01T00:00:00.123456Z')..null"
    )]
    #[case::end_only(
        None,
        Some("2024-01-01T00:00:00.654321Z"),
        true,
        "null..=ts('2024-01-01T00:00:00.654321Z')"
    )]
    #[case::before_epoch(
        Some("1969-12-31T23:59:59.123456Z"),
        Some("1969-12-31T23:59:59.999999Z"),
        false,
        "ts('1969-12-31T23:59:59.123456Z')..ts('1969-12-31T23:59:59.999999Z')"
    )]
    #[case::unbounded(None, None, false, "null")]
    fn timestamp_literals_preserve_microseconds(
        #[case] start: Option<&str>,
        #[case] end: Option<&str>,
        #[case] end_inclusive: bool,
        #[case] expected: &str,
    ) {
        assert_expression(
            TimeRange {
                start: start.map(|ts| ts.parse().unwrap()),
                end: end.map(|ts| ts.parse().unwrap()),
                end_inclusive,
            },
            expected,
        );
    }
}