Missing foreign key constraint on namespaces parent_id column
A namespace/group can have a parent namespace, but we don't have a DB constraint to make sure that the referenced parent_id references valid parent namespace. We should add a foreign key similar to epics (which use parent-child hierarchy too):
add_foreign_key "epics", "epics", column: "parent_id", name: "fk_25b99c1be3", on_delete: :cascade
As part of this fix it may be necessary to nullify any invalid references first.
There is a reason to assume that we have invalid parent_id at the moment in DB - invalid parent_id is the only explanation for #36938 (closed) issue - we check if parent_id is not null, but then the code fails on parent being nil.
The list of invalid references could be verified with select id from namespaces where parent_id not in (select id from namespaces); but this is quite slow/expensive (ran on #database-lab and timed out for me).