refactor: add chat_message_role enum and content_version column (#23042)

Migration 000434 converts chat_messages.role from text to a Postgres
enum, rebuilds the partial index, and adds content_version smallint.
The column is backfilled with DEFAULT 0, then the default is dropped
so future inserts must set it explicitly.

Version 0 uses the role-aware heuristic from #22958. Version 1 (all
new inserts) stores []ChatMessagePart JSON for all roles, including
system messages. ParseContent takes database.ChatMessage directly
and dispatches on version internally. Unknown versions error.

All string(codersdk.ChatMessageRole*) casts at DB write sites are
replaced with database.ChatMessageRole* constants from sqlc.

Refs #22958
This commit is contained in:
Mathias Fredriksson
2026-03-13 16:47:36 +00:00
committed by GitHub
parent bdbcd3428b
commit 4a79af1a0d
17 changed files with 455 additions and 208 deletions
@@ -0,0 +1,15 @@
ALTER TABLE chat_messages DROP COLUMN content_version;
DROP INDEX idx_chat_messages_compressed_summary_boundary;
ALTER TABLE chat_messages
ALTER COLUMN role TYPE text
USING (role::text);
CREATE INDEX idx_chat_messages_compressed_summary_boundary
ON chat_messages(chat_id, created_at DESC, id DESC)
WHERE compressed = TRUE
AND role = 'system'
AND visibility IN ('model', 'both');
DROP TYPE chat_message_role;
@@ -0,0 +1,32 @@
-- Add chat_message_role enum.
CREATE TYPE chat_message_role AS ENUM (
'system',
'user',
'assistant',
'tool'
);
-- Drop the partial index that references role as text before
-- converting the column type.
DROP INDEX idx_chat_messages_compressed_summary_boundary;
-- Convert role column from text to enum.
ALTER TABLE chat_messages
ALTER COLUMN role TYPE chat_message_role
USING (role::chat_message_role);
-- Recreate the partial index with enum-typed comparison.
CREATE INDEX idx_chat_messages_compressed_summary_boundary
ON chat_messages(chat_id, created_at DESC, id DESC)
WHERE compressed = TRUE
AND role = 'system'
AND visibility IN ('model', 'both');
-- Add content_version column. Default 0 backfills existing rows.
-- The default is then dropped so future inserts must specify the
-- version explicitly.
ALTER TABLE chat_messages
ADD COLUMN content_version smallint NOT NULL DEFAULT 0;
ALTER TABLE chat_messages
ALTER COLUMN content_version DROP DEFAULT;