uqa_sql/params/
binding.rs1use crate::{ColumnType, FunctionTypeResolver, RowSchema, SQLError, SQLParam, ScalarExpr};
10use uqa_core::{
11 memory::{Produced, ProductionControl},
12 Value,
13};
14
15#[cfg(test)]
16mod tests;
17
18pub fn bind_parameter_types(
20 parameters: &[SQLParam],
21 types: &dyn FunctionTypeResolver,
22) -> Result<Vec<Option<ColumnType>>, SQLError> {
23 let control = ProductionControl::uncontrolled();
24 parameters
25 .iter()
26 .map(|parameter| {
27 bind_parameter_type_with_control(parameter, types, &control).map(|ty| {
28 ty.map(|ty| {
29 ty.into_uncontrolled()
30 .expect("ordinary parameter binding has no reservation")
31 })
32 })
33 })
34 .collect()
35}
36
37pub fn bind_declared_parameter_types(
39 declarations: &[Option<ColumnType>],
40 types: &dyn FunctionTypeResolver,
41) -> Result<Vec<Option<ColumnType>>, SQLError> {
42 let control = ProductionControl::uncontrolled();
43 declarations
44 .iter()
45 .map(|ty| {
46 ty.as_ref()
47 .map(|ty| {
48 declared_parameter_type(ty, types, &control).map(|ty| {
49 ty.into_uncontrolled()
50 .expect("ordinary declaration binding has no reservation")
51 })
52 })
53 .transpose()
54 })
55 .collect()
56}
57
58pub fn bind_parameter_type_with_control(
60 parameter: &SQLParam,
61 types: &dyn FunctionTypeResolver,
62 control: &ProductionControl<'_>,
63) -> Result<Option<Produced<ColumnType>>, SQLError> {
64 control.check()?;
65 match parameter {
66 SQLParam::Scalar(Value::Str(_) | Value::Null) => Ok(None),
67 SQLParam::TypedScalar { ty, .. } => declared_parameter_type(ty, types, control).map(Some),
68 _ => crate::type_resolution::scalar_type_with_control(
69 &ScalarExpr::Param(1),
70 &RowSchema::empty_with_control(control)?,
71 std::slice::from_ref(parameter),
72 control,
73 ),
74 }
75}
76
77fn declared_parameter_type(
78 ty: &ColumnType,
79 types: &dyn FunctionTypeResolver,
80 control: &ProductionControl<'_>,
81) -> Result<Produced<ColumnType>, SQLError> {
82 let mut leaf = ty;
83 while let ColumnType::Array(element) = leaf {
84 leaf = element;
85 }
86 if !matches!(
87 leaf,
88 ColumnType::Enum(_)
89 | ColumnType::Composite(_)
90 | ColumnType::Domain { .. }
91 | ColumnType::DeclaredRange(_)
92 | ColumnType::DeclaredMultirange(_)
93 ) {
94 return ty.clone_with_control(control).map_err(Into::into);
95 }
96 let name = ty.catalog_name_with_control(control)?;
97 match types.resolve_type_name_with_control(&name, control) {
98 Ok(Some(current)) => Ok(current),
99 Ok(None) => Err(missing_parameter_type(ty)),
100 Err(error) if error.sqlstate() == Some("42704") => Err(missing_parameter_type(ty)),
101 Err(error) => Err(error),
102 }
103}
104
105fn missing_parameter_type(ty: &ColumnType) -> SQLError {
106 SQLError::Routine {
107 sqlstate: "XX000".into(),
108 message: format!(
109 "cache lookup failed for type {}",
110 crate::catalog::type_metadata::pg_type_oid(ty),
111 ),
112 }
113}