fix(storage): stop locking PostgreSQL tables at startup for columns that already exist
Every store constructor runs its column migrations on every start. On PostgreSQL that meant 72 ALTER TABLE … ADD COLUMN IF NOT EXISTS statements per start (19 on usage, 15 on audit_logs), and PostgreSQL takes an ACCESS EXCLUSIVE lock for each one even when the column already exists. An ALTER that is waiting for its lock also blocks every later query on the table. So during a rolling restart, one long query (hourly retention DELETE, dashboard aggregation, concurrent index build) stalled all usage and audit traffic on every replica behind the new replica's no-op ALTERs.
sqlx.AddColumns now reads each table's columns once (information_schema.columns scoped to current_schema()) and runs only the ALTERs for missing columns. A restart against an up-to-date schema now issues no ALTER TABLE at all. A missing column (fresh install, upgrade) is still added as before. IF NOT EXISTS and the duplicate-column tolerance stay, so replicas starting at the same time still race safely. SQLite uses the same path.
Measured on PostgreSQL 14 with the real usage store: a 5 s query is open on usage, a replica runs its startup schema, then a dashboard SELECT count(*) FROM usage and an INSERT arrive.
| replica startup | SELECT waited | INSERT waited | |
|---|---|---|---|
| before | 4.5–5.8 s | 3.99–4.02 s | 0.00–1.16 s |
| after | 0.01–0.02 s | 0.00–0.02 s | 0.00–0.01 s |
For reviewers:
AddColumnsstill takes raw SQL strings. The table and column come fromstrings.Fieldson the fixedALTER TABLE <t> ADD COLUMN [IF NOT EXISTS] <c>shape that all 72 statements use. This keeps the 12 stores unchanged. Any statement that doesn't match that shape (quoted or schema-qualified names, anything else) still runs unconditionally, so a parse miss can only cost a lock, never skip a migration.auditlog's privateauditColumnsmoved into sqlx assqlx.Columns(same query), soAddColumnsand the audit-log rename share one implementation.budget,ratelimitandvirtualmodelsstill carry their own copies of the query. Moving them is left for a follow-up, becauseratelimitis touched by an open PR.- A statement containing a comma (several actions, or a type like
NUMERIC(10,2)) is not parsed and always runs, so a multi-action ALTER can never be skipped based on its first column. None of today's migrations contains one. - Tests: a table-driven parser test, a table-driven conformance test on both dialects that records which ALTERs run, and a usage-store test showing that a second start issues zero ALTERs and that a dropped column is added back.