use super::{
foreign_key_comparison_types, foreign_key_lookup_values, referencing_rows,
referrers_to_for_actions, BTreeSet, DeletedRowLookup, DocId, Document, ForeignKey,
ForeignKeyAction, PhysicalDocumentIdentity, ReferentialContext, SQLError, Value,
};
pub fn defer_updated_key_checks<S: Clone + 'static>(
context: &ReferentialContext<'_, S>,
table: &str,
referenced_relation: &str,
parent_doc_id: DocId,
old_doc: &Document,
new_doc: &Document,
) -> Result<(), SQLError> {
for (ref_table, fk) in referrers_to_for_actions(context.constraints.referrers, table)? {
if fk.on_update != ForeignKeyAction::NoAction
|| !super::checks::referenced_key_changed(&fk.ref_columns, old_doc, new_doc)
{
continue;
}
let old_values: Vec<Value> = fk
.ref_columns
.iter()
.map(|c| old_doc.get(c).cloned().unwrap_or(Value::Null))
.collect();
if old_values.iter().any(|v| matches!(v, Value::Null)) {
continue;
}
let firing = uqa_sql::schema::referenced_partitions::firing_constraint(
context.constraints.partitions.catalog,
table,
(referenced_relation != table).then_some(referenced_relation),
&fk,
)?;
if !context
.constraints
.transactions
.referenced_key_is_deferred(&ref_table, &fk, firing.derived)?
{
continue;
}
let comparison =
foreign_key_comparison_types(context.constraints.partitions.catalog, &ref_table, &fk)?;
let referenced_values: std::sync::Arc<[Value]> = old_values.into();
let expected = comparison.normalize_referenced(referenced_values.to_vec())?;
context.deferrals.defer_foreign_key_parent_event(
&ref_table,
firing.relation,
&fk,
firing.derived,
)?;
if fk.period {
let parent = PhysicalDocumentIdentity {
table: table.to_string(),
doc_id: parent_doc_id,
};
defer_period_key_checks(
context,
PeriodKeyChecks {
constraint_table: &ref_table,
firing_relation: firing.relation,
foreign_key: &fk,
derived: firing.derived,
expected: &expected,
referenced_values: &referenced_values,
root_deletes: &|_, _| Ok(false),
},
&|table, id| Ok(table == parent.table && id == parent.doc_id),
Some((&parent, new_doc)),
)?;
continue;
}
let referencing = referencing_rows(
context,
&ref_table,
&fk,
&comparison,
&expected,
ForeignKeyAction::NoAction,
)?;
for child in referencing.read_rows()? {
let child = child?;
context.deferrals.defer_foreign_key_check(
&ref_table,
firing.relation,
(&child.table, child.doc_id),
&fk,
firing.derived,
referenced_values.clone(),
)?;
}
}
Ok(())
}
pub fn defer_deleted_key_checks<S: Clone + 'static>(
context: &ReferentialContext<'_, S>,
parent_table: &str,
parent_doc_id: DocId,
parent_document: &Document,
root_deletes: &BTreeSet<(String, DocId)>,
) -> Result<(), SQLError> {
defer_deleted_key_checks_excluding(
context,
parent_table,
parent_doc_id,
parent_document,
&|table, id| Ok(root_deletes.contains(&(table.to_owned(), id))),
)
}
pub(crate) fn defer_deleted_key_checks_excluding<S: Clone + 'static>(
context: &ReferentialContext<'_, S>,
parent_table: &str,
parent_doc_id: DocId,
parent_document: &Document,
root_deletes: &DeletedRowLookup<'_>,
) -> Result<(), SQLError> {
for (ref_table, fk) in referrers_to_for_actions(context.constraints.referrers, parent_table)? {
if fk.on_delete != ForeignKeyAction::NoAction {
continue;
}
let key_values: Vec<Value> = fk
.ref_columns
.iter()
.map(|column| parent_document.get(column).cloned().unwrap_or(Value::Null))
.collect();
if key_values.iter().any(|value| matches!(value, Value::Null)) {
continue;
}
let firing = uqa_sql::schema::referenced_partitions::firing_constraint(
context.constraints.partitions.catalog,
parent_table,
None,
&fk,
)?;
if !context
.constraints
.transactions
.referenced_key_is_deferred(&ref_table, &fk, firing.derived)?
{
continue;
}
let comparison =
foreign_key_comparison_types(context.constraints.partitions.catalog, &ref_table, &fk)?;
let referenced_values: std::sync::Arc<[Value]> = key_values.into();
let expected = comparison.normalize_referenced(referenced_values.to_vec())?;
context.deferrals.defer_foreign_key_parent_event(
&ref_table,
parent_table,
&fk,
firing.derived,
)?;
if fk.period {
let excluded_parents = |table: &str, id| {
if table == parent_table && id == parent_doc_id {
Ok(true)
} else {
root_deletes(table, id)
}
};
defer_period_key_checks(
context,
PeriodKeyChecks {
constraint_table: &ref_table,
firing_relation: parent_table,
foreign_key: &fk,
derived: firing.derived,
expected: &expected,
referenced_values: &referenced_values,
root_deletes,
},
&excluded_parents,
None,
)?;
continue;
}
let referencing = referencing_rows(
context,
&ref_table,
&fk,
&comparison,
&expected,
ForeignKeyAction::NoAction,
)?;
for child in referencing.read_rows()? {
let child = child?;
if root_deletes(&child.table, child.doc_id)? {
continue;
}
context.deferrals.defer_foreign_key_check(
&ref_table,
parent_table,
(&child.table, child.doc_id),
&fk,
firing.derived,
referenced_values.clone(),
)?;
}
}
Ok(())
}
struct PeriodKeyChecks<'a> {
constraint_table: &'a str,
firing_relation: &'a str,
foreign_key: &'a ForeignKey,
derived: Option<&'a uqa_sql::ast::ReferencedPartitionConstraint>,
expected: &'a [Value],
referenced_values: &'a std::sync::Arc<[Value]>,
root_deletes: &'a DeletedRowLookup<'a>,
}
fn defer_period_key_checks<S: Clone + 'static>(
context: &ReferentialContext<'_, S>,
key: PeriodKeyChecks<'_>,
excluded_parents: &DeletedRowLookup<'_>,
replacement: Option<(&PhysicalDocumentIdentity, &Document)>,
) -> Result<(), SQLError> {
let snapshot = super::snapshots::ReferenceSnapshot::new(context)?;
let ordinary_len = key.expected.len().saturating_sub(1);
for physical_table in uqa_sql::semantics::partition::foreign_key_scan_tables(
context.constraints.partitions.catalog,
key.constraint_table,
)? {
let rows = snapshot.table(&physical_table)?;
rows.visit_doc_ids(
context.constraints.memory.work_mem_bytes()?,
context.triggers.runtime.cancellation,
&mut |child_id| {
if (key.root_deletes)(&physical_table, child_id)? {
return Ok(true);
}
let Some(child_document) = rows.document(child_id)? else {
return Ok(true);
};
let Some(child_lookup) = foreign_key_lookup_values(
context.constraints.partitions.catalog,
&physical_table,
key.foreign_key,
&child_document,
)?
else {
return Ok(true);
};
if !crate::mutation::constraints::index_keys::key_values_equal(
&child_lookup.values[..ordinary_len],
&key.expected[..ordinary_len],
context.constraints.values,
)? {
return Ok(true);
}
if crate::mutation::constraints::period::period_foreign_key_coverage_excluding(
context.constraints,
key.foreign_key,
&child_lookup.values,
excluded_parents,
replacement,
)? {
return Ok(true);
}
context.deferrals.defer_foreign_key_check(
key.constraint_table,
key.firing_relation,
(&physical_table, child_id),
key.foreign_key,
key.derived,
key.referenced_values.clone(),
)?;
Ok(true)
},
)?;
}
Ok(())
}