Files
coder/coderd/database/migrations/000606_chat_diff_statuses_composite_key.down.sql
T
Danielle Maywood 63a95d87f3 feat(coderd): key chat diff statuses by ref (#29081)
Part 1 of 6.

`chat_diff_statuses` had one row per chat, so a chat could only track
one PR, and switching branches overwrote the old branch's PR data. The
primary key is now `(chat_id, git_remote_origin, git_branch)`, so each
ref the agent reports gets its own row. The API still returns a single
`diff_status`: the first row of the chat's statuses, ordered by
`updated_at`, newest report first. The primary ref changes only when the
agent reports a ref: refreshes, claims, backoffs and URL writes do not
advance `updated_at`, so they cannot reorder the primary.

The gitsync worker now claims, backs off and clears rows by the full
key, not the whole chat. When the diff GET discovers a PR URL, it
updates the existing ref row and no longer inserts one. Telemetry picks
one row per chat.

**NOTE**: Migration `000606` swaps the primary key under an ACCESS
EXCLUSIVE lock. The table is small. Existing rows already fit the new
key, so no data is rewritten. The down migration keeps only the primary
row per chat. Stop old coderd instances before migrating: their `ON
CONFLICT (chat_id)` upserts fail once the old key is gone.

Generated by Coder Agents.
2026-10-01 10:59:27 +01:00

26 lines
810 B
SQL

-- The old key allows one row per chat, so keep the primary row and
-- drop the rest. The primary is the first row of the same ordering
-- the API uses: newest report first, then origin and branch.
DELETE FROM chat_diff_statuses
WHERE (chat_id, git_remote_origin, git_branch) IN (
SELECT chat_id, git_remote_origin, git_branch
FROM (
SELECT
chat_id,
git_remote_origin,
git_branch,
ROW_NUMBER() OVER (
PARTITION BY chat_id
ORDER BY updated_at DESC, git_remote_origin, git_branch
) AS rank
FROM chat_diff_statuses
) ranked
WHERE ranked.rank > 1
);
ALTER TABLE chat_diff_statuses
DROP CONSTRAINT chat_diff_statuses_pkey;
ALTER TABLE chat_diff_statuses
ADD PRIMARY KEY (chat_id);