# Migrate From lib/pq to pgx in a Go API

Yes. An agent swaps lib/pq for pgx's database/sql driver, finds the connection and error differences by running the tests, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-lib-pq-to-pgx/lib-pq/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent first checks how deep the driver goes. In an API like TomFern/go-mux-api it is shallow: `app.go` has the blank import `_ "github.com/lib/pq"` and one `sql.Open("postgres", ...)`, and `model.go` holds five queries written against `*sql.DB` with `$1` placeholders. Nothing imports `pq.Error`, `pq.Array`, `pq.CopyIn` or the listener. That decides the shape of the change: keep `database/sql` and register pgx through `github.com/jackc/pgx/v5/stdlib` under the driver name `pgx`, so the queries and the `sql.ErrNoRows` branch in `getProduct` stay as they are. Moving to pgx's own pool and row types is a second step the agent names but does not take.

It installs PostgreSQL in the sandbox, sets a password for the test role and runs the six tests in `main_test.go` on the unchanged code, which pass. Then it changes the import and the driver name and runs them again without touching the connection string. They fail before the first test with `failed to connect ... /var/run/postgresql/.s.PGSQL.5432 ... Peer authentication failed for user "postgres"`. `Initialize` builds `user=%s password=%s dbname=%s sslmode=disable` with no host. lib/pq fills in `localhost` and connects over TCP. pgx looks for a Unix socket directory first and uses it when one exists, which on a host that runs PostgreSQL locally means a different authentication rule. Adding `host=localhost` to the string restores the old path, and the six tests pass.

Next it compares what the application hands to its callers. Five handlers in `app.go` put `err.Error()` into a 500 response, so driver error text reaches clients. A duplicate key is `pq: duplicate key value violates unique constraint "products_pkey"` on lib/pq and `ERROR: duplicate key value violates unique constraint "products_pkey" (SQLSTATE 23505)` on pgx, where the error type is `*pgconn.PgError`. A `NUMERIC(10,2)` column scanned into `interface{}` arrives as `[]uint8` from lib/pq and as `string` from pgx. Scanned into the `float64` field of `product`, as this code does, both give 11.22.

The dependency side has the largest effect. `go get github.com/jackc/pgx/v5` installed v5.12.0 when this page was written and moved the `go` line in `go.mod` from 1.16 to 1.25.0, because pgx supports the two most recent Go releases. The repository's `.semaphore/semaphore.yml` selects `sem-version go 1.16` in four places on an `ubuntu1804` image. The agent updates those lines and says plainly that the migration is also a toolchain upgrade. If your build cannot move that far, say so in the prompt and name the Go version you have, and the agent pins an older pgx v5 release that still compiles on it.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Move this Go service from github.com/lib/pq to pgx v5 through its database/sql driver, github.com/jackc/pgx/v5/stdlib. Read go.mod, every file that imports lib/pq or calls sql.Open, every query, the tests and the CI configuration. List any use of pq-specific API (pq.Error, pq.Array, pq.CopyIn, the listener, pq.NullTime); if there is one, show its pgx replacement before editing. There is no Docker here: install PostgreSQL with apt, start it, give the test role a password and export the variables the tests read. Run go test ./... on the unchanged code and keep the output. Change the import and the driver name only, run the tests again without changing the connection string, and report exactly what happens. Fix the connection string so it reaches the same server the same way as before. Then write a short test that prints, on both drivers, the type and text of a unique-violation error and the Go type a NUMERIC column scans to in an interface value, and list every place the code returns driver error text to a client. Report the go directive before and after go get, and update every CI or image file that pins an older Go. Run go mod tidy and go vet. Do not rewrite queries to the native pgx API. Open a pull request with every command and its output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that changes two lines of `app.go` plus the connection string, `go.mod`, `go.sum` and the CI file. The description shows the six tests passing on lib/pq, failing on pgx with the socket error, and passing once the host is explicit. It includes the comparison of error type and text for the two drivers, the list of handlers that return that text, and the `go` directive before and after with the pgx version that set it.

A reviewer checks three things. The connection string in every environment, since the same change that broke the test run applies to any deployment whose string has no host. The clients or log filters that match on the `pq:` prefix. And the Go version, which the pull request raises in CI but which also has to be true of the image that builds the release. The description lists what was left for a follow-up: `pgxpool`, `pgx.CollectRows` and typed errors through `errors.As` with `*pgconn.PgError`.

## Run it on every Linear issue labelled database

A driver change is usually planned as an issue per service. Connect Linear under Settings → Connections and add an automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label you use for this work. Save the prompt above as the automation's prompt. The issue text is appended after it as event data, and the prompt remains the only instruction, so anything specific to one service belongs in the prompt or in the repository.

A Linear trigger needs a Linear connection for the member the automation runs as, and it fires only when someone in your Rush org adds the label. Each labelled issue starts one run in the Project's repository and ends as one pull request.

## Why run it on Rush?

The failure that matters in this migration appears only when the new driver meets a real server. The code compiles, the diff is two lines, and the first connection goes to a socket the old driver never used. A run on Rush has a PostgreSQL of its own to find that against, installed for this task in the run's sandbox, and the failing output is kept beside the passing one.

The same is true of the toolchain. That one `go get` moves the module nine minor Go versions forward is a fact about the resolved dependency, printed by the command. The agent reports it with the files that pin the old version, so the decision to upgrade Go is made in review and not discovered by a red build.

## Frequently asked questions

### Is lib/pq deprecated?

No. It is maintained and had a release, v1.12.3, in April 2026. Teams move to pgx for what it adds: its own connection pool, a native interface with typed rows, `COPY` support and richer error values. If none of that matters to you, staying on lib/pq is a reasonable choice.

### Do my queries need to change?

Not when you stay on `database/sql`. Both drivers use `$1` style placeholders, and `sql.ErrNoRows`, transactions and `Scan` behave the same. A statement that holds several commands and takes parameters is refused by both with `cannot insert multiple commands into a prepared statement`.

### Why did the connection fail when only the driver changed?

Because the string names no host. lib/pq then connects to `localhost` over TCP, and pgx prefers a Unix socket in `/var/run/postgresql` when that directory exists. The server applies a different authentication rule to each, so a password that works on one is never asked for on the other.

### Can the agent go all the way to the native pgx interface?

Yes, as a second pull request. That one replaces `*sql.DB` with `*pgxpool.Pool` in every function signature and changes how rows are read, so it touches each query. Doing the driver swap first keeps the behaviour changes of each step small enough to review.

## More jobs like this: Turn a Linear label into a PR

- [Migrate From Logrus to log/slog in a Go CLI](https://getrush.ai/run/migrate-logrus-to-slog/logrus/)
- [Migrate mkdirp to fs.mkdir with recursive: true](https://getrush.ai/run/migrate-mkdirp-to-fs-mkdir/mkdirp/)
- [Replace Moment.js With Day.js in an Express API](https://getrush.ai/run/migrate-moment-to-dayjs/moment/)
- [Replace pytz With zoneinfo in a Python Scraper](https://getrush.ai/run/migrate-pytz-to-zoneinfo/pytz/)
- [Migrate From querystring to URLSearchParams in a Node.js API Client](https://getrush.ai/run/migrate-querystring-to-urlsearchparams/querystring/)
- [Migrate From Requests to HTTPX in a Python Project](https://getrush.ai/run/migrate-requests-to-httpx/requests/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
