Skip to main content

uqa_sql/assignment/
columns.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Declared mutation columns, generated-column assignment rules, and table-value coercion.
8use super::{conversion::coerce_assignment_value, AssignmentContext};
9use crate::{
10    ast::{ColumnDef, ColumnType, Expr, GeneratedColumnKind},
11    SQLError,
12};
13use uqa_core::{memory::ProductionControl, Value};
14
15pub(crate) mod production;
16pub use production::{
17    declared_column_names_with_control, validate_mutation_columns_with_control,
18    validate_mutation_targets_with_control,
19};
20pub type ColumnCatalogError = Box<dyn std::error::Error>;
21
22/// What a written value needs to know of its column.
23#[derive(Debug, Clone, PartialEq)]
24pub struct ColumnShape {
25    pub ty: ColumnType,
26    pub generated: Option<GeneratedColumnKind>,
27    /// The sequence of an identity column, which `DEFAULT` draws its value from.
28    pub identity_sequence: Option<String>,
29}
30
31/// The sequence an identity column draws its values from: `None` for any other column.
32fn identity_sequence(definition: &ColumnDef) -> Option<String> {
33    definition
34        .auto_increment
35        .as_ref()
36        .filter(|provenance| provenance.is_identity())
37        .and_then(|provenance| provenance.sequence.clone())
38}
39
40pub trait AssignmentColumnCatalog {
41    fn try_describe_table(&self, table: &str)
42        -> Result<Option<Vec<ColumnDef>>, ColumnCatalogError>;
43    fn columns_declared(&self, table: &str) -> Result<bool, ColumnCatalogError>;
44    /// Lend one declaration generation after observing the same default/generated sequence dependencies as a full description. Call the reader exactly once for a found table and do no catalog work afterwards. Consumers inspect names, types and flags; expression consumers still request resolved expressions.
45    fn with_column_metadata_with_control(
46        &self,
47        table: &str,
48        control: &ProductionControl<'_>,
49        read: &mut dyn FnMut(&[ColumnDef]) -> Result<(), SQLError>,
50    ) -> Result<bool, SQLError> {
51        control.check()?;
52        let Some(columns) = self
53            .try_describe_table(table)
54            .map_err(|error| catalog_error(error, control))?
55        else {
56            return Ok(false);
57        };
58        read(&columns)?;
59        Ok(true)
60    }
61    fn columns_declared_with_control(
62        &self,
63        table: &str,
64        control: &ProductionControl<'_>,
65    ) -> Result<bool, SQLError> {
66        control.check()?;
67        self.columns_declared(table)
68            .map_err(|error| catalog_error(error, control))
69    }
70    fn try_column_insert_default_expr(
71        &self,
72        table: &str,
73        column: &str,
74    ) -> Result<Option<Expr>, ColumnCatalogError>;
75    /// The sequence an identity DEFAULT draws from. An identity declaration with no sequence owned by it reports `PostgreSQL`'s error.
76    fn try_identity_column_sequence(
77        &self,
78        table: &str,
79        column: &str,
80    ) -> Result<Option<String>, SQLError> {
81        Ok(self
82            .try_column_shape(table, column)
83            .map_err(|error| SQLError::Internal(format!("read identity column: {error}")))?
84            .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?
85            .and_then(|shape| shape.identity_sequence))
86    }
87    /// The type and generated kind of one column: `None` for an unknown table, and an inner `None` for a column the table does not declare. Every written value asks for it, so a catalog answers from the column alone. The default describes the whole table, which copies every column and resolves every default expression.
88    fn try_column_shape(
89        &self,
90        table: &str,
91        column: &str,
92    ) -> Result<Option<Option<ColumnShape>>, ColumnCatalogError> {
93        Ok(self.try_describe_table(table)?.map(|columns| {
94            columns
95                .into_iter()
96                .find(|definition| definition.name == column)
97                .map(|definition| ColumnShape {
98                    identity_sequence: identity_sequence(&definition),
99                    ty: definition.ty,
100                    generated: definition.generated.map(|generated| generated.kind),
101                })
102        }))
103    }
104}
105fn catalog_error(error: ColumnCatalogError, control: &ProductionControl<'_>) -> SQLError {
106    match control.format(format_args!("{error}")) {
107        Ok(message) => SQLError::Internal(message.into_parts().0),
108        Err(error) => error.into(),
109    }
110}
111fn ddl_storage_error(action: &str, error: ColumnCatalogError) -> SQLError {
112    crate::catalog::errors::storage_error(action, error.as_ref())
113}
114/// Coerce a write value to fit the column's declared type.
115pub fn coerce_to_column_type(
116    assignment: &dyn AssignmentContext,
117    catalog: &dyn AssignmentColumnCatalog,
118    table: &str,
119    column: &str,
120    value: Value,
121) -> Result<Value, SQLError> {
122    coerce_to_column_type_from(assignment, catalog, table, column, value, None)
123}
124
125pub fn coerce_to_column_type_from(
126    assignment: &dyn AssignmentContext,
127    catalog: &dyn AssignmentColumnCatalog,
128    table: &str,
129    column: &str,
130    value: Value,
131    source: Option<&ColumnType>,
132) -> Result<Value, SQLError> {
133    let Some(Some(shape)) = catalog
134        .try_column_shape(table, column)
135        .map_err(|err| ddl_storage_error("column type coercion", err))?
136    else {
137        return Ok(value);
138    };
139    coerce_column_value(assignment, value, &shape.ty, source)
140}
141
142/// Admit a table attribute and flatten procedural record descriptors at the tuple
143/// boundary. The same representation is used by triggers, constraints and storage.
144pub fn coerce_column_value(
145    assignment: &dyn AssignmentContext,
146    value: Value,
147    target: &ColumnType,
148    source: Option<&ColumnType>,
149) -> Result<Value, SQLError> {
150    let value = coerce_assignment_value(assignment, value, target, source)?;
151    let control = uqa_core::memory::ProductionControl::uncontrolled();
152    crate::expr::composites::flatten_value_with_control(
153        control.retain_external_value(value)?,
154        &control,
155    )
156    .map(|value| value.into_uncontrolled().expect("table column assignment"))
157}
158
159pub fn validate_mutation_columns<'a>(
160    catalog: &dyn AssignmentColumnCatalog,
161    table: &str,
162    columns: impl IntoIterator<Item = &'a str>,
163    action: &str,
164) -> Result<(), SQLError> {
165    validate_mutation_columns_with_control(
166        catalog,
167        table,
168        columns,
169        action,
170        &ProductionControl::uncontrolled(),
171    )
172}
173
174/// The sequence `DEFAULT` draws an identity column's value from, or `None` for a column that is not an identity column.
175pub fn identity_column_sequence(
176    catalog: &dyn AssignmentColumnCatalog,
177    table: &str,
178    column: &str,
179) -> Result<Option<String>, SQLError> {
180    catalog.try_identity_column_sequence(table, column)
181}
182
183pub fn generated_column_kind(
184    catalog: &dyn AssignmentColumnCatalog,
185    table: &str,
186    column: &str,
187) -> Result<Option<GeneratedColumnKind>, SQLError> {
188    Ok(catalog
189        .try_column_shape(table, column)
190        .map_err(|error| SQLError::Internal(format!("read generated column: {error}")))?
191        .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?
192        .and_then(|shape| shape.generated))
193}
194
195/// Validate partial targets without rejecting independent writes into the same column.
196pub fn validate_mutation_targets<'a, E: 'a>(
197    catalog: &dyn AssignmentColumnCatalog,
198    table: &str,
199    targets: impl IntoIterator<Item = &'a crate::ast::AssignmentTarget<E>>,
200    action: &str,
201    insert: bool,
202) -> Result<(), SQLError> {
203    validate_mutation_targets_with_control(
204        catalog,
205        table,
206        targets,
207        action,
208        insert,
209        &ProductionControl::uncontrolled(),
210    )
211}