Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion .github/workflows/wicked.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
- uses: actions/checkout@v6
with:
repository: Stumble/bookstore
ref: 2a7f7e396451821a8fe3054eb265037b830af68d
ref: 89b3fbc09bf274e563722c3f582f5c3ac4bca3ec
path: bookstore
- name: Check generated API and code
working-directory: bookstore
Expand Down
31 changes: 27 additions & 4 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,26 @@ ERROR: orders/GetOrderByID does not have a timeout option
ERROR: *pkg*/*name* does not have a timeout option
```

The `timeout` is the query's database timeout: it bounds how long the query
holds a database connection, not how long it waits for one. Generated code
passes it to `wpgx.WithDBTimeout`, so it requires a wpgx release with that
function. At run time:

- On a pool connection the query first waits for a connection, at most the
larger of `timeout` and the pool's `AcquireTimeout` (wpgx default 2s).
- The `timeout` starts once the query has a connection, or at the call inside a
transaction, and covers reading its rows (an `each` visitor included).
- Cache lookups are bounded by the Redis client's own timeouts, with dcache
v0.3.0+ and Redis single flight off (its default). With Redis single flight,
an unresponsive Redis is retried until the caller's context ends, so callers
need a deadline.
- The caller's context deadline and cancellation always apply.

Errors match `wpgx.ErrAcquireTimeout` or `wpgx.ErrDBTimeout`, and
`context.DeadlineExceeded`. Before this release the `timeout` started when the
method was called and also covered the cache lookup and the wait for a
connection.

Here is an example of listing all books of a category, with using id
as the cursor for pagination.

Expand Down Expand Up @@ -471,9 +491,10 @@ the original `Querier` method set stays the same. `each: false` disables a
companion. The new annotation requires a generator release supporting it.

The consumer is synchronous, holds the connection, and runs under the query
context/deadline. It must respect that context and cannot reenter the same
active transaction connection. Normal stop, error and panic close/drain rows
before the query's own context is cancelled. A drain failure after normal stop
context, which carries the database timeout once the query has a connection.
It must respect that context and cannot reenter the same active transaction
connection. Normal stop, error and panic close/drain rows before the query's
own context is cancelled. A drain failure after normal stop
is returned; a prior callback/scan error remains primary. Panic propagates after
cleanup. To stop receiving remaining data, cancel a caller-created context
scoped to this query. Explicit cancellation or timeout may close the physical
Expand Down Expand Up @@ -906,7 +927,9 @@ The code of wpgx is very simple, the best way to understand it is to read its so

+ {appName}_wpgx_conn_pool{name="max_conns/total_conns/...."}: connection pool gauges.
+ {appName}_wpgx_request_total{name="$queryName"}: number of DB hits for each query.
+ {appName}_wpgx_latency_milliseconds{name="$queryName"}: histogram of SQL execution duration.
+ {appName}_wpgx_latency_milliseconds{name="$queryName"}: histogram of the whole call, including the wait for a connection.
+ wpgx_acquire_wait_milliseconds, wpgx_db_latency_milliseconds and wpgx_timeout_total split
the wait for a connection from database time; see the wpgx README.

### Open Telemetry

Expand Down
124 changes: 124 additions & 0 deletions docs/changelogs/2026-11-20-db-timeout-after-acquire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# feat: pass query timeouts to wpgx as database timeouts

Local record. The complete design, decisions and risks are in the primary
record, Stumble/wpgx `docs/changelogs/2026-11-20-db-timeout-after-acquire.md`.

## 1. Background and Current State

- Every wicked query requires `-- -- timeout: T`. Generated methods start
`context.WithTimeout(ctx, T)` at the top, so T also covers the dcache lookup
and the wait for a pooled connection (`queryCode.tmpl`, `copyfromCopy.tmpl`).
- The opt-in Each companion (v2.5.0) runs the visitor under that context and
checks it after each row and after closing.
- Fixtures under `internal/endtoend/testdata` compile against wpgx v0.3.1; the
`wicked` CI job regenerates Stumble/bookstore at a pinned commit and requires
no diff, then runs its runtime contracts.

## 2. Problem Model and End-to-End Behavior

- B1 — Every generated method (`:one`, `:many`, `:exec`, `:execrows`,
`:execresult`, `:copyfrom`, Each) passes T to
`wpgx.WithDBTimeout(ctx, "<unique label>", T)` instead of starting its own
deadline. wpgx starts T once the statement has a connection (B1/B2 of the
primary record). Annotation syntax, validation and method signatures are
unchanged.
- B2 — dcache receives the caller's context (plus the timeout value), so cache
lookups and fills are bounded by the Redis client's timeouts, not by T.
- B3 — Each visitors receive the statement context from wpgx rows (falling
back to the method context; `qctx` is reassigned, so no new local name can
collide with a SQL parameter). Each reports through `wpgx.StatementErr`: an
ended statement context, a visitor's error that is that context's deadline,
and, after closing the rows, a database timeout that expired while reading or
draining buffered rows all match `wpgx.ErrDBTimeout` (as the previous Each
failed when its query context expired). Other visitor and row errors stay
primary; the caller's context is checked last.
- B4 — Generated files import `github.com/stumble/wpgx`; regenerated code
needs a wpgx release with `WithDBTimeout` (compile-time check).
- F1 — Missing timeouts still fail generation.
- F2 — A SQL parameter named `wpgx` is generated as `wpgx_` (reserved), so it
cannot shadow the package the method bodies now call.
- B2 precondition: the Redis-client bound holds with dcache v0.3.0+ and Redis
single flight off (default); see R6 of the primary record.
- Compatibility: regenerating changes generated code by design (owner chose
the new semantics as the default of this minor release). Old generated code
keeps working with new wpgx.

## 3. Research, Findings, and Architecture Decision

See the primary record (D1–D5, R1–R5). Local decisions:

- D6 — Keep the template variable `qctx` so the diff stays small and
readable; it now carries only the timeout value.
- D7 — Each discovers the statement context through an anonymous
`interface{ Context() context.Context }` assertion, so fake queriers in
tests keep working and no new exported API is needed in generated code.

## 4. Implementation Design

- `internal/codegen/wicked/templates/wpgx/queryCode.tmpl`: replace the five
`context.WithTimeout` blocks and the Each body.
- `internal/codegen/wicked/templates/wpgx/copyfromCopy.tmpl`: same for
`:copyfrom`.
- `internal/codegen/wicked/imports.go`: import wpgx in query and copyfrom files.
- Regenerate `internal/endtoend/testdata/wicked_*` and bump the testdata
module's wpgx; update the Each runtime contract tests; add a PostgreSQL
runtime check for the timeout boundary next to the existing optional Each
check.
- `.github/workflows/wicked.yml`: point the bookstore job at the bookstore
commit regenerated with this change.
- `GUIDE.md`: document the timeout semantics.

### Serial Implementation Checklist

- [x] Templates and imports.
- [x] Regenerate fixtures; bump the testdata wpgx; update/add runtime tests.
- [x] Guide.
- [x] Bookstore pin (commit 89b3fbc, published with this branch).

## 5. Verification and E2E Design

E2E Required: no.

Commands (repository root, GOMAXPROCS=2, GOWORK=off unless noted):

- `go build -p=1 -ldflags "-X github.com/sqlc-dev/sqlc/internal/info.Version=v2.4.0-dev-wicked-fork" -o ../sqlc-new ./cmd/sqlc` (as CI's `make build COMMIT_HASH=v2.4.0-dev`) and a default-version build for fixtures.
- `go test -p=1 -count=1 ./internal/codegen/wicked ./internal/cmd`.
- `go test -p=1 -count=1 -run 'TestReplay/base/wicked' ./internal/endtoend`.
- In `internal/endtoend/testdata`: `go build ./...` (`make build-endtoend`) and
`go test ./wicked_compat/go`, plus the PostgreSQL checks with
`SQLC_EACH_TEST_DSN`.
- Bookstore: `make sqlc`, `make sqlc-verify`, `git diff --exit-code -- pkg/repos`,
`go test -race -count=1 -p 1 ./pkg/usecases`.

## 6. Human Decisions and Interaction

See the primary record, section 6.

## 7. Outcome and Evidence

- Result: B1–B4 and F1–F2 as specified; generated code requires wpgx with
`WithDBTimeout`/`StatementErr` (pinned to the wpgx branch commit
`v0.5.2-0.20261120053742-4b29cac2136d` in the testdata module until tagged).
- Deviations (reviewed): Each reassigns `qctx` instead of declaring `vctx`
(R1-05); `wpgx` is a reserved identifier; Each reports through
`wpgx.StatementErr` (R2-02). The testdata module was already not tidy at the
base, so only `go get` was applied.
- Verification on the final content (`GOMAXPROCS=2`, `-p 1`):
- Builds: `go build -p=1 -ldflags "-X github.com/sqlc-dev/sqlc/internal/info.Version=v2.4.0-dev-wicked-fork" -o ../sqlc-new ./cmd/sqlc` and the default-label `../sqlc-fixture`; fixtures regenerated with the latter.
- `GOWORK=off go test -p=1 -count=1 ./internal/codegen/wicked ./internal/cmd`: pass.
- `GOWORK=off go test -p=1 -count=1 -run 'TestReplay/base/' ./internal/endtoend` with this repository's `sqlc-gen-json` on PATH: pass (a stale `~/go/bin/sqlc-gen-json` from another build fails `process_plugin_sqlc_gen_json` independently of this change); `-run 'TestReplay/base/wicked'`: pass.
- `internal/endtoend/testdata` with `GOWORK=off CGO_ENABLED=0`: `go build ./...` pass; `SQLC_EACH_TEST_DSN=postgres://…@127.0.0.1:55491/sqlc_test go test -race -count=1 ./wicked_compat/go`: pass, including `TestGeneratedTimeoutPostgres` (5 subtests) and `TestGeneratedEachPostgres`.
- Mutation checks: the v2.5.0 generated Each fixture fails the timeout test; reverting the two `StatementErr` lines fails both new Each regressions.
- Wicked CI bookstore job reproduced on a clean clone of bookstore 89b3fbc: regenerate, `sqlc diff`, no diff, build.
- Cross-agent review: primary record section 7 (Codex session
`5e2002b6-dea5-4c53-96c9-cde8cdd6a84b`, rounds 1–5, final ACCEPT of
5291d2071 with wpgx 4b29cac and bookstore 89b3fbc). Later changes here are
record-only.
- Not run locally: the full CI suite (`go test --tags=examples ./...` needs
MySQL and PostgreSQL services); CI runs it.

## 8. Remaining Work

- Before merge: after wpgx is tagged and the bookstore PR merged, bump the
testdata wpgx pin to the tag and point `.github/workflows/wicked.yml` at the
merged bookstore commit; then tag a new sqlc minor.
3 changes: 3 additions & 0 deletions internal/codegen/wicked/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,8 @@ func (i *importer) queryImports(filename string) fileImports {
}
}
pkg[ImportSpec{Path: "github.com/rs/zerolog/log"}] = struct{}{}
// Generated methods pass their timeout to wpgx.WithDBTimeout.
pkg[ImportSpec{Path: "github.com/stumble/wpgx"}] = struct{}{}
return sortedImports(std, pkg)
}

Expand Down Expand Up @@ -421,6 +423,7 @@ func (i *importer) copyfromImports() fileImports {

std["context"] = struct{}{}
std["time"] = struct{}{}
pkg[ImportSpec{Path: "github.com/stumble/wpgx"}] = struct{}{}
if i.Options.SqlDriver == opts.SQLDriverGoSQLDriverMySQL {
std["io"] = struct{}{}
std["fmt"] = struct{}{}
Expand Down
11 changes: 11 additions & 0 deletions internal/codegen/wicked/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,14 @@ func TestEachVisitorNames(t *testing.T) {
}
}
}

func TestGeneratedPackageNamesAreReserved(t *testing.T) {
// Generated method bodies call the wpgx package, so a parameter must not
// shadow it.
if got := escape("wpgx"); got != "wpgx_" {
t.Fatalf("escape(wpgx)=%s", got)
}
if got := escape("vctx"); got != "vctx" {
t.Fatalf("escape(vctx)=%s", got)
}
}
3 changes: 3 additions & 0 deletions internal/codegen/wicked/reserved.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ func IsReserved(s string) bool {
return true
case "q":
return true
case "wpgx":
// Generated methods call the wpgx package.
return true
default:
return false
}
Expand Down
3 changes: 1 addition & 2 deletions internal/codegen/wicked/templates/wpgx/copyfromCopy.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ func (r iteratorFor{{.MethodName}}) Err() error {
{{end -}}
func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.SlicePair}}) (int64, error) {
{{- if gt .Option.Timeout.Milliseconds 0 }}
ctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
ctx = wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
q.db.CountIntent("{{.UniqueLabel}}")
return q.db.WCopyFrom(ctx, "{{.UniqueLabel}}", {{.TableIdentifierAsGoSlice}}, {{.Arg.ColumnNamesAsGoSlice}}, &iteratorFor{{.MethodName}}{rows: {{.Arg.Name}}})
Expand Down
39 changes: 20 additions & 19 deletions internal/codegen/wicked/templates/wpgx/queryCode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ func (q *ReadOnlyQueries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}}) (*

func _{{.MethodName}}(ctx context.Context, q {{.ConnType}}, {{.Arg.Pair}} {{.InvalidateArgs}}) (*{{.Ret.Type}}, error) {
{{- if gt .Option.Timeout.Milliseconds 0 }}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
{{- if .CountIntent }}
q.GetConn().CountIntent("{{.UniqueLabel}}")
Expand Down Expand Up @@ -138,8 +137,7 @@ func (q *ReadOnlyQueries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}}) ([

func _{{.MethodName}}(ctx context.Context, q {{.ConnType}}, {{.Arg.Pair}} {{.InvalidateArgs}}) ([]{{.Ret.Type}}, error) {
{{- if gt .Option.Timeout.Milliseconds 0 }}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
{{- if .CountIntent }}
q.GetConn().CountIntent("{{.UniqueLabel}}")
Expand Down Expand Up @@ -233,7 +231,8 @@ func _{{.MethodName}}(ctx context.Context, q {{.ConnType}}, {{.Arg.Pair}} {{.Inv
// It directly queries the DB, bypassing the slice method's result cache.
// Return true to continue or false to stop the whole read; to skip a row,
// omit its output and return true. Errors are returned after rows are closed.
// The query timeout covers the synchronous visitor and draining. The visitor
// The query's database timeout starts once it has a connection and covers the
// synchronous visitor and draining; the visitor's ctx carries it. The visitor
// must respect ctx and must not query again on the same active connection.
// Normal stop and visitor error drain by default; cancel a query-specific
// caller context to abort transfer, which may invalidate its connection/tx.
Expand All @@ -252,28 +251,33 @@ func _{{.MethodName}}Each(ctx context.Context, q CacheQuerierConn, {{if .Arg.Pai
if {{.EachVisitName}} == nil {
return fmt.Errorf("{{.MethodName}}Each: nil visitor")
}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{if .CountIntent}}q.GetConn().CountIntent("{{.UniqueLabel}}"){{end}}
rows, err := q.GetConn().WQuery(qctx, "{{.UniqueLabel}}", {{.ConstantName}}, {{.Arg.Params}})
if err != nil {
return err
}
defer rows.Close()
// wpgx rows carry the statement context and its database timeout.
if sc, ok := rows.(interface{ Context() context.Context }); ok {
qctx = sc.Context()
}
for rows.Next() {
if err := qctx.Err(); err != nil { return err }
if err := wpgx.StatementErr(qctx, qctx.Err()); err != nil { return err }
var eachRow *{{.Ret.Type}} = new({{.Ret.Type}})
if err := rows.Scan({{.EachScan}}); err != nil { return err }
more, err := {{.EachVisitName}}(qctx, *eachRow)
if err != nil { return err }
if err := qctx.Err(); err != nil { return err }
if err != nil { return wpgx.StatementErr(qctx, err) }
if err := wpgx.StatementErr(qctx, qctx.Err()); err != nil { return err }
if !more { break }
}
// Close may drain pending results and surface a server error after a
// successful early stop. It must run before checking Err and cancelling.
// successful early stop. It must run before checking Err. StatementErr
// also reports a database timeout that expired while reading or draining
// buffered rows, but not the cancellation that closing causes.
rows.Close()
if err := rows.Err(); err != nil { return err }
return qctx.Err()
if err := wpgx.StatementErr(qctx, rows.Err()); err != nil { return err }
return ctx.Err()
}
{{end}}
{{end}}
Expand All @@ -283,8 +287,7 @@ func _{{.MethodName}}Each(ctx context.Context, q CacheQuerierConn, {{if .Arg.Pai
{{end -}}
func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}} {{.InvalidateArgs}}) error {
{{- if gt .Option.Timeout.Milliseconds 0 }}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
_, err := q.db.WExec(qctx, "{{.UniqueLabel}}", {{.ConstantName}}, {{.Arg.Params}})
if err != nil {
Expand Down Expand Up @@ -331,8 +334,7 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}} {{.Invalida
{{end -}}
func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}} {{.InvalidateArgs}}) (int64, error) {
{{- if gt .Option.Timeout.Milliseconds 0 }}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
result, err := q.db.WExec(qctx, "{{.UniqueLabel}}", {{.ConstantName}}, {{.Arg.Params}})
if err != nil {
Expand Down Expand Up @@ -379,8 +381,7 @@ func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}} {{.Invalida
{{end -}}
func (q *Queries) {{.MethodName}}(ctx context.Context, {{.Arg.Pair}} {{.InvalidateArgs}}) (pgconn.CommandTag, error) {
{{- if gt .Option.Timeout.Milliseconds 0 }}
qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}})
defer cancel()
qctx := wpgx.WithDBTimeout(ctx, "{{.UniqueLabel}}", time.Millisecond * {{.Option.Timeout.Milliseconds}})
{{- end}}
rv, err := q.db.WExec(qctx, "{{.UniqueLabel}}", {{.ConstantName}}, {{.Arg.Params}})
if err != nil {
Expand Down
Loading
Loading