Skip to main content

datafusion_common/
param_value.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
5use crate::error::{_plan_datafusion_err, _plan_err};
6use crate::metadata::{ScalarAndMetadata, check_metadata_with_storage_equal};
7use crate::{Result, ScalarValue};
8use arrow::datatypes::{DataType, Field, FieldRef};
9use std::collections::HashMap;
10
11/// The parameter value corresponding to the placeholder
12#[derive(Debug, Clone)]
13pub enum ParamValues {
14    /// For positional query parameters, like `SELECT * FROM test WHERE a > $1 AND b = $2`
15    List(Vec<ScalarAndMetadata>),
16    /// For named query parameters, like `SELECT * FROM test WHERE a > $foo AND b = $goo`
17    Map(HashMap<String, ScalarAndMetadata>),
18}
19
20impl ParamValues {
21    /// Verify parameter list length and DataType
22    ///
23    /// Use [`ParamValues::verify_fields`] to ensure field metadata is considered when
24    /// computing type equality.
25    #[deprecated(since = "51.0.0", note = "Use verify_fields instead")]
26    pub fn verify(&self, expect: &[DataType]) -> Result<()> {
27        // make dummy Fields
28        let expect = expect
29            .iter()
30            .map(|dt| Field::new("", dt.clone(), true).into())
31            .collect::<Vec<_>>();
32        self.verify_fields(&expect)
33    }
34
35    /// Verify parameter list length and type
36    pub fn verify_fields(&self, expect: &[FieldRef]) -> Result<()> {
37        match self {
38            ParamValues::List(list) => {
39                // Verify if the number of params matches the number of values
40                if expect.len() != list.len() {
41                    return _plan_err!(
42                        "Expected {} parameters, got {}",
43                        expect.len(),
44                        list.len()
45                    );
46                }
47
48                // Verify if the types of the params matches the types of the values
49                let iter = expect.iter().zip(list.iter());
50                for (i, (param_type, lit)) in iter.enumerate() {
51                    check_metadata_with_storage_equal(
52                        (
53                            &lit.value.data_type(),
54                            lit.metadata.as_ref().map(|m| m.to_metadata()).as_ref(),
55                        ),
56                        (param_type.data_type(), Some(param_type.metadata())),
57                        "parameter",
58                        &format!(" at index {i}"),
59                    )?;
60                }
61            }
62            ParamValues::Map(_) => {
63                // If it is a named query, variables can be reused,
64                // but the lengths are not necessarily equal
65            }
66        }
67        Ok(())
68    }
69
70    pub fn get_placeholders_with_values(&self, id: &str) -> Result<ScalarAndMetadata> {
71        match self {
72            ParamValues::List(list) => {
73                if id.is_empty() {
74                    return _plan_err!("Empty placeholder id");
75                }
76                // convert id (in format $1, $2, ..) to idx (0, 1, ..)
77                let idx = id[1..]
78                    .parse::<usize>()
79                    .map_err(|e| {
80                        _plan_datafusion_err!("Failed to parse placeholder id: {e}")
81                    })?
82                    .checked_sub(1);
83                // value at the idx-th position in param_values should be the value for the placeholder
84                let value = idx.and_then(|idx| list.get(idx)).ok_or_else(|| {
85                    _plan_datafusion_err!("No value found for placeholder with id {id}")
86                })?;
87                Ok(value.clone())
88            }
89            ParamValues::Map(map) => {
90                // convert name (in format $a, $b, ..) to mapped values (a, b, ..)
91                let name = &id[1..];
92                // value at the name position in param_values should be the value for the placeholder
93                let value = map.get(name).ok_or_else(|| {
94                    _plan_datafusion_err!("No value found for placeholder with name {id}")
95                })?;
96                Ok(value.clone())
97            }
98        }
99    }
100}
101
102impl From<Vec<ScalarValue>> for ParamValues {
103    fn from(value: Vec<ScalarValue>) -> Self {
104        Self::List(value.into_iter().map(ScalarAndMetadata::from).collect())
105    }
106}
107
108impl<K> From<Vec<(K, ScalarValue)>> for ParamValues
109where
110    K: Into<String>,
111{
112    fn from(value: Vec<(K, ScalarValue)>) -> Self {
113        let value: HashMap<String, ScalarAndMetadata> = value
114            .into_iter()
115            .map(|(k, v)| (k.into(), ScalarAndMetadata::from(v)))
116            .collect();
117        Self::Map(value)
118    }
119}
120
121impl<K> From<HashMap<K, ScalarValue>> for ParamValues
122where
123    K: Into<String>,
124{
125    fn from(value: HashMap<K, ScalarValue>) -> Self {
126        let value: HashMap<String, ScalarAndMetadata> = value
127            .into_iter()
128            .map(|(k, v)| (k.into(), ScalarAndMetadata::from(v)))
129            .collect();
130        Self::Map(value)
131    }
132}