Demo, all content is generated
Question

Can't delete a user from the dashboard: 'Database error deleting user'

Solved · 414 views · asked by tariq_builds · edited

Someone asked me to delete their account. In Authentication > Users > Delete user I get "Database error deleting user". The Postgres logs say:

update or delete on table "users" violates foreign key constraint "posts_author_id_fkey" on table "posts"
What I’ve tried

Tried deleting their posts first by hand, then it fails on a different table (comments). There are 6 tables that reference the user.

Comment
Do you want their posts gone, or kept as 'deleted user'? That decides the fix. sven_fire · edited

2 answers

Marked as helpful by the asker
hannah_reyes · edited

Your foreign keys to auth.users were created without an on delete rule, so Postgres refuses. Decide per table:

-- their own stuff disappears with them
alter table posts drop constraint posts_author_id_fkey,
  add constraint posts_author_id_fkey foreign key (author_id)
  references auth.users(id) on delete cascade;

-- keep the row, lose the link (column must be nullable)
alter table comments drop constraint comments_author_id_fkey,
  add constraint comments_author_id_fkey foreign key (author_id)
  references auth.users(id) on delete set null;

Find them all at once:

select conrelid::regclass, conname from pg_constraint
where confrelid = 'auth.users'::regclass;

For a GDPR-style deletion, cascade on their personal data is usually what you want.

Comment
Nice query for finding all constraints, stealing it. sven_fire · edited
6 constraints fixed via one migration, user deleted. Thanks both tariq_builds · edited
wes_codes · edited

If you'd rather keep their content, anonymize instead of deleting: set their profile name to "Deleted user", remove email and avatar, then delete the auth user with on delete set null on the content tables.

Comment
They wanted everything gone, but good to know for the next one. tariq_builds · edited