Skip to main content

uqa_sql/assignment/
domain.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Domain base conversion and inherited constraint evaluation.
8
9use super::AssignmentContext;
10use crate::{ColumnType, RowSchema, SQLError};
11use uqa_core::{
12    memory::{Produced, ProductionControl, ProductionVec},
13    Value,
14};
15
16mod diagnostics;
17
18#[cfg(test)]
19mod tests;
20
21pub fn cast_domain_value(
22    context: &dyn AssignmentContext,
23    value: &Value,
24    source: Option<&str>,
25    ty: &ColumnType,
26) -> Result<Option<Value>, SQLError> {
27    convert_domain_value(context, value, source, ty, false)
28}
29
30/// Domain input retains the caller's resource owners through base conversion, tuple admission and every constraint callback.
31pub fn cast_domain_value_with_control(
32    context: &dyn AssignmentContext,
33    value: &Value,
34    source: Option<&str>,
35    ty: &ColumnType,
36    control: &ProductionControl<'_>,
37) -> Result<Option<Produced<Value>>, SQLError> {
38    convert_domain_value_with_control(context, value, source, ty, false, control)
39}
40
41pub fn assign_domain_value_with_control(
42    context: &dyn AssignmentContext,
43    value: &Value,
44    source: Option<&str>,
45    ty: &ColumnType,
46    control: &ProductionControl<'_>,
47) -> Result<Option<Produced<Value>>, SQLError> {
48    convert_domain_value_with_control(context, value, source, ty, true, control)
49}
50
51pub fn assign_domain_value(
52    context: &dyn AssignmentContext,
53    value: &Value,
54    ty: &ColumnType,
55) -> Result<Option<Value>, SQLError> {
56    assign_domain_value_from(context, value, None, ty)
57}
58
59pub(super) fn assign_domain_value_from(
60    context: &dyn AssignmentContext,
61    value: &Value,
62    source: Option<&str>,
63    ty: &ColumnType,
64) -> Result<Option<Value>, SQLError> {
65    convert_domain_value(context, value, source, ty, true)
66}
67
68fn convert_domain_value(
69    context: &dyn AssignmentContext,
70    value: &Value,
71    source: Option<&str>,
72    ty: &ColumnType,
73    assignment: bool,
74) -> Result<Option<Value>, SQLError> {
75    convert_domain_value_with_control(
76        context,
77        value,
78        source,
79        ty,
80        assignment,
81        &ProductionControl::uncontrolled(),
82    )?
83    .map(|value| {
84        value
85            .into_uncontrolled()
86            .map_err(|_| SQLError::Internal("ordinary domain value retention".into()))
87    })
88    .transpose()
89}
90
91fn convert_domain_value_with_control(
92    context: &dyn AssignmentContext,
93    value: &Value,
94    source: Option<&str>,
95    ty: &ColumnType,
96    assignment: bool,
97    control: &ProductionControl<'_>,
98) -> Result<Option<Produced<Value>>, SQLError> {
99    control.check()?;
100    let ColumnType::Domain { oid, .. } = ty else {
101        return Ok(None);
102    };
103    let Some(domain) = context.domain_by_oid_with_control(*oid, control)? else {
104        return Ok(None);
105    };
106    let source_type = source
107        .map(|name| context.resolve_type_name_with_control(name, control))
108        .transpose();
109    let source_type = match source_type {
110        Ok(ty) => ty.flatten(),
111        Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => return Err(error),
112        Err(_) => None,
113    };
114    if source_type.as_deref() == Some(ty) {
115        return Ok(Some(
116            super::conversion::normalize_legacy_vector_carrier_with_control(value, ty, control)?
117                .map_or_else(|| control.copy_value(value), Ok)?,
118        ));
119    }
120    let mut base = domain.definition.base.clone_with_control(control)?;
121    let mut chain = ProductionVec::new(*control);
122    chain.push_produced(domain)?;
123    while let ColumnType::Domain {
124        oid,
125        base: underlying,
126        ..
127    } = &*base
128    {
129        control.check()?;
130        if let Some(parent) = context.domain_by_oid_with_control(*oid, control)? {
131            base = parent.definition.base.clone_with_control(control)?;
132            chain.push_produced(parent)?;
133        } else {
134            base = underlying.clone_with_control(control)?;
135        }
136    }
137    let value = if assignment {
138        let source = source
139            .map(|source| context.resolve_type_name_with_control(source, control))
140            .transpose()?
141            .flatten();
142        super::conversion::coerce_assignment_value_with_control(
143            context,
144            control.copy_value(value)?,
145            &base,
146            source.as_deref(),
147            control,
148        )?
149    } else {
150        crate::expr::cast_value_with_type_resolution_with_control(
151            value,
152            source,
153            &base.catalog_name_with_control(control)?,
154            Some(context),
155            control,
156        )?
157    };
158    check_value(context, value, &chain, control).map(Some)
159}
160
161fn check_value(
162    context: &dyn AssignmentContext,
163    value: Produced<Value>,
164    chain: &[crate::catalog::domain::StoredDomain],
165    control: &ProductionControl<'_>,
166) -> Result<Produced<Value>, SQLError> {
167    if matches!(*value, Value::Null)
168        && chain
169            .iter()
170            .any(|domain| domain.definition.not_null.is_some())
171    {
172        return Err(diagnostics::violation(
173            context,
174            chain[0].oid,
175            None,
176            control,
177        )?);
178    }
179    // Checks may change the catalog. Retain the admitted tuple before invoking them.
180    let value = crate::expr::composites::retain_value_with_control(
181        value,
182        context.composite_types(),
183        control,
184    )?;
185    let row = DomainValue(&value);
186    let schema = RowSchema::with_column_metadata_with_control(
187        None,
188        [("value", Some(&chain[0].definition.base), None)],
189        control,
190    )?;
191    for check in chain
192        .iter()
193        .rev()
194        .flat_map(|domain| &domain.definition.checks)
195    {
196        control.check()?;
197        let result = context.evaluate_domain_check_with_control(
198            &check.expression,
199            &row,
200            &schema,
201            control,
202        )?;
203        control.check()?;
204        if *result == Value::Bool(false) {
205            return Err(diagnostics::violation(
206                context,
207                chain[0].oid,
208                Some(check.name.as_deref().expect("bound domain constraint")),
209                control,
210            )?);
211        }
212    }
213    Ok(value)
214}
215
216struct DomainValue<'a>(&'a Value);
217
218impl crate::expr::RowLookup for DomainValue<'_> {
219    fn column(&self, name: &str) -> Option<&Value> {
220        (name == "value").then_some(self.0)
221    }
222
223    fn qualified_column(&self, _: &str, _: &str) -> Option<&Value> {
224        None
225    }
226
227    fn positional_column(&self, index: usize) -> Option<&Value> {
228        (index == 0).then_some(self.0)
229    }
230}
231
232pub fn domain_error(sqlstate: &str, message: impl Into<String>) -> SQLError {
233    SQLError::Routine {
234        sqlstate: sqlstate.into(),
235        message: message.into(),
236    }
237}