safeslice

Relationships

How the foreign-key walk builds a slice that restores without orphans, and what to do about relationships the database does not enforce.

A subset of a relational database is only useful if it still joins. Safeslice builds the slice by walking the foreign-key graph, not by taking the first N rows of each table.

Parents and children

  • Parents are followed unconditionally and transitively. A row cannot be inserted without the rows it references, so every selected row drags its referenced rows along, recursively.
  • Children are followed to child_depth. They are optional context. Following them without a bound reaches the whole database through any popular table.

The result is referentially complete: the load runs with foreign keys enforced the whole way through, so a successful commit is PostgreSQL itself confirming there are no orphans.

Cycles

Real schemas have cycles — users.company_id references companies, and companies.owner_id references users. SET CONSTRAINTS ALL DEFERRED only affects constraints declared DEFERRABLE, and neither Rails nor Django declares them.

Safeslice breaks the cycle instead: it inserts the closing column as NULL, then restores the real value with an UPDATE once every referenced row exists.

Self-references

employees.manager_id pointing at employees is the same problem in one table, and is handled the same way.

Consistency

The whole read side runs inside one REPEATABLE READ transaction. Without it, a parent row can be deleted between the query that found a child and the query that fetches the parent — and the slice then fails validation on restore for reasons nobody can reproduce afterwards.

Relationships the database does not enforce

Rails polymorphic associations and Django generic relations have no pg_constraint row. Neither does a foreign key a team simply never added. Safeslice cannot follow what the schema does not declare — so instead of guessing, it reports them:

⚠ 1 relationship the database does not enforce, so it was not followed:
  comments.commentable_id (polymorphic, with commentable_type) — no foreign key

This is the usual reason a slice comes out smaller than someone expected. Declare the ones that matter as virtual_keys and they join the graph like any other edge:

virtual_keys:
  - table: comments
    columns: [commentable_id]
    references: { table: posts, columns: [id] }
    when: "commentable_type = 'Post'"

Nothing is followed automatically on a guess. A slice whose shape nobody can explain is worse than one that is visibly incomplete.