From 2a3be30a88061cb228e00b93ceccbb3f966e804f Mon Sep 17 00:00:00 2001 From: Ethan <39577870+ethanndickson@users.noreply.github.com> Date: Sat, 21 Mar 2026 00:19:41 +1100 Subject: [PATCH] fix(coderd): return human-readable error when deleting chat provider with active chats (#23347) ## Problem Deleting a chat provider that has models referenced by existing chats returns a raw PostgreSQL foreign key violation error to the user: ``` pq: update or delete on table "chat_model_configs" violates foreign key constraint "chat_messages_model_config_id_fkey" on table "chat_messages" ``` This happens because `DELETE FROM chat_providers` cascades to hard-delete `chat_model_configs` rows, but `chat_messages` and `chats` still reference them with the default `RESTRICT` behavior. ## Fix Check for `IsForeignKeyViolation` on the two relevant constraints and return a 400 Bad Request with `"Provider models are still referenced by existing chats."`, matching the existing FK error handling pattern used elsewhere in the same file. --- coderd/chats.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/coderd/chats.go b/coderd/chats.go index ac3d33d203..566158f6e4 100644 --- a/coderd/chats.go +++ b/coderd/chats.go @@ -3485,6 +3485,16 @@ func (api *API) deleteChatProvider(rw http.ResponseWriter, r *http.Request) { } if err := api.Database.DeleteChatProviderByID(ctx, providerID); err != nil { + if database.IsForeignKeyViolation(err, + database.ForeignKeyChatMessagesModelConfigID, + database.ForeignKeyChatsLastModelConfigID, + ) { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Provider models are still referenced by existing chats.", + Detail: err.Error(), + }) + return + } httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ Message: "Failed to delete chat provider.", Detail: err.Error(),