Subscribe

Talking to Postgres from Go with pgx and sqlc

Part 2 of the shorty series: Postgres from Go with pgx v5 and sqlc. Type-safe code generated from plain SQL, ON CONFLICT with pgx.ErrNoRows, connection pool settings, a deadlock-free batch transaction and goose migrations embedded in the binary.

Talking to Postgres from Go with pgx and sqlc

In the last part shorty got an HTTP API that talks to a LinkService interface. Nothing real was behind it yet. In this blog we will put Postgres behind it, using pgx as the driver and sqlc to generate type-safe Go code from plain SQL. We will also look at the connection pool settings, a transaction that writes click counts in a batch, and migrations embedded in the binary.

Level is intermediate. You should be fine with basic SQL and the Go from part 1. Versions I used: Go 1.27.3, pgx v5.13.0, sqlc v1.31.1, goose v3.30.1 and Postgres 18.7 in Docker.

Why sqlc

I wrote about ORMs vs query builders a few years ago. sqlc is a third option that I like more than both for small services. You write the SQL yourself, in .sql files. sqlc reads your schema and your queries, checks that the columns and types exist, and writes the Go functions and structs for you. If you rename a column and forget a query, sqlc generate fails, you find out before the code even compiles.

There is no runtime magic. The generated code is just pgx calls you could have written by hand. You can read it, and you can step into it with a debugger.

Installing sqlc

go install github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1
sqlc version

The Postgres parser inside sqlc is C code, so this needs cgo and a C compiler. On my Mac with the Xcode command line tools it just built. If you don't want a compiler around, there is an official image:

docker run --rm -v "$(pwd):/src" -w /src sqlc/sqlc:1.31.1 generate

The schema is the migrations

sqlc needs to know the tables. I didn't want a second copy of the schema, so sqlc reads the goose migration files directly. It understands the -- +goose Up and -- +goose Down markers and only uses the Up part.

migrations/00001_create_links.sql:

