Skip to main content

datafusion_expr/
var_provider.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Variable provider
6
7use arrow::datatypes::DataType;
8use datafusion_common::{Result, ScalarValue};
9
10/// Variable type, system/user defined
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12pub enum VarType {
13    /// System variable, like @@version
14    System,
15    /// User defined variable, like @name
16    UserDefined,
17}
18
19/// A var provider for `@variable` and `@@variable` runtime values.
20pub trait VarProvider: std::fmt::Debug {
21    /// Get variable value
22    fn get_value(&self, var_names: Vec<String>) -> Result<ScalarValue>;
23
24    /// Return the type of the given variable
25    fn get_type(&self, var_names: &[String]) -> Option<DataType>;
26}
27
28/// Returns true if the specified string is a "system" variable such as
29/// `@@version`
30///
31/// See [`SessionContext::register_variable`] for more details
32///
33/// [`SessionContext::register_variable`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html#method.register_variable
34pub fn is_system_variables(variable_names: &[String]) -> bool {
35    !variable_names.is_empty() && variable_names[0].get(0..2) == Some("@@")
36}
37
38#[cfg(test)]
39mod test {
40    use super::*;
41
42    #[test]
43    fn test_is_system_variables() {
44        assert!(!is_system_variables(&["N".into(), "\"\"".into()]));
45        assert!(is_system_variables(&["@@D".into(), "F".into(), "J".into()]));
46        assert!(!is_system_variables(&[
47            "J".into(),
48            "@@F".into(),
49            "K".into()
50        ]));
51        assert!(!is_system_variables(&[]));
52        assert!(is_system_variables(&[
53            "@@longvariablenamethatIdontknowhwyanyonewoulduse".into()
54        ]));
55        assert!(!is_system_variables(&["@F".into()]));
56    }
57}