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::{
9    candidate_ids::CandidateIds,
10    constraints::context::{ConstraintContext, MutationRead},
11};
12use crate::query::runtime::QueryMemorySettings;
13use uqa_core::{CancellationToken, Value};
14use uqa_sql::{
15    assignment::columns::{AssignmentColumnCatalog, ColumnCatalogError},
16    semantics::partition::PartitionExpressions,
17    SQLError,
18};
19
20#[cfg(test)]
21mod tests;
22
23pub struct CheckValidationContext<'a> {
24    pub columns: &'a dyn AssignmentColumnCatalog,
25    pub reads: &'a dyn MutationRead,
26    pub expressions: &'a dyn PartitionExpressions,
27    pub types: &'a dyn uqa_sql::FunctionTypeResolver,
28    pub memory: &'a dyn QueryMemorySettings,
29    pub cancellation: &'a CancellationToken,
30}
31fn ddl_storage_error(action: &str, error: ColumnCatalogError) -> SQLError {
32    uqa_sql::catalog::errors::storage_error(action, error.as_ref())
33}
34fn constraint_error(sqlstate: &str, message: impl Into<String>) -> SQLError {
35    SQLError::Routine {
36        sqlstate: sqlstate.into(),
37        message: message.into(),
38    }
39}
40pub fn validate_foreign_key_rows(
41    context: ConstraintContext<'_>,
42    table: &str,
43    name: &str,
44    foreign_key: &uqa_sql::ast::ForeignKey,
45) -> Result<(), SQLError> {
46    let ids = CandidateIds::from_pages(
47        context.memory.work_mem_bytes()?,
48        context.cancellation,
49        |after, limit, control| {
50            context
51                .reads
52                .live_table_doc_id_page(table, after, limit, control)
53        },
54    )?;
55    for row in ids.read_rows()? {
56        let (_, doc_id) = row?;
57        let Some(document) = context.reads.get_document(table, doc_id)? else {
58            continue;
59        };
60        let Some(values) = uqa_sql::semantics::foreign_keys::foreign_key_lookup_values(
61            context.partitions.catalog,
62            table,
63            foreign_key,
64            &document,
65        )?
66        else {
67            continue;
68        };
69        let parent_exists = if foreign_key.period {
70            crate::mutation::constraints::period::period_foreign_key_is_covered(
71                context,
72                foreign_key,
73                &values.values,
74                &[],
75                None,
76            )?
77        } else {
78            crate::mutation::constraints::find_foreign_key_parent(context, foreign_key, &values)?
79                .is_some()
80        };
81        if !parent_exists {
82            return Err(crate::mutation::constraints::referencing_row_violation(
83                context,
84                table,
85                name,
86                foreign_key,
87                &document,
88            )?);
89        }
90    }
91    Ok(())
92}
93
94/// 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.
95pub fn validate_rewritten_foreign_keys(
96    context: ConstraintContext<'_>,
97    table: &str,
98    changed: &[String],
99) -> Result<(), SQLError> {
100    for foreign_key in context
101        .catalog
102        .try_foreign_keys(table)
103        .map_err(|error| SQLError::Internal(format!("foreign key lookup: {error}")))?
104    {
105        if !foreign_key.enforced
106            || !foreign_key.validated
107            || !foreign_key
108                .local_columns
109                .iter()
110                .any(|column| changed.contains(column))
111        {
112            continue;
113        }
114        let name = foreign_key
115            .name
116            .clone()
117            .unwrap_or_else(|| "<unnamed>".into());
118        validate_foreign_key_rows(context, table, &name, &foreign_key)?;
119    }
120    let mut checked = std::collections::BTreeSet::new();
121    for target in context.referrers.partition_ancestor_tables(table)? {
122        let referrers = context
123            .referrers
124            .try_referrers_to(&target)
125            .map_err(|error| SQLError::Internal(format!("foreign key lookup: {error}")))?;
126        for (declaring_table, foreign_key) in referrers {
127            if !foreign_key.enforced
128                || !foreign_key.validated
129                || !foreign_key
130                    .ref_columns
131                    .iter()
132                    .any(|column| changed.contains(column))
133            {
134                continue;
135            }
136            let name = foreign_key
137                .name
138                .clone()
139                .unwrap_or_else(|| "<unnamed>".into());
140            for physical_table in uqa_sql::semantics::partition::foreign_key_scan_tables(
141                context.partitions.catalog,
142                &declaring_table,
143            )? {
144                if checked.insert((physical_table.clone(), name.clone())) {
145                    validate_foreign_key_rows(context, &physical_table, &name, &foreign_key)?;
146                }
147            }
148        }
149    }
150    Ok(())
151}
152
153pub fn validate_not_null_rows(
154    reads: &dyn MutationRead,
155    memory: &dyn QueryMemorySettings,
156    cancellation: &CancellationToken,
157    table: &str,
158    column: &str,
159) -> Result<(), SQLError> {
160    validate_not_null_columns(reads, memory, cancellation, table, &[column])
161}
162
163/// Validate retained NOT NULL requirements in physical column order with one row traversal.
164pub fn validate_not_null_columns(
165    reads: &dyn MutationRead,
166    memory: &dyn QueryMemorySettings,
167    cancellation: &CancellationToken,
168    table: &str,
169    columns: &[&str],
170) -> Result<(), SQLError> {
171    let relation = uqa_core::RelationIdentity::from_legacy_name(table)
172        .map_err(|error| SQLError::Internal(format!("resolve NOT NULL relation: {error}")))?;
173    let ids = CandidateIds::from_pages(
174        memory.work_mem_bytes()?,
175        cancellation,
176        |after, limit, control| reads.live_table_doc_id_page(table, after, limit, control),
177    )?;
178    for row in ids.read_rows()? {
179        let (_, doc_id) = row?;
180        let Some(document) = reads.get_document(table, doc_id)? else {
181            continue;
182        };
183        if let Some(column) = columns
184            .iter()
185            .copied()
186            .find(|column| matches!(document.get(*column), None | Some(Value::Null)))
187        {
188            return Err(constraint_error(
189                "23502",
190                format!(
191                    "column \"{column}\" of relation \"{}\" contains null values",
192                    relation.name
193                ),
194            ));
195        }
196    }
197    Ok(())
198}
199
200pub fn validate_check_rows(
201    context: &CheckValidationContext<'_>,
202    table: &str,
203    name: &str,
204    expression: &uqa_sql::ast::Expr,
205) -> Result<(), SQLError> {
206    let definitions = context
207        .columns
208        .try_describe_table(table)
209        .map_err(|error| ddl_storage_error("VALIDATE CHECK", error))?
210        .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
211    let scope = super::check_rows::CheckRowScope::new(context.types, table, &definitions)?;
212    let ids = CandidateIds::from_pages(
213        context.memory.work_mem_bytes()?,
214        context.cancellation,
215        |after, limit, control| {
216            context
217                .reads
218                .live_table_doc_id_page(table, after, limit, control)
219        },
220    )?;
221    for row in ids.read_rows()? {
222        let (_, doc_id) = row?;
223        let Some(mut document) = context.reads.get_document(table, doc_id)? else {
224            continue;
225        };
226        crate::query::generated::materialize_virtual_generated_columns(
227            &definitions,
228            &mut document,
229        )?;
230        let value = scope.evaluate(context.expressions, expression, &document, &[])?;
231        if !matches!(value, Value::Null) && !uqa_sql::expr::truthy(&value) {
232            let relation = uqa_core::RelationIdentity::from_legacy_name(table)
233                .map_or_else(|_| table.to_string(), |identity| identity.name);
234            return Err(constraint_error(
235                "23514",
236                format!(
237                    "check constraint \"{name}\" of relation \"{relation}\" is violated by some row"
238                ),
239            ));
240        }
241    }
242    Ok(())
243}