-- +goose Up
CREATE TABLE links (
    id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    code       TEXT        NOT NULL UNIQUE CHECK (length(code) BETWEEN 3 AND 32),
    url        TEXT        NOT NULL CHECK (length(url) <= 2048),
    clicks     BIGINT      NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- +goose Down
DROP TABLE links;

The UNIQUE on code creates the index that the redirect lookup uses, so there's no separate CREATE INDEX. If you want to know which other indexes are worth adding later, I went through that in Postgres index design.

The queries

queries/links.sql. The comment above each query gives the Go function name and what it returns.

-- name: CreateLink :one
-- ON CONFLICT DO NOTHING returns no row when the code is taken;
-- the Go side sees pgx.ErrNoRows and tries another code.
INSERT INTO links (code, url)
VALUES ($1, $2)
ON CONFLICT (code) DO NOTHING
RETURNING id, code, url, clicks, created_at;

-- name: GetLinkByCode :one
SELECT id, code, url, clicks, created_at
FROM links
WHERE code = $1;

-- name: AddClicks :exec
UPDATE links
SET clicks = clicks + sqlc.arg(delta)
WHERE code = sqlc.arg(code);

-- name: DeleteLink :execrows
DELETE FROM links
WHERE code = $1;

:one returns one row, :many a slice, :exec only an error and :execrows the number of affected rows. I use :execrows for delete so the service can tell "deleted" from "wasn't there" without a second query.

sqlc.arg(delta) gives the parameter a name. I tried the same UPDATE with plain $1 and $2 in a scratch folder, and sqlc named the first one after the column, so the struct got a field called Clicks that is really a delta. Somebody would pass the total there one day. Naming it makes the Go side read right.

sqlc.yaml

version: "2"
sql:
  - engine: postgresql
    schema: migrations
    queries: queries
    gen:
      go:
        package: db
        out: internal/db
        sql_package: pgx/v5
        emit_interface: true
        emit_json_tags: true
        json_tags_case_style: snake
        overrides:
          - db_type: timestamptz
            go_type: time.Time
        rename:
          url: URL

sql_package: pgx/v5 makes it generate code for pgx directly instead of database/sql. The override is there because with pgx/v5, sqlc maps timestamptz to pgtype.Timestamptz by default. That type can hold NULL and infinity, which my column never does (it is NOT NULL), so plain time.Time is nicer to work with.

The rename I actually added only after the first run. The generated struct had a field called Url. It compiles fine. But Go style is URL and the rest of my code already said URL, so it read wrong everywhere. One line in the config fixed it.

sqlc generate
ls internal/db
db.go       links.sql.go    models.go   querier.go

What comes out

The model:

type Link struct {
    ID        int64     `json:"id"`
    Code      string    `json:"code"`
    URL       string    `json:"url"`
    Clicks    int64     `json:"clicks"`
    CreatedAt time.Time `json:"created_at"`
}

And one of the functions. This is the whole thing, nothing hidden:

func (q *Queries) CreateLink(ctx context.Context, arg CreateLinkParams) (Link, error) {
    row := q.db.QueryRow(ctx, createLink, arg.Code, arg.URL)
    var i Link
    err := row.Scan(
        &i.ID,
        &i.Code,
        &i.URL,
        &i.Clicks,
        &i.CreatedAt,
    )
    return i, err
}

q.db is a small interface called DBTX with Exec, Query and QueryRow. A *pgxpool.Pool, a single *pgx.Conn and a pgx.Tx all satisfy it. That's what makes transactions easy later.

With emit_interface: true you also get a Querier interface listing every query. My service only needs three of them, so it declares its own smaller interface instead. A test fake then only has to implement three methods:

type Store interface {
    CreateLink(ctx context.Context, arg db.CreateLinkParams) (db.Link, error)
    GetLinkByCode(ctx context.Context, code string) (db.Link, error)
    DeleteLink(ctx context.Context, code string) (int64, error)
}

ON CONFLICT and pgx.ErrNoRows

When the random code already exists, ON CONFLICT DO NOTHING inserts nothing and RETURNING returns no row. pgx reports that from Scan as pgx.ErrNoRows. So "code taken" is not a special error type, it's just "no row":

l, err := s.store.CreateLink(ctx, db.CreateLinkParams{Code: code, URL: rawURL})
if errors.Is(err, pgx.ErrNoRows) {
    return db.Link{}, ErrCodeTaken
}

The other way to do it is a plain INSERT and checking for a unique violation, Postgres error code 23505, with errors.As into a *pgconn.PgError. That works too. I prefer ON CONFLICT here because a failed INSERT inside a transaction aborts the whole transaction, and DO NOTHING doesn't. For a single statement it doesn't matter, but it's a good habit.

The connection pool

See, this is the part people skip, then they wonder why database has hundreds of connections. Here is how shorty opens the pool:

pcfg, err := pgxpool.ParseConfig(cfg.DatabaseURL)
if err != nil {
    return nil, fmt.Errorf("DATABASE_URL: %w", err)
}
pcfg.MaxConns = cfg.DBMaxConns // DB_MAX_CONNS, default 10
pcfg.MinConns = 1
pcfg.MaxConnLifetime = 30 * time.Minute
pcfg.MaxConnIdleTime = 5 * time.Minute
pcfg.HealthCheckPeriod = 30 * time.Second

pool, err := pgxpool.NewWithConfig(ctx, pcfg)

If you set nothing, pgxpool uses 4 or the number of CPUs, whichever is bigger, for MaxConns. I looked it up in the v5.13.0 source itself to be sure. Inside a container that "number of CPUs" can be the host's count, not your limit, so I set it myself.

How to pick the number? Add it up: max conns per instance times the number of instances, plus migrations, plus you in psql at 2 am. That total has to stay under Postgres max_connections (100 by default). With 10 per instance, shorty can run about eight copies before that gets tight. A redirect query takes well under a millisecond, so 10 connections go a long way.

MaxConnLifetime makes the pool slowly replace old connections. That matters when the database moves behind a DNS name, like an RDS failover. MaxConnIdleTime gives connections back when traffic drops. You can also set all of these in the URL (?pool_max_conns=10), but I like them in code where I can see them.

pgxpool.NewWithConfig doesn't connect straight away. So main.go does a Ping with a 5 second timeout right after, and the process exits with a clear error if Postgres isn't there. Failing at startup is much better than failing on the first request.

A transaction for the click counts

From part 0: shorty counts clicks in memory and writes them every few seconds. Each flush is many UPDATEs, and I want them all or none. pgx.BeginFunc runs a function in a transaction, commits if it returns nil and rolls back if it returns an error:

func (p *PGClickSink) AddClicks(ctx context.Context, counts map[string]int64) error {
    // Sorted codes mean two shorty instances always lock rows in the same order,
    // so their flushes cannot deadlock each other.
    codes := make([]string, 0, len(counts))
    for code := range counts {
        codes = append(codes, code)
    }
    slices.Sort(codes)

    return pgx.BeginFunc(ctx, p.pool, func(tx pgx.Tx) error {
        q := db.New(tx)
        for _, code := range codes {
            if err := q.AddClicks(ctx, db.AddClicksParams{Code: code, Delta: counts[code]}); err != nil {
                return err
            }
        }
        return nil
    })
}

db.New(tx) works because pgx.Tx satisfies DBTX. sqlc also generates q.WithTx(tx) if you already have a Queries value, it does the same thing.

The sort is the interesting line. Now what happens is, Go map order is random. Say instance A has clicks for blog and pgx, and instance B has the same two. If A updates blog then pgx, and B does pgx then blog, each can end up holding one row lock and waiting for the other. Postgres detects that, kills one of them with a deadlock error, and those clicks wait for the next flush. Sorting the codes means everyone takes locks in the same order, so it can't happen.

If you prefer to see the steps, this is the long form of the same thing:

tx, err := pool.Begin(ctx)
if err != nil {
    return err
}
defer tx.Rollback(ctx) // no-op after a successful Commit

q := db.New(tx)
// ... queries ...
return tx.Commit(ctx)

When the flush fails, the counter puts the counts back in its map so the next flush tries again. There is a unit test for that with a sink that fails once.

Migrations in the binary

I want one image that can both serve and migrate, so the migrations are embedded with go:embed and goose runs them from inside the binary:

//go:embed *.sql
var FS embed.FS
sqlDB, err := sql.Open("pgx", dsn) // database/sql driver from github.com/jackc/pgx/v5/stdlib
if err != nil {
    return err
}
defer sqlDB.Close()

p, err := goose.NewProvider(goose.DialectPostgres, sqlDB, migrations.FS)
if err != nil {
    return err
}
res, err := p.Up(ctx)

goose wants a database/sql handle, which is why this opens one through pgx's stdlib package instead of using the pool. Running shorty migrate up against an empty database printed:

OK    up 00001_create_links.sql (5.05ms)

The same command will run as a one-off task later in the series, the way I described in running goose migrations as a one-off ECS task.

Testing against a real Postgres

Unit tests use a map-backed fake of Store. The fake returns pgx.ErrNoRows for a missing code, same as the real thing, so the service code doesn't know the difference. But the fake can't tell me if the SQL is right, or if the flush really doesn't deadlock. For that there is one test that needs a real database and skips itself otherwise:

func TestPostgres(t *testing.T) {
    dsn := os.Getenv("SHORTY_TEST_DATABASE_URL")
    if dsn == "" {
        t.Skip("SHORTY_TEST_DATABASE_URL not set")
    }
    // ... run migrations, create a link, insert the same code again (want ErrCodeTaken) ...

    // Two flushers at once, like two shorty containers, must not deadlock or lose counts.
    sink := NewPGClickSink(pool)
    var wg sync.WaitGroup
    for range 2 {
        wg.Go(func() {
            for range 10 {
                if err := sink.AddClicks(ctx, map[string]int64{code: 1}); err != nil {
                    t.Error(err)
                }
            }
        })
    }
    wg.Wait()
    // ... then check clicks == 20
}

sync.WaitGroup.Go is new in Go 1.25 and saves the Add(1) and defer Done() dance. I ran it against Postgres 18.7 in Docker (the compose setup is the next part):

SHORTY_TEST_DATABASE_URL='postgres://shorty:shorty@localhost:5432/shorty?sslmode=disable' \
  go test -count=1 -run TestPostgres -v ./internal/links/
=== RUN   TestPostgres
--- PASS: TestPostgres (1.19s)
PASS

20 clicks from 20 single-click flushes running on two goroutines, no deadlock. -count=1 stops Go from caching the result, since the test depends on something outside the code.

If you need TLS to Postgres, the DSN takes sslmode=verify-full and pgx handles the rest. I wrote about the older way of doing it in connecting to postgres using ssl.

Next part puts all of this into Docker Compose with Postgres, Redis and a one-shot migration step, so docker compose up gives you the whole stack.