Skip to main content

uqa_execution/mutation/referential/
references.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{
8    dml_storage_error, lock_physical_mutation_target, missing_document_error, update_lock_strength,
9    Document, ForeignKey, ForeignKeyAction, ForeignKeyComparison, PhysicalDocumentIdentity,
10    PhysicalMutationLockTarget, ReferentialContext, SQLError, Value,
11};
12
13/// Lock one referencing child row for a referential action and refetch it after the wait. Returns `None` when the child vanished or its foreign-key columns no longer reference the parent key that triggered the action, so the action skips it exactly like `PostgreSQL` after an `EvalPlanQual` recheck of the referencing row.
14pub struct ReferencingChildLock<'a> {
15    pub ref_table: &'a str,
16    pub child: &'a PhysicalDocumentIdentity,
17    pub lock_columns: &'a [String],
18    pub foreign_key: &'a ForeignKey,
19    pub comparison: &'a ForeignKeyComparison,
20    pub expected: &'a [Value],
21}
22
23pub fn lock_referencing_child<S: Clone + 'static>(
24    context: &ReferentialContext<'_, S>,
25    request: ReferencingChildLock<'_>,
26) -> Result<Option<(PhysicalDocumentIdentity, Document)>, SQLError> {
27    let ReferencingChildLock {
28        ref_table,
29        child,
30        lock_columns,
31        foreign_key,
32        comparison,
33        expected,
34    } = request;
35    let target = lock_physical_mutation_target(
36        context.locking.session,
37        &child.table,
38        ref_table,
39        child.doc_id,
40        update_lock_strength(context.locking.catalog, &child.table, lock_columns),
41    )?;
42    let PhysicalMutationLockTarget::Present { identity, recheck } = target else {
43        return Ok(None);
44    };
45    if recheck {
46        context
47            .constraints
48            .transactions
49            .refresh_explicit_statement_snapshot()?;
50    }
51    let Some(child_doc) = context
52        .locking
53        .rows
54        .get_document_for_mutation(&identity.table, identity.doc_id)?
55    else {
56        return Ok(None);
57    };
58    let actual = foreign_key
59        .local_columns
60        .iter()
61        .map(|column| child_doc.get(column).cloned().unwrap_or(Value::Null))
62        .collect();
63    let actual = comparison.normalize_local(actual)?;
64    Ok(
65        normalized_keys_equal(context.constraints.values, &actual, expected)?
66            .then_some((identity, child_doc)),
67    )
68}
69
70pub fn referencing_rows<S: Clone + 'static>(
71    context: &ReferentialContext<'_, S>,
72    table: &str,
73    fk: &ForeignKey,
74    comparison: &ForeignKeyComparison,
75    expected: &[Value],
76    action: ForeignKeyAction,
77) -> Result<Vec<(PhysicalDocumentIdentity, Document)>, SQLError> {
78    // Referential actions use SQL equality, so a NULL parent key cannot select a child row.
79    if expected.iter().any(|value| matches!(value, Value::Null)) {
80        return Ok(Vec::new());
81    }
82    let mut out = Vec::new();
83    let snapshot = super::snapshots::ReferenceSnapshot::new(context)?;
84    for physical_table in uqa_sql::semantics::partition::foreign_key_scan_tables(
85        context.constraints.partitions.catalog,
86        table,
87    )? {
88        let rows = snapshot.table(&physical_table)?;
89        let indexed = if comparison.exact_local_lookup {
90            rows.indexed_doc_ids(&fk.local_columns, expected)?
91        } else {
92            None
93        };
94        let ids = match indexed {
95            Some(ids) => ids,
96            None => rows.doc_ids()?,
97        };
98        for doc_id in ids {
99            let identity = PhysicalDocumentIdentity {
100                table: physical_table.clone(),
101                doc_id,
102            };
103            let Some(doc) = rows.document(doc_id)? else {
104                return Err(missing_document_error(
105                    "foreign-key reference scan",
106                    &physical_table,
107                    doc_id,
108                ));
109            };
110            let values = fk
111                .local_columns
112                .iter()
113                .map(|column| doc.get(column).cloned().unwrap_or(Value::Null))
114                .collect();
115            if normalized_keys_equal(
116                context.constraints.values,
117                &comparison.normalize_local(values)?,
118                expected,
119            )? {
120                if matches!(
121                    action,
122                    ForeignKeyAction::Cascade
123                        | ForeignKeyAction::SetNull
124                        | ForeignKeyAction::SetDefault
125                ) {
126                    rows.check_visible(doc_id)?;
127                }
128                out.push((identity, doc));
129            }
130        }
131    }
132    Ok(out)
133}
134
135/// Recheck already-coerced FK columns with their SQL field operators, including nested records and arrays.
136pub(super) fn normalized_keys_equal(
137    catalog: &dyn uqa_sql::expr::SQLValueCatalog,
138    actual: &[Value],
139    expected: &[Value],
140) -> Result<bool, SQLError> {
141    if actual.len() != expected.len() {
142        return Err(SQLError::Internal(
143            "foreign-key comparison widths differ after normalization".into(),
144        ));
145    }
146    let control = uqa_core::memory::ProductionControl::uncontrolled();
147    for (actual, expected) in actual.iter().zip(expected) {
148        if !uqa_sql::expr::equal_typed_values_with_enum_catalog(
149            actual,
150            expected,
151            &control,
152            Some(catalog),
153        )? {
154            return Ok(false);
155        }
156    }
157    Ok(true)
158}
159
160pub fn apply_set_action_to_child<S: Clone + 'static>(
161    context: &ReferentialContext<'_, S>,
162    table: &str,
163    old_doc: &Document,
164    new_doc: &mut Document,
165    columns: &[String],
166    action: ForeignKeyAction,
167) -> Result<(), SQLError> {
168    for column in columns {
169        let (value, source) = match action {
170            ForeignKeyAction::SetNull => (Value::Null, None),
171            ForeignKeyAction::SetDefault => {
172                if let Some(expr) = context
173                    .assignment
174                    .columns
175                    .try_column_insert_default_expr(table, column)
176                    .map_err(|err| dml_storage_error("referential SET DEFAULT", err))?
177                {
178                    crate::query::catalog_expression::eval_lowered_expression_with_type(
179                        context.assignment.expressions.expressions,
180                        context.assignment.scopes.current_routine_scope(),
181                        &expr,
182                        Some(old_doc),
183                        &[],
184                    )?
185                } else {
186                    (Value::Null, None)
187                }
188            }
189            ForeignKeyAction::NoAction | ForeignKeyAction::Restrict | ForeignKeyAction::Cascade => {
190                return Err(SQLError::Internal(format!(
191                    "invalid SET action helper for `{action:?}`"
192                )));
193            }
194        };
195        let value = uqa_sql::assignment::columns::coerce_to_column_type_from(
196            context.assignment.assignment,
197            context.assignment.columns,
198            table,
199            column,
200            value,
201            source.as_ref(),
202        )?;
203        new_doc.insert(column.clone(), value);
204    }
205    Ok(())
206}