Skip to main content

Module foreign_key

Module foreign_key 

Source
Expand description

Foreign keys, as the triggers they are.

Invariant: a foreign key is enforced by exactly the machinery a written trigger is enforced by. The clause is turned into CREATE TRIGGER text, parsed by the same parser, bound by the same binder and inlined by the same compiler - so ON DELETE CASCADE and the DELETE somebody wrote by hand cannot disagree about what a conflict clause does, what OLD means, or what order things happen in. SQLite makes the same choice for the same reason.

Generating text rather than building bound structures is deliberate. The text is printable, so a diagnostic can show what a constraint actually does, and it is the same shape a person would have written - which means every test that covers written triggers covers this too.

Four kinds of trigger come out of one clause:

  • the child’s check, on INSERT and on UPDATE OF its own key columns, which refuses a row whose parent is not there;
  • the parent’s check, on DELETE and on UPDATE OF its key, which refuses to strand a child - this is NO ACTION and RESTRICT;
  • the parent’s CASCADE, which deletes or updates the children with it;
  • the parent’s SET NULL and SET DEFAULT, which keep the children and let go of the key.

Reference: https://sqlite.org/foreignkeys.html.

Enums§

ForeignKeyEvent
Which write a synthesised trigger is generated for.

Constants§

VIOLATION_MESSAGE
The message SQLite reports for every foreign-key violation.

Functions§

parent_columns
The parent columns a key refers to.
parent_key_is_unique
Reports whether a key’s parent columns are a key of the parent.
plan_schema
Builds the triggers every table’s writes fire because of a foreign key.
sweep_statement
Returns the statement that repairs one cyclic key, or None when the key has nothing to repair.
trigger_for
Builds the trigger that enforces one key for one event, if there is one.
violation_query
Returns the SELECT that finds every row of a child table whose key has no parent, which is what PRAGMA foreign_key_check reports and what a deferred constraint is tested with at commit.