datafusion_common/
param_value.rs1use 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#[derive(Debug, Clone)]
13pub enum ParamValues {
14 List(Vec<ScalarAndMetadata>),
16 Map(HashMap<String, ScalarAndMetadata>),
18}
19
20impl ParamValues {
21 #[deprecated(since = "51.0.0", note = "Use verify_fields instead")]
26 pub fn verify(&self, expect: &[DataType]) -> Result<()> {
27 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 pub fn verify_fields(&self, expect: &[FieldRef]) -> Result<()> {
37 match self {
38 ParamValues::List(list) => {
39 if expect.len() != list.len() {
41 return _plan_err!(
42 "Expected {} parameters, got {}",
43 expect.len(),
44 list.len()
45 );
46 }
47
48 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 }
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 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 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 let name = &id[1..];
92 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}