common_function/
helper.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use api::v1::meta::ResolveStrategy;
16use common_query::error::{
17    InvalidFuncArgsSnafu, InvalidInputTypeSnafu, Result, UnsupportedInputDataTypeSnafu,
18};
19use common_query::prelude::{Signature, TypeSignature, Volatility};
20use datatypes::prelude::ConcreteDataType;
21use datatypes::types::cast::cast;
22use datatypes::value::ValueRef;
23use snafu::{OptionExt, ResultExt};
24
25/// Create a function signature with oneof signatures of interleaving two arguments.
26pub fn one_of_sigs2(args1: Vec<ConcreteDataType>, args2: Vec<ConcreteDataType>) -> Signature {
27    let mut sigs = Vec::with_capacity(args1.len() * args2.len());
28
29    for arg1 in &args1 {
30        for arg2 in &args2 {
31            sigs.push(TypeSignature::Exact(vec![arg1.clone(), arg2.clone()]));
32        }
33    }
34
35    Signature::one_of(sigs, Volatility::Immutable)
36}
37
38/// Cast a [`ValueRef`] to u64, returns `None` if fails
39pub fn cast_u64(value: &ValueRef) -> Result<Option<u64>> {
40    cast((*value).into(), &ConcreteDataType::uint64_datatype())
41        .context(InvalidInputTypeSnafu {
42            err_msg: format!(
43                "Failed to cast input into uint64, actual type: {:#?}",
44                value.data_type(),
45            ),
46        })
47        .map(|v| v.as_u64())
48}
49
50/// Cast a [`ValueRef`] to u32, returns `None` if fails
51pub fn cast_u32(value: &ValueRef) -> Result<Option<u32>> {
52    cast((*value).into(), &ConcreteDataType::uint32_datatype())
53        .context(InvalidInputTypeSnafu {
54            err_msg: format!(
55                "Failed to cast input into uint32, actual type: {:#?}",
56                value.data_type(),
57            ),
58        })
59        .map(|v| v.as_u64().map(|v| v as u32))
60}
61
62/// Parse a resolve strategy from a string.
63pub fn parse_resolve_strategy(strategy: &str) -> Result<ResolveStrategy> {
64    ResolveStrategy::from_str_name(strategy).context(InvalidFuncArgsSnafu {
65        err_msg: format!("Invalid resolve strategy: {}", strategy),
66    })
67}
68
69/// Default parallelism for reconcile operations.
70pub fn default_parallelism() -> u32 {
71    64
72}
73
74/// Default resolve strategy for reconcile operations.
75pub fn default_resolve_strategy() -> ResolveStrategy {
76    ResolveStrategy::UseLatest
77}
78
79/// Get the string value from the params.
80///
81/// # Errors
82/// Returns an error if the input type is not a string.
83pub fn get_string_from_params<'a>(
84    params: &'a [ValueRef<'a>],
85    index: usize,
86    fn_name: &'a str,
87) -> Result<&'a str> {
88    let ValueRef::String(s) = &params[index] else {
89        return UnsupportedInputDataTypeSnafu {
90            function: fn_name,
91            datatypes: params.iter().map(|v| v.data_type()).collect::<Vec<_>>(),
92        }
93        .fail();
94    };
95    Ok(s)
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn test_parse_resolve_strategy() {
104        assert_eq!(
105            parse_resolve_strategy("UseLatest").unwrap(),
106            ResolveStrategy::UseLatest
107        );
108    }
109}