Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
perf: optimize migration 371 to run faster on large deployments
closes #20899

This is in response to a migration in v2.27 that takes very long on deployments with large `api_key` tables.
  • Loading branch information
geokat committed Nov 25, 2025
commit 237ee70bec4e4920c7d6f8a45dd21e53ce98b869
Original file line number Diff line number Diff line change
Expand Up @@ -141,17 +141,24 @@ ALTER TYPE api_key_scope ADD VALUE IF NOT EXISTS 'workspace_proxy:read';
ALTER TYPE api_key_scope ADD VALUE IF NOT EXISTS 'workspace_proxy:update';
-- End enum extensions

-- Purge old API keys to speed up the migration for large deployments.
-- Note: that problem should be solved in coderd once PR 20863 is released:
-- https://github.com/coder/coder/blob/main/coderd/database/dbpurge/dbpurge.go#L85

DELETE FROM api_keys WHERE expires_at < NOW() - INTERVAL '7 days';

-- Add new columns without defaults; backfill; then enforce NOT NULL
ALTER TABLE api_keys ADD COLUMN scopes api_key_scope[];
ALTER TABLE api_keys ADD COLUMN allow_list text[];
ALTER TABLE api_keys
ADD COLUMN scopes api_key_scope[],
ADD COLUMN allow_list text[];

-- Backfill existing rows for compatibility
UPDATE api_keys SET scopes = ARRAY[scope::api_key_scope];
UPDATE api_keys SET allow_list = ARRAY['*:*'];

-- Enforce NOT NULL
ALTER TABLE api_keys ALTER COLUMN scopes SET NOT NULL;
ALTER TABLE api_keys ALTER COLUMN allow_list SET NOT NULL;
UPDATE api_keys SET
scopes = ARRAY[scope::api_key_scope],
allow_list = ARRAY['*:*'];

-- Drop legacy single-scope column
ALTER TABLE api_keys DROP COLUMN scope;
-- Enforce NOT NULL and drop legacy single-scope column
ALTER TABLE api_keys
ALTER COLUMN scopes SET NOT NULL,
ALTER COLUMN allow_list SET NOT NULL,
DROP COLUMN scope;