Skip to main content

Module foreign_key

Module foreign_key 

Source
Expand description

Foreign Key Constraint Enforcement

This module provides helpers for checking referential integrity:

  • On INSERT/UPDATE: verify parent rows exist (index-based O(log n) / O(1))
  • On DELETE/UPDATE of parent: enforce RESTRICT/CASCADE/SET NULL

All operations participate in the caller’s transaction (via txn_id), ensuring:

  • CASCADE effects are atomic with the parent operation
  • FK checks see uncommitted rows from the current transaction
  • No independent transactions are created (no resource leaks)

Performance guarantees:

  • Zero cost for non-FK tables (all checks short-circuit on empty foreign_keys)
  • Cached reverse FK mapping (rebuilt only on schema_epoch change)
  • Index-based parent lookups (no table scans when index exists)

Functions§

check_no_referencing_rows
Check if any child tables have rows that actually reference the given parent table. Used by DROP TABLE and TRUNCATE to ensure no referencing rows exist. Only counts rows where the FK column is non-NULL (NULL means “no reference”).
check_parent_exists
Check that all FK values in a row reference existing parent rows. Called on INSERT and UPDATE (when FK columns change).
enforce_delete_actions_iter
Enforce referential actions for DELETE from a parent table. Accepts an iterator of PK values to avoid allocating a separate Vec.
enforce_update_actions
Enforce referential actions for UPDATE of a referenced column. RESTRICT is already handled by pre_check_restrict_for_update before the parent row is written. This function only dispatches CASCADE/SET NULL.
find_referencing_fks
Find all foreign key constraints in other tables that reference the given parent table. Delegates to the engine’s cached reverse mapping (rebuilt only on schema_epoch change). Returns Arc-wrapped Vec (ref-count bump only, no cloning).
find_referencing_fks_for_txn
fk_tree_needs_precheck
Check if the FK tree rooted at these referencing FKs needs row-level pre-checking. Returns true if any path contains RESTRICT/NoAction or exceeds CASCADE depth. This is a metadata-only walk (no row scans) used to skip the expensive pre-scan when the tree is pure CASCADE/SET NULL within depth limits.
pre_check_restrict_for_update
Pre-check RESTRICT constraints and CASCADE depth before writing parent rows. Walks the full FK tree (including recursive grandchild RESTRICT behind CASCADE/SET NULL) to detect violations before any rows are modified, preserving statement atomicity. Returns true if the tree has constraints that need row-level pre-checking.
validate_fk_value
Pre-validate a single FK value against its parent table. Used for early validation of constant SET values in UPDATE statements to prevent dirty state in explicit transactions.