Migrate from lib/pq to pgx to fix context cancellation data race #18492
+908
−200
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #6201
This PR migrates the Coder codebase from the
lib/pq
PostgreSQL driver topgx
to address data race issues with context cancellation and improve overall database performance.Problem
The
lib/pq
library has a longstanding issue with data races during context cancellation (lib/pq#1021), which can cause instability in applications that heavily use contexts like Coder. Additionally,lib/pq
is in maintenance mode and not actively developed.Solution
Migrate to
pgx
, which:Changes Made
Core Database Layer
pq.Error
topgconn.PgError
pq.Array()
calls with direct Go slice usage (pgx handles this automatically)LISTEN/NOTIFY (PubSub)
pq.Listener
with custompgxListenerShim
usingpgx.Conn.WaitForNotification()
Extra
toPayload
forpgconn.Notification
Dependencies
github.com/jackc/pgx/v5
andgithub.com/jackc/pgx/v5/stdlib
github.com/lib/pq
dependency and custom replace directivegithub.com/jackc/pgx/v5/stdlib
fordatabase/sql
compatibilityTesting
Benefits
lib/pq
due do data race in context cancellation #6201Migration Notes
This is a significant but necessary change that touches the core database layer. The migration maintains full compatibility with existing database operations while providing the benefits of the more modern pgx driver.
The most complex part was migrating the pubsub LISTEN/NOTIFY implementation, which required a complete rewrite due to the different APIs between lib/pq and pgx. The new implementation is simpler and more robust.