1use super::AssignmentContext;
10use crate::{ColumnType, RowSchema, SQLError};
11use uqa_core::{
12 memory::{Produced, ProductionControl, ProductionVec},
13 Value,
14};
15
16#[cfg(test)]
17mod tests;
18
19pub fn cast_domain_value(
20 context: &dyn AssignmentContext,
21 value: &Value,
22 source: Option<&str>,
23 ty: &ColumnType,
24) -> Result<Option<Value>, SQLError> {
25 convert_domain_value(context, value, source, ty, false)
26}
27
28pub fn cast_domain_value_with_control(
30 context: &dyn AssignmentContext,
31 value: &Value,
32 source: Option<&str>,
33 ty: &ColumnType,
34 control: &ProductionControl<'_>,
35) -> Result<Option<Produced<Value>>, SQLError> {
36 convert_domain_value_with_control(context, value, source, ty, false, control)
37}
38
39pub fn assign_domain_value(
40 context: &dyn AssignmentContext,
41 value: &Value,
42 ty: &ColumnType,
43) -> Result<Option<Value>, SQLError> {
44 assign_domain_value_from(context, value, None, ty)
45}
46
47pub(super) fn assign_domain_value_from(
48 context: &dyn AssignmentContext,
49 value: &Value,
50 source: Option<&str>,
51 ty: &ColumnType,
52) -> Result<Option<Value>, SQLError> {
53 convert_domain_value(context, value, source, ty, true)
54}
55
56fn convert_domain_value(
57 context: &dyn AssignmentContext,
58 value: &Value,
59 source: Option<&str>,
60 ty: &ColumnType,
61 assignment: bool,
62) -> Result<Option<Value>, SQLError> {
63 convert_domain_value_with_control(
64 context,
65 value,
66 source,
67 ty,
68 assignment,
69 &ProductionControl::uncontrolled(),
70 )?
71 .map(|value| {
72 value
73 .into_uncontrolled()
74 .map_err(|_| SQLError::Internal("ordinary domain value retention".into()))
75 })
76 .transpose()
77}
78
79fn convert_domain_value_with_control(
80 context: &dyn AssignmentContext,
81 value: &Value,
82 source: Option<&str>,
83 ty: &ColumnType,
84 assignment: bool,
85 control: &ProductionControl<'_>,
86) -> Result<Option<Produced<Value>>, SQLError> {
87 control.check()?;
88 let ColumnType::Domain { oid, .. } = ty else {
89 return Ok(None);
90 };
91 let Some(domain) = context.domain_by_oid(*oid) else {
92 return Ok(None);
93 };
94 let domain = domain.retain_external_with_control(control)?;
95 if source
96 .and_then(|name| context.resolve_type_name(name).ok().flatten())
97 .as_ref()
98 == Some(ty)
99 {
100 return Ok(Some(
101 super::conversion::normalize_legacy_vector_carrier_with_control(value, ty, control)?
102 .map_or_else(|| control.copy_value(value), Ok)?,
103 ));
104 }
105 let mut base = domain.definition.base.clone_with_control(control)?;
106 let mut chain = ProductionVec::new(*control);
107 chain.push_produced(domain)?;
108 while let ColumnType::Domain {
109 oid,
110 base: underlying,
111 ..
112 } = &*base
113 {
114 control.check()?;
115 if let Some(parent) = context.domain_by_oid(*oid) {
116 let parent = parent.retain_external_with_control(control)?;
117 base = parent.definition.base.clone_with_control(control)?;
118 chain.push_produced(parent)?;
119 } else {
120 base = underlying.clone_with_control(control)?;
121 }
122 }
123 let value = if assignment {
124 let source = source
125 .map(|source| {
126 context
127 .resolve_type_name(source)
128 .map_err(SQLError::Internal)
129 })
130 .transpose()?
131 .flatten();
132 control.retain_external_value(super::conversion::coerce_assignment_value(
133 context,
134 value.clone(),
135 &base,
136 source.as_ref(),
137 )?)?
138 } else {
139 crate::expr::cast_value_with_type_resolution_with_control(
140 value,
141 source,
142 &base.catalog_name_with_control(control)?,
143 Some(context),
144 control,
145 )?
146 };
147 check_value(context, value, &chain, control).map(Some)
148}
149
150fn check_value(
151 context: &dyn AssignmentContext,
152 value: Produced<Value>,
153 chain: &[crate::catalog::domain::StoredDomain],
154 control: &ProductionControl<'_>,
155) -> Result<Produced<Value>, SQLError> {
156 if matches!(*value, Value::Null)
157 && chain
158 .iter()
159 .any(|domain| domain.definition.not_null.is_some())
160 {
161 return Err(domain_error(
162 "23502",
163 format!(
164 "domain {} does not allow null values",
165 domain_display_name(context, chain[0].oid)?
166 ),
167 ));
168 }
169 let value = crate::expr::composites::retain_value_with_control(
171 value,
172 context.composite_types(),
173 control,
174 )?;
175 let row = DomainValue(&value);
176 let (check_type, _type_memory) = chain[0]
177 .definition
178 .base
179 .clone_with_control(control)?
180 .into_parts();
181 let schema = RowSchema::with_types(vec!["value".into()], vec![Some(check_type)]);
182 for check in chain
183 .iter()
184 .rev()
185 .flat_map(|domain| &domain.definition.checks)
186 {
187 control.check()?;
188 let result = context.evaluate_domain_check(&check.expression, &row, &schema)?;
189 control.check()?;
190 if result == Value::Bool(false) {
191 return Err(domain_error(
192 "23514",
193 format!(
194 "value for domain {} violates check constraint \"{}\"",
195 domain_display_name(context, chain[0].oid)?,
196 check.name.as_deref().expect("bound domain constraint")
197 ),
198 ));
199 }
200 }
201 Ok(value)
202}
203
204struct DomainValue<'a>(&'a Value);
205
206impl crate::expr::RowLookup for DomainValue<'_> {
207 fn column(&self, name: &str) -> Option<&Value> {
208 (name == "value").then_some(self.0)
209 }
210
211 fn qualified_column(&self, _: &str, _: &str) -> Option<&Value> {
212 None
213 }
214
215 fn positional_column(&self, index: usize) -> Option<&Value> {
216 (index == 0).then_some(self.0)
217 }
218}
219
220fn domain_display_name(context: &dyn AssignmentContext, oid: u32) -> Result<String, SQLError> {
221 context
222 .resolve_regtype_output(&ColumnType::Regtype, i64::from(oid))
223 .map_err(SQLError::Internal)?
224 .ok_or_else(|| SQLError::Internal("domain type has no catalog display name".into()))
225}
226
227pub fn domain_error(sqlstate: &str, message: impl Into<String>) -> SQLError {
228 SQLError::Routine {
229 sqlstate: sqlstate.into(),
230 message: message.into(),
231 }
232}