From c0ebe7f59f2fa5c585872382b61486b64972295c Mon Sep 17 00:00:00 2001 From: Hermes Date: Fri, 14 Aug 2026 15:20:40 +0200 Subject: [PATCH] fix(manage-users): detach FK references before deleting user (RESTRICT FKs in order_history/action_logs/suggestions/order_groups blocked auth.deleteUser with 'Database error deleting user') --- supabase/functions/manage-users/index.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/supabase/functions/manage-users/index.ts b/supabase/functions/manage-users/index.ts index b2d1a10..4e529ef 100644 --- a/supabase/functions/manage-users/index.ts +++ b/supabase/functions/manage-users/index.ts @@ -132,6 +132,25 @@ Deno.serve(async (request) => { return jsonResponse({ ok: false, error: "Пользователь не найден" }, 404, corsHeaders); } + // Detach FK references before deleting auth user. + // Several tables reference public.users via RESTRICT FKs (no ON DELETE CASCADE): + // order_history, action_logs, suggestions, order_groups.assigned_driver_id, etc. + // Without detaching, auth.admin.deleteUser fails with "Database error deleting user". + const detachStatements: Array<[string, string]> = [ + ["orders", "manager_id"], + ["orders", "logistician_id"], + ["orders", "assigned_driver_id"], + ["order_logisticians", "assigned_by"], + ["order_history", "user_id"], + ["delivery_slots", "logistician_id"], + ["order_groups", "assigned_driver_id"], + ["action_logs", "performed_by"], + ["suggestions", "author_id"], + ]; + for (const [table, column] of detachStatements) { + await supabase.from(table).update({ [column]: null }).eq(column, userId); + } + // Delete auth user (FK ON DELETE CASCADE will remove public.users row) const { error: authDeleteError } = await supabase.auth.admin.deleteUser(userId); if (authDeleteError) {