uqa_execution/mutation/referential/
references.rs1use 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};
12use crate::mutation::candidate_ids::{CandidateIds, CapturedCandidateIds};
13
14pub struct ReferencingRows {
16 tables: Vec<String>,
17 rows: Option<CapturedCandidateIds>,
18}
19
20impl ReferencingRows {
21 pub fn is_empty(&self) -> bool {
22 self.rows
23 .as_ref()
24 .is_none_or(CapturedCandidateIds::is_empty)
25 }
26
27 pub fn read_rows(
28 &self,
29 ) -> Result<impl Iterator<Item = Result<PhysicalDocumentIdentity, SQLError>> + '_, SQLError>
30 {
31 Ok(self
32 .rows
33 .as_ref()
34 .map(CapturedCandidateIds::read_rows)
35 .transpose()?
36 .into_iter()
37 .flatten()
38 .map(|row| {
39 let (table, doc_id) = row?;
40 let table = self.tables.get(table).ok_or_else(|| {
41 SQLError::Internal("referencing row has an invalid table ordinal".into())
42 })?;
43 Ok(PhysicalDocumentIdentity {
44 table: table.clone(),
45 doc_id,
46 })
47 }))
48 }
49}
50
51pub struct ReferencingChildLock<'a> {
53 pub ref_table: &'a str,
54 pub child: &'a PhysicalDocumentIdentity,
55 pub lock_columns: &'a [String],
56 pub foreign_key: &'a ForeignKey,
57 pub comparison: &'a ForeignKeyComparison,
58 pub expected: &'a [Value],
59}
60
61pub fn lock_referencing_child<S: Clone + 'static>(
62 context: &ReferentialContext<'_, S>,
63 request: ReferencingChildLock<'_>,
64) -> Result<Option<(PhysicalDocumentIdentity, Document)>, SQLError> {
65 let ReferencingChildLock {
66 ref_table,
67 child,
68 lock_columns,
69 foreign_key,
70 comparison,
71 expected,
72 } = request;
73 let target = lock_physical_mutation_target(
74 context.locking.session,
75 &child.table,
76 ref_table,
77 child.doc_id,
78 update_lock_strength(context.locking.catalog, &child.table, lock_columns),
79 )?;
80 let PhysicalMutationLockTarget::Present { identity, recheck } = target else {
81 return Ok(None);
82 };
83 if recheck {
84 context
85 .constraints
86 .transactions
87 .refresh_explicit_statement_snapshot()?;
88 }
89 let Some(child_doc) = context
90 .locking
91 .rows
92 .get_document_for_mutation(&identity.table, identity.doc_id)?
93 else {
94 return Ok(None);
95 };
96 let actual = foreign_key
97 .local_columns
98 .iter()
99 .map(|column| child_doc.get(column).cloned().unwrap_or(Value::Null))
100 .collect();
101 let actual = comparison.normalize_local(actual)?;
102 Ok(
103 normalized_keys_equal(context.constraints.values, &actual, expected)?
104 .then_some((identity, child_doc)),
105 )
106}
107
108pub fn referencing_rows<S: Clone + 'static>(
109 context: &ReferentialContext<'_, S>,
110 table: &str,
111 fk: &ForeignKey,
112 comparison: &ForeignKeyComparison,
113 expected: &[Value],
114 action: ForeignKeyAction,
115) -> Result<ReferencingRows, SQLError> {
116 if expected.iter().any(|value| matches!(value, Value::Null)) {
118 return Ok(ReferencingRows {
119 tables: Vec::new(),
120 rows: None,
121 });
122 }
123 let mut out = CandidateIds::new(
124 context.constraints.memory.work_mem_bytes()?,
125 context.triggers.runtime.cancellation.clone(),
126 );
127 let snapshot = super::snapshots::ReferenceSnapshot::new(context)?;
128 let tables = uqa_sql::semantics::partition::foreign_key_scan_tables(
129 context.constraints.partitions.catalog,
130 table,
131 )?;
132 for (table_index, physical_table) in tables.iter().enumerate() {
133 let rows = snapshot.table(physical_table)?;
134 let indexed = if comparison.exact_local_lookup {
135 rows.indexed_doc_ids(
136 &fk.local_columns,
137 expected,
138 context.constraints.memory.work_mem_bytes()?,
139 context.triggers.runtime.cancellation,
140 )?
141 } else {
142 None
143 };
144 let mut visit = |doc_id| -> Result<bool, SQLError> {
145 context.triggers.runtime.cancellation.check()?;
146 let Some(doc) = rows.document(doc_id)? else {
147 return Err(missing_document_error(
148 "foreign-key reference scan",
149 physical_table,
150 doc_id,
151 ));
152 };
153 let values = fk
154 .local_columns
155 .iter()
156 .map(|column| doc.get(column).cloned().unwrap_or(Value::Null))
157 .collect();
158 if normalized_keys_equal(
159 context.constraints.values,
160 &comparison.normalize_local(values)?,
161 expected,
162 )? {
163 if matches!(
164 action,
165 ForeignKeyAction::Cascade
166 | ForeignKeyAction::SetNull
167 | ForeignKeyAction::SetDefault
168 ) {
169 rows.check_visible(doc_id)?;
170 }
171 out.push(table_index, doc_id)?;
172 }
173 Ok(true)
174 };
175 match indexed {
176 Some(ids) => ids.visit(&mut |_, id| visit(id))?,
177 None => rows.visit_doc_ids(
178 context.constraints.memory.work_mem_bytes()?,
179 context.triggers.runtime.cancellation,
180 &mut visit,
181 )?,
182 }
183 }
184 Ok(ReferencingRows {
185 tables,
186 rows: Some(out.finish()?),
187 })
188}
189
190pub(super) fn normalized_keys_equal(
192 catalog: &dyn uqa_sql::expr::SQLValueCatalog,
193 actual: &[Value],
194 expected: &[Value],
195) -> Result<bool, SQLError> {
196 if actual.len() != expected.len() {
197 return Err(SQLError::Internal(
198 "foreign-key comparison widths differ after normalization".into(),
199 ));
200 }
201 let control = uqa_core::memory::ProductionControl::uncontrolled();
202 for (actual, expected) in actual.iter().zip(expected) {
203 if !uqa_sql::expr::equal_typed_values_with_enum_catalog(
204 actual,
205 expected,
206 &control,
207 Some(catalog),
208 )? {
209 return Ok(false);
210 }
211 }
212 Ok(true)
213}
214
215pub fn apply_set_action_to_child<S: Clone + 'static>(
216 context: &ReferentialContext<'_, S>,
217 table: &str,
218 old_doc: &Document,
219 new_doc: &mut Document,
220 columns: &[String],
221 action: ForeignKeyAction,
222) -> Result<(), SQLError> {
223 for column in columns {
224 let (value, source) = match action {
225 ForeignKeyAction::SetNull => (Value::Null, None),
226 ForeignKeyAction::SetDefault => {
227 if let Some(expr) = context
228 .assignment
229 .columns
230 .try_column_insert_default_expr(table, column)
231 .map_err(|err| dml_storage_error("referential SET DEFAULT", err))?
232 {
233 crate::query::catalog_expression::eval_lowered_expression_with_type(
234 context.assignment.expressions.expressions,
235 context.assignment.scopes.current_routine_scope(),
236 &expr,
237 Some(old_doc),
238 &[],
239 )?
240 } else {
241 (Value::Null, None)
242 }
243 }
244 ForeignKeyAction::NoAction | ForeignKeyAction::Restrict | ForeignKeyAction::Cascade => {
245 return Err(SQLError::Internal(format!(
246 "invalid SET action helper for `{action:?}`"
247 )));
248 }
249 };
250 let value = uqa_sql::assignment::columns::coerce_to_column_type_from(
251 context.assignment.assignment,
252 context.assignment.columns,
253 table,
254 column,
255 value,
256 source.as_ref(),
257 )?;
258 new_doc.insert(column.clone(), value);
259 }
260 Ok(())
261}