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((actual == expected).then_some((identity, child_doc)))
65}
66
67pub fn referencing_rows<S: Clone + 'static>(
68    context: &ReferentialContext<'_, S>,
69    table: &str,
70    fk: &ForeignKey,
71    comparison: &ForeignKeyComparison,
72    expected: &[Value],
73    action: ForeignKeyAction,
74) -> Result<Vec<(PhysicalDocumentIdentity, Document)>, SQLError> {
75    // Referential actions use SQL equality, so a NULL parent key cannot select a child row.
76    if expected.iter().any(|value| matches!(value, Value::Null)) {
77        return Ok(Vec::new());
78    }
79    let mut out = Vec::new();
80    let snapshot = super::snapshots::ReferenceSnapshot::new(context)?;
81    for physical_table in uqa_sql::semantics::partition::foreign_key_scan_tables(
82        context.constraints.partitions.catalog,
83        table,
84    )? {
85        let rows = snapshot.table(&physical_table)?;
86        let indexed = if comparison.exact_local_lookup {
87            rows.indexed_doc_ids(&fk.local_columns, expected)?
88        } else {
89            None
90        };
91        let ids = match indexed {
92            Some(ids) => ids,
93            None => rows.doc_ids()?,
94        };
95        for doc_id in ids {
96            let identity = PhysicalDocumentIdentity {
97                table: physical_table.clone(),
98                doc_id,
99            };
100            let Some(doc) = rows.document(doc_id)? else {
101                return Err(missing_document_error(
102                    "foreign-key reference scan",
103                    &physical_table,
104                    doc_id,
105                ));
106            };
107            let values = fk
108                .local_columns
109                .iter()
110                .map(|column| doc.get(column).cloned().unwrap_or(Value::Null))
111                .collect();
112            if comparison.normalize_local(values)? == expected {
113                if matches!(
114                    action,
115                    ForeignKeyAction::Cascade
116                        | ForeignKeyAction::SetNull
117                        | ForeignKeyAction::SetDefault
118                ) {
119                    rows.check_visible(doc_id)?;
120                }
121                out.push((identity, doc));
122            }
123        }
124    }
125    Ok(out)
126}
127
128pub fn apply_set_action_to_child<S: Clone + 'static>(
129    context: &ReferentialContext<'_, S>,
130    table: &str,
131    old_doc: &Document,
132    new_doc: &mut Document,
133    columns: &[String],
134    action: ForeignKeyAction,
135) -> Result<(), SQLError> {
136    for column in columns {
137        let (value, source) = match action {
138            ForeignKeyAction::SetNull => (Value::Null, None),
139            ForeignKeyAction::SetDefault => {
140                if let Some(expr) = context
141                    .assignment
142                    .columns
143                    .try_column_insert_default_expr(table, column)
144                    .map_err(|err| dml_storage_error("referential SET DEFAULT", err))?
145                {
146                    crate::query::catalog_expression::eval_lowered_expression_with_type(
147                        context.assignment.expressions.expressions,
148                        context.assignment.scopes.current_routine_scope(),
149                        &expr,
150                        Some(old_doc),
151                        &[],
152                    )?
153                } else {
154                    (Value::Null, None)
155                }
156            }
157            ForeignKeyAction::NoAction | ForeignKeyAction::Restrict | ForeignKeyAction::Cascade => {
158                return Err(SQLError::Internal(format!(
159                    "invalid SET action helper for `{action:?}`"
160                )));
161            }
162        };
163        let value = uqa_sql::assignment::columns::coerce_to_column_type_from(
164            context.assignment.assignment,
165            context.assignment.columns,
166            table,
167            column,
168            value,
169            source.as_ref(),
170        )?;
171        new_doc.insert(column.clone(), value);
172    }
173    Ok(())
174}