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.
This commit is contained in:
Ethan
2026-03-21 00:19:41 +11:00
committed by GitHub
parent 186424b4e2
commit 2a3be30a88
+10
View File
@@ -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(),