What does REFERENCE ON DELETE CASCADE delete in SurrealDB?
Record reference that deletes on cascade
Note: this works, but it is a documented trap or a cost the author may not have meant.
What happens
Observed on SurrealDB 3.0.2: with post:1 referencing person:1 through a field declared REFERENCE ON DELETE CASCADE, DELETE person:1 leaves SELECT * FROM post empty.
Why it is dangerous on a populated table
SurrealDB checks a schema change against new writes, not the records already stored, so an empty table hides it: on a populated one every old record is a write waiting to fail, and whole-table work runs for the length of the table in one transaction.
Fires on
DEFINE FIELD author ON TABLE post TYPE option<record<person>> REFERENCE ON DELETE CASCADE;The safe pattern
Prefer ON DELETE REJECT (the delete fails while references exist) or UNSET, and delete dependants explicitly where that is the intent.
DEFINE FIELD author ON TABLE post TYPE option<record<person>> REFERENCE ON DELETE UNSET;Fixtures
The rule ships with these files and the test suite runs them on every change: the first set must fire, the second must stay silent.
Fires (2)
ALTER FIELD author ON TABLE post REFERENCE ON DELETE CASCADE;DEFINE FIELD author ON TABLE post TYPE option<record<person>> REFERENCE ON DELETE CASCADE;Stays silent (3)
DEFINE FIELD author ON TABLE post TYPE option<record<person>>;DEFINE FIELD author ON TABLE post TYPE option<record<person>> REFERENCE ON DELETE REJECT;DEFINE FIELD author ON TABLE post TYPE option<record<person>> REFERENCE ON DELETE UNSET;How to check locally
SurrealDB support is in beta: this rule runs locally in the free CLI over .surql migrations, static only, and not in the hosted service yet. No install, nothing leaves your machine:
npx bolvrk check migration.surql --engine=surrealdb