Skip to main content

uqa_execution/schema/
validation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Validate newly declared constraints against existing physical rows.
8use crate::mutation::constraints::context::{ConstraintContext, MutationRead};
9use uqa_core::Value;
10use uqa_sql::{
11    assignment::columns::{AssignmentColumnCatalog, ColumnCatalogError},
12    semantics::partition::PartitionExpressions,
13    SQLError,
14};
15pub struct CheckValidationContext<'a> {
16    pub columns: &'a dyn AssignmentColumnCatalog,
17    pub reads: &'a dyn MutationRead,
18    pub expressions: &'a dyn PartitionExpressions,
19    pub types: &'a dyn uqa_sql::FunctionTypeResolver,
20}
21fn ddl_storage_error(action: &str, error: ColumnCatalogError) -> SQLError {
22    uqa_sql::catalog::errors::storage_error(action, error.as_ref())
23}
24fn constraint_error(sqlstate: &str, message: impl Into<String>) -> SQLError {
25    SQLError::Routine {
26        sqlstate: sqlstate.into(),
27        message: message.into(),
28    }
29}
30pub fn validate_foreign_key_rows(
31    context: ConstraintContext<'_>,
32    table: &str,
33    name: &str,
34    foreign_key: &uqa_sql::ast::ForeignKey,
35) -> Result<(), SQLError> {
36    for doc_id in context.reads.live_table_doc_ids(table)? {
37        let Some(document) = context.reads.get_document(table, doc_id)? else {
38            continue;
39        };
40        let Some(values) = uqa_sql::semantics::foreign_keys::foreign_key_lookup_values(
41            context.partitions.catalog,
42            table,
43            foreign_key,
44            &document,
45        )?
46        else {
47            continue;
48        };
49        let parent_exists = if foreign_key.period {
50            crate::mutation::constraints::period::period_foreign_key_coverage(
51                context,
52                foreign_key,
53                &values.values,
54                &[],
55                None,
56            )?
57            .0
58        } else {
59            crate::mutation::constraints::find_foreign_key_parent(context, foreign_key, &values)?
60                .is_some()
61        };
62        if !parent_exists {
63            return Err(crate::mutation::constraints::referencing_row_violation(
64                context,
65                table,
66                name,
67                foreign_key,
68                &document,
69            )?);
70        }
71    }
72    Ok(())
73}
74
75/// Validate the foreign keys that a rewrite of `table` rebuilds because they involve one of its `changed` columns: those of `table`, against the rows they reference, and those of other tables that reference `table`, against its rewritten rows. `PostgreSQL` validates a rebuilt foreign key whatever the replication role and leaves a `NOT VALID` one unvalidated.
76pub fn validate_rewritten_foreign_keys(
77    context: ConstraintContext<'_>,
78    table: &str,
79    changed: &[String],
80) -> Result<(), SQLError> {
81    for foreign_key in context
82        .catalog
83        .try_foreign_keys(table)
84        .map_err(|error| SQLError::Internal(format!("foreign key lookup: {error}")))?
85    {
86        if !foreign_key.enforced
87            || !foreign_key.validated
88            || !foreign_key
89                .local_columns
90                .iter()
91                .any(|column| changed.contains(column))
92        {
93            continue;
94        }
95        let name = foreign_key
96            .name
97            .clone()
98            .unwrap_or_else(|| "<unnamed>".into());
99        validate_foreign_key_rows(context, table, &name, &foreign_key)?;
100    }
101    let mut checked = std::collections::BTreeSet::new();
102    for target in context.referrers.partition_ancestor_tables(table)? {
103        let referrers = context
104            .referrers
105            .try_referrers_to(&target)
106            .map_err(|error| SQLError::Internal(format!("foreign key lookup: {error}")))?;
107        for (declaring_table, foreign_key) in referrers {
108            if !foreign_key.enforced
109                || !foreign_key.validated
110                || !foreign_key
111                    .ref_columns
112                    .iter()
113                    .any(|column| changed.contains(column))
114            {
115                continue;
116            }
117            let name = foreign_key
118                .name
119                .clone()
120                .unwrap_or_else(|| "<unnamed>".into());
121            for physical_table in uqa_sql::semantics::partition::foreign_key_scan_tables(
122                context.partitions.catalog,
123                &declaring_table,
124            )? {
125                if checked.insert((physical_table.clone(), name.clone())) {
126                    validate_foreign_key_rows(context, &physical_table, &name, &foreign_key)?;
127                }
128            }
129        }
130    }
131    Ok(())
132}
133
134pub fn validate_not_null_rows(
135    reads: &dyn MutationRead,
136    table: &str,
137    column: &str,
138) -> Result<(), SQLError> {
139    let relation = uqa_core::RelationIdentity::from_legacy_name(table)
140        .map_err(|error| SQLError::Internal(format!("resolve NOT NULL relation: {error}")))?;
141    for doc_id in reads.live_table_doc_ids(table)? {
142        let Some(document) = reads.get_document(table, doc_id)? else {
143            continue;
144        };
145        if matches!(document.get(column), None | Some(Value::Null)) {
146            return Err(constraint_error(
147                "23502",
148                format!(
149                    "column \"{column}\" of relation \"{}\" contains null values",
150                    relation.name
151                ),
152            ));
153        }
154    }
155    Ok(())
156}
157
158pub fn validate_check_rows(
159    context: &CheckValidationContext<'_>,
160    table: &str,
161    name: &str,
162    expression: &uqa_sql::ast::Expr,
163) -> Result<(), SQLError> {
164    let definitions = context
165        .columns
166        .try_describe_table(table)
167        .map_err(|error| ddl_storage_error("VALIDATE CHECK", error))?
168        .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
169    let scope = super::check_rows::CheckRowScope::new(context.types, table, &definitions)?;
170    for doc_id in context.reads.live_table_doc_ids(table)? {
171        let Some(mut document) = context.reads.get_document(table, doc_id)? else {
172            continue;
173        };
174        crate::query::generated::materialize_virtual_generated_columns(
175            &definitions,
176            &mut document,
177        )?;
178        let value = scope.evaluate(context.expressions, expression, &document, &[])?;
179        if !matches!(value, Value::Null) && !uqa_sql::expr::truthy(&value) {
180            let relation = uqa_core::RelationIdentity::from_legacy_name(table)
181                .map_or_else(|_| table.to_string(), |identity| identity.name);
182            return Err(constraint_error(
183                "23514",
184                format!(
185                    "check constraint \"{name}\" of relation \"{relation}\" is violated by some row"
186                ),
187            ));
188        }
189    }
190    Ok(())
191}