use relate_core::{temporal, Error, Result, Value};
use crate::overlay::ExecGraph;
pub(super) fn bi_format(_graph: &ExecGraph<'_>, _n: &str, vals: Vec<Value>) -> Result<Value> {
Ok(if vals.iter().any(Value::is_null) {
Value::Null
} else {
let Value::Temporal(t) = &vals[0] else {
return Err(Error::ty("format() requires a temporal value"));
};
match vals.get(1) {
None => Value::String(t.full_seconds_string().into()),
Some(Value::String(pattern)) => {
Value::String(temporal::format_pattern(t, pattern)?.into())
}
_ => return Err(Error::ty("format() pattern must be a string")),
}
})
}
pub(super) fn bi_date(graph: &ExecGraph<'_>, n: &str, vals: Vec<Value>) -> Result<Value> {
graph.construct_temporal(n, &vals)
}
pub(super) fn bi_datetime_fromepoch(
_graph: &ExecGraph<'_>,
_n: &str,
vals: Vec<Value>,
) -> Result<Value> {
Ok({
let secs = vals
.first()
.and_then(|v| v.as_int())
.ok_or_else(|| Error::ty("datetime.fromepoch seconds"))?;
let nanos = vals.get(1).and_then(|v| v.as_int()).unwrap_or(0);
Value::Temporal(temporal::datetime_from_epoch(secs, nanos)?)
})
}
pub(super) fn bi_datetime_fromepochmillis(
_graph: &ExecGraph<'_>,
_n: &str,
vals: Vec<Value>,
) -> Result<Value> {
Ok({
let ms = vals
.first()
.and_then(|v| v.as_int())
.ok_or_else(|| Error::ty("datetime.fromepochmillis"))?;
Value::Temporal(temporal::datetime_from_epoch_millis(ms)?)
})
}
pub(super) fn bi_timestamp(_graph: &ExecGraph<'_>, _n: &str, _vals: Vec<Value>) -> Result<Value> {
Ok(Value::Int(temporal::now_epoch_millis()))
}
pub(super) fn between_call(unit: temporal::BetweenUnit, [a, b]: [Value; 2]) -> Result<Value> {
match (&a, &b) {
(Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
(Value::Temporal(x), Value::Temporal(y)) => Ok(Value::Temporal(
temporal::duration_between_unit(x, y, unit)?,
)),
_ => Err(Error::procedure_call(format!(
"Invalid call signature for Between: Provided input was [{}, {}]",
a.pretty_print(),
b.pretty_print()
))),
}
}
pub(super) fn truncate_call(kind: temporal::ClockKind, vals: Vec<Value>) -> Result<Value> {
let (unit, rest) = vals
.split_first()
.expect("the truncate row requires a unit argument");
let unit = match unit {
Value::String(unit) => &**unit,
Value::Null => return Ok(Value::Null),
_ => return Err(Error::ty("truncate unit must be a string")),
};
let (value, map) = match rest {
[] => return Ok(Value::Temporal(temporal::truncate_now(kind, unit)?)),
[value] => (value, None),
[value, map, ..] => (value, Some(map)),
};
match value {
Value::Temporal(value) => Ok(Value::Temporal(temporal::truncate(kind, unit, value, map)?)),
Value::Null => Ok(Value::Null),
_ => Err(Error::procedure_call(format!(
"Invalid call signature: {}.truncate needs a temporal value",
kind.name()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::Graph;
#[test]
fn truncate_without_a_value_uses_the_pinned_clock() {
let _clock = relate_core::QueryClockGuard::new();
let unit = Value::String("millennium".into());
let implicit = truncate_call(temporal::ClockKind::Date, vec![unit.clone()]).unwrap();
let explicit = truncate_call(
temporal::ClockKind::Date,
vec![unit, temporal::construct_named("date", &[]).unwrap()],
)
.unwrap();
assert_eq!(implicit, explicit);
assert!(!implicit.is_null());
}
#[test]
fn truncate_refuses_a_fourth_argument() {
let _clock = relate_core::QueryClockGuard::new();
let g = Graph::default();
let graph = ExecGraph::read(&g);
let row = crate::row::Row::new();
let params = std::collections::BTreeMap::new();
let err = super::super::function(
&graph,
&row,
¶ms,
"date.truncate",
false,
&[
relate_ir::Expr::String("day".into()),
relate_ir::Expr::String("2024-01-01".into()),
relate_ir::Expr::Null,
relate_ir::Expr::Null,
],
)
.unwrap_err()
.to_string();
assert!(
err.contains("date.truncate() requires one to three arguments"),
"{err}"
);
}
#[test]
fn clock_access_rows_dispatch_through_the_table() {
let _clock = relate_core::QueryClockGuard::new();
let g = Graph::default();
let graph = ExecGraph::read(&g);
let row = crate::row::Row::new();
let params = std::collections::BTreeMap::new();
let call = |name: &str, args: &[relate_ir::Expr]| {
super::super::function(&graph, &row, ¶ms, name, false, args)
};
let out = call("date.realtime", &[relate_ir::Expr::String("+14:00".into())]).unwrap();
assert!(matches!(out, Value::Temporal(_)));
let numeric = call("date.realtime", &[relate_ir::Expr::Int(42)])
.unwrap_err()
.to_string();
assert!(
numeric.contains("Invalid call signature: date.realtime()"),
"{numeric}"
);
let two = call(
"date.transaction",
&[
relate_ir::Expr::String("UTC".into()),
relate_ir::Expr::String("UTC".into()),
],
)
.unwrap_err()
.to_string();
assert!(
two.contains(
"InvalidNumberOfArguments: date.transaction() requires at most one argument"
),
"{two}"
);
}
#[test]
fn timestamp_reads_the_pinned_statement_clock() {
let _clock = relate_core::QueryClockGuard::new();
let g = Graph::default();
let graph = ExecGraph::read(&g);
let result = bi_timestamp(&graph, "timestamp", vec![]).unwrap();
let Value::Int(ms) = result else {
panic!("timestamp() must return an INTEGER, got {result:?}");
};
assert_eq!(ms, temporal::now_epoch_millis());
}
#[test]
fn between_call_non_temporal_operands_fail_the_call() {
let err = between_call(
temporal::BetweenUnit::Months,
[Value::String("abc".into()), Value::String("def".into())],
)
.expect_err("non-temporal operands must fail the call");
assert!(matches!(err, Error::ProcedureCall(_)), "{err}");
assert_eq!(
err.to_string(),
"ProcedureError: Invalid call signature for Between: \
Provided input was [String(\"abc\"), String(\"def\")]"
);
}
}