vrl/stdlib/
timestamp.rs

1use crate::compiler::prelude::*;
2
3fn timestamp(value: Value) -> Resolved {
4    match value {
5        v @ Value::Timestamp(_) => Ok(v),
6        v => Err(format!("expected timestamp, got {}", v.kind()).into()),
7    }
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct Timestamp;
12
13impl Function for Timestamp {
14    fn identifier(&self) -> &'static str {
15        "timestamp"
16    }
17
18    fn usage(&self) -> &'static str {
19        "Returns `value` if it is a timestamp, otherwise returns an error. This enables the type checker to guarantee that the returned value is a timestamp and can be used in any function that expects a timestamp."
20    }
21
22    fn category(&self) -> &'static str {
23        Category::Type.as_ref()
24    }
25
26    fn internal_failure_reasons(&self) -> &'static [&'static str] {
27        &["`value` is not a timestamp."]
28    }
29
30    fn return_kind(&self) -> u16 {
31        kind::TIMESTAMP
32    }
33
34    fn return_rules(&self) -> &'static [&'static str] {
35        &[
36            "Returns the `value` if it's a timestamp.",
37            "Raises an error if not a timestamp.",
38        ]
39    }
40
41    fn parameters(&self) -> &'static [Parameter] {
42        const PARAMETERS: &[Parameter] = &[Parameter::required(
43            "value",
44            kind::ANY,
45            "The value to check if it is a timestamp.",
46        )];
47        PARAMETERS
48    }
49
50    fn examples(&self) -> &'static [Example] {
51        &[
52            example! {
53                title: "Declare a timestamp type",
54                source: "timestamp(t'2020-10-10T16:00:00Z')",
55                result: Ok("t'2020-10-10T16:00:00Z'"),
56            },
57            example! {
58                title: "Invalid type",
59                source: "timestamp!(true)",
60                result: Err(
61                    r#"function call error for "timestamp" at (0:16): expected timestamp, got boolean"#,
62                ),
63            },
64        ]
65    }
66
67    fn compile(
68        &self,
69        _state: &state::TypeState,
70        _ctx: &mut FunctionCompileContext,
71        arguments: ArgumentList,
72    ) -> Compiled {
73        let value = arguments.required("value");
74
75        Ok(TimestampFn { value }.as_expr())
76    }
77}
78
79#[derive(Debug, Clone)]
80struct TimestampFn {
81    value: Box<dyn Expression>,
82}
83
84impl FunctionExpression for TimestampFn {
85    fn resolve(&self, ctx: &mut Context) -> Resolved {
86        let value = self.value.resolve(ctx)?;
87        timestamp(value)
88    }
89
90    fn type_def(&self, state: &state::TypeState) -> TypeDef {
91        let non_timestamp = !self.value.type_def(state).is_timestamp();
92
93        TypeDef::timestamp().maybe_fallible(non_timestamp)
94    }
95}