diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d5be38468b..d818b7c167 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - name: install ./... run: go build ./... env: diff --git a/.github/workflows/ci-kotlin.yml b/.github/workflows/ci-kotlin.yml index 06db4b29ea..8b2d75c8a2 100644 --- a/.github/workflows/ci-kotlin.yml +++ b/.github/workflows/ci-kotlin.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - name: install ./... run: go install ./... - uses: actions/checkout@v6 diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml index 6f8d4676bd..60e9ab613f 100644 --- a/.github/workflows/ci-python.yml +++ b/.github/workflows/ci-python.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - name: install ./... run: go install ./... - uses: actions/checkout@v6 diff --git a/.github/workflows/ci-typescript.yml b/.github/workflows/ci-typescript.yml index 1b72174230..cc4017cf91 100644 --- a/.github/workflows/ci-typescript.yml +++ b/.github/workflows/ci-typescript.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - name: install ./... run: go install ./... - uses: actions/checkout@v6 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e592ddfae9..0409a30373 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - run: go build ./... env: CGO_ENABLED: "0" @@ -28,7 +28,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: - go-version: '1.26.10' + go-version: '1.26.11' - name: install gotestsum run: go install gotest.tools/gotestsum@latest @@ -73,4 +73,4 @@ jobs: steps: - uses: golang/govulncheck-action@v1 with: - go-version-input: '1.26.10' + go-version-input: '1.26.11' diff --git a/GUIDE.md b/GUIDE.md index 03a7469981..b1152466e7 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -405,7 +405,7 @@ ORDER BY LIMIT @first; ``` -This wicked forked sqlc adds 3 abilities to query: cache, timeout and invalidate. +This wicked fork supports cache, timeout, invalidation and opt-in row consumers. Options are written as `-- -- key: value` comments above each query. sqlc passes them through its standard query comments, and the wicked backend parses and @@ -426,6 +426,68 @@ Btw, this syntax looks very similar as passing arguments to the underlying scrip npm run server -- --port=8080 // invokes `run server script with --port=8080` ``` +#### Consume rows with Each + +Enable a companion on a read-only `:many` query: + +```sql +-- name: ListBooks :many +-- -- timeout: 1s +-- -- each: true +SELECT * FROM books WHERE id >= @min_id ORDER BY id; +``` + +The existing `ListBooks` method still collects its result slice. The new +`ListBooksEach` method takes a typed consumer and returns the final error: + +```go +err := queries.ListBooksEach(ctx, minID, + func(ctx context.Context, book Book) (bool, error) { + if err := ctx.Err(); err != nil { + return false, err + } + if shouldSkip(book) { + return true, nil + } + if err := consume(book); err != nil { + return false, err + } + return true, nil + }) +``` + +Return `true, nil` to continue. Return `false, nil` to stop the entire read +successfully. To filter one row, omit its output and continue. A non-nil error +ends consumption and is returned after cleanup. No result slice is collected +by Each; application collectors should discard their local partial result on +error when they require all-or-nothing output. + +Each directly queries the selected DB connection, bypassing result-cache reads, +writes and singleflight, even if the slice method has a cache annotation. +Timeout, CountIntent and connection/transaction/replica routing still apply. +ReadOnlyQueries gets the companion only when replica access is allowed. +When `emit_interface` is enabled, companions are in a separate `EachQuerier`; +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 +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 +connection and invalidate its transaction. Borrowing/custom codecs retain their +own field-lifetime rules. + +Each is generated for SELECT reads, rejecting visible data-changing CTEs, +unsupported CTE statements and SELECT INTO. This syntactic check does not prove +absence of function side effects. Locking SELECTs follow the existing declared +routing and transaction rules; draining can still acquire locks for remaining +rows. Each does not bound the current row's receive or decode allocation. Keep +SQL-level single-value protections where required, and implement request policy +and domain errors in the consumer. + #### Cache Cache accepts a [Go time.Duration format](https://pkg.go.dev/maze.io/x/duration#ParseDuration) as the diff --git a/docs/changelogs/2026-11-11-add-many-each.md b/docs/changelogs/2026-11-11-add-many-each.md new file mode 100644 index 0000000000..3a666d2e75 --- /dev/null +++ b/docs/changelogs/2026-11-11-add-many-each.md @@ -0,0 +1,401 @@ +# feat: generate opt-in Each companions for many reads + +## 1. Background and Current State + +Wicked `:many` methods collect every row before returning. Downstream Go +services with variable-width records consequently maintain handwritten SQL +iteration to enforce request policies. A row-count limit alone cannot bound +the result size. Six existing downstream reads motivate the companion API; +consumer migration remains a separate follow-up after a generator release. + +Current source is sqlc main e0d9cae. The wicked backend owns comment options, +row types, collectors, caching and Dump/Load. Wpgx already exposes pgx.Rows. +Top-level SELECT classification alone misses data-changing CTEs. Current +wicked fixtures do not characterize `:many` output. + +Eight inspected consumers use wpgx, from v0.3.4 to v0.5.0. Source-level +compatibility includes method types and optional generated interfaces, not +only ordinary calls. Production inspection is unnecessary for this change. + +## 2. Problem Model and End-to-End Behavior + +- B1 Existing SQL without opt-in generates identical output on the same + compiler/version baseline. Existing methods, constructors, Querier, + cache/invalidation, timeout, replicas and Dump/Load retain their contracts. +- B2 `-- -- each: true` on a read-only `:many` adds XxxEach on Queries and, + when allowed, ReadOnlyQueries. Existing slice methods remain independent. +- B3 The synchronous visitor receives the query context and a fresh Row and + returns `(more bool, err error)`. True continues; false completes normal + consumption; error aborts consumption and remains the primary error. + Filtering means omitting output and continuing. Each retains no result slice. +- B4 Each uses the same connection/transaction, SQL, arguments, timeout and + CountIntent policy, directly accessing the DB without result-cache fill. +- B5 Normal stop and callback error drain/close by default. Cleanup/source + errors surface when there is no earlier primary error. Explicitly cancelling + a query-specific caller context opts into network abort and may invalidate + the physical connection/transaction. Panic propagates after cleanup. +- B6 The callback is never called for an empty selection; it must respect the + query context and cannot reenter the same active transaction connection. +- F1 Nil visitors fail before SQL. Invalid option values, unsupported commands, + mutations/data-changing CTEs, missing safety facts and companion-name + collisions fail generation. No new policy applies to legacy queries. +- F2 Callback, scan, source, deadline and close errors do not become success. + Normal stop preserves a separate channel so a late drain error remains visible. + +Single-row receive protection remains explicit SQL. Policies, row costing, +domain errors and all-or-nothing application collectors stay in their clients. +Downstream migration must preserve each reader's existing abort/drain policy +and any outer deadline shared with subsequent queries. + +## 3. Research, Findings, and Architecture Decision + +D1 Owner approved the reviewed Each design and requested implementation on +2026-11-11 (US Pacific), then explicitly requested continued local progress +while arranging a project-specific Stumble token. The reviewed API, cleanup +algorithm and compatibility obligations are the implementation contract. + +D2 Generate a companion with `visit func(context.Context, Row) (more bool, +err error)`, returning error after cleanup. Do not turn the old collector into +an adapter or add variadic parameters to existing methods. Typed options remain +a credible alternative for a narrower full-result-or-error guard, but alter +exact method types. Bare Seq2/cursors have additional terminal-error/lifetime +contracts and are not generated in this iteration. + +D3 The feature is wicked-only and opt-in. Reuse wpgx as-is; no runtime release, +SQL rewriting, migrations or budget primitive. If emit_interface is enabled, +EachQuerier is separate from the legacy Querier method set. + +D4 Reject syntactically visible mutations anywhere in an opted-in SELECT AST. +This does not prove absence of volatile-function side effects; opt-in follows +existing read/replica declarations and DB permissions. Legacy classification +is intentionally not redefined. + +Independent Codex/Claude design review accepted the same synthesis. The author +challenged error-only stop sentinels because they can mask late drain errors; +Claude accepted the separate normal-stop channel. AI-related benefits are +reasoned from API shape, not measured model success rates. + +R1 Cancellation can destroy a connection; callback work holds the connection +and consumes the deadline. R2 Cache-bypassing companions may increase DB load. +R3 Standard []byte ownership differs from custom borrowing codecs. R4 Bool +false means stop, not skip; generated docs/examples must be explicit. +R5 A new generator release is needed before adopting the annotation; existing +binaries fail on unknown options. R6 Exact downstream upgrades remain separate +from this generator change, with generator publication/release boundaries. + +References: prior scratch proposal and AI-facing synthesis; pgx Rows and +ForEachRow documentation; Go iter documentation; wicked option/query/interface +code and dcache GetWithTtl. The primary implementation record lives here. + +## 4. Implementation Design + +The approved public signature and loop/cleanup design map to these locations. + +- `protos/plugin/codegen.proto` and generated Go protocol code gain an optional + wicked per-query fact for syntactically visible mutations. The shim obtains + it through the existing recursive AST walker; other backend metadata remains + absent and legacy generation ignores the new fact. +- Wicked option parsing accepts literal true/false for `each`. Query building + validates command/safety facts only when enabled. Validation checks generated + companion methods/helper/interface names against existing declarations. +- The wpgx query template adds an independent visitor loop. It reuses existing + Row/Params and Scan representations, checks context before/after visits, + closes rows before cancelling its own context, and retains primary errors. + Visitor identifiers must avoid scalar/multi-parameter name collisions. +- The interface template adds EachQuerier only when companions exist; legacy + Querier stays byte-identical. Docs describe direct DB path, callback lifetime, + error/stop meanings and cooperative cancellation. +- Characterization fixtures precede template edits. Behavioral tests execute + actual generated methods with controllable Rows to exercise Close-only errors, + callback failures and context/panic paths; a scoped real-PostgreSQL check + verifies transaction reuse and explicit cancellation if available. +- First publication is a branch/PR against Stumble/sqlc using owner-provided + project credentials. Owner retains merge/release authority. Consumer code + migration follows publication/release separately, respecting existing downstream feature boundaries. + +### Serial Implementation Checklist + +- [x] Characterize existing many generation and save an immutable baseline binary. +- [x] Add each option, AST safety metadata and focused rejection tests. +- [x] Generate companion methods/docs and separate optional interface. +- [x] Prove generated runtime behavior and scoped integration semantics. +- [x] Compare non-opt-in fixture/consumer output against baseline; inspect goldens. +- [x] Update GUIDE and complete author verification, independent Claude review. +- [x] With verified project credentials, publish branch/PR and monitor checks. + +## 5. Verification and E2E Design + +E2E Required: no — no full Alva local-stack E2E was requested. Generator tests, +compiled generated code and scoped PG checks establish the affected contract. +No production DB or credentials are needed for those tests. Builds/tests run +serially with reduced parallelism on the shared VM. + +Focused commands (from repository root, GOMAXPROCS=2, GOWORK=off): + +- `go build -p=2 -o ../sqlc-before ./cmd/sqlc` before product changes. +- `go test -p=2 -count=1 ./internal/codegen/wicked ./internal/cmd`. +- `buf generate --path protos/plugin/codegen.proto` using installed tooling; + inspect generated diff and restrict changes to the protocol source of truth. +- `go build -p=2 -o ../sqlc-after ./cmd/sqlc`. +- From `internal/endtoend/testdata`, run `go test -p=2 -count=1 ./wicked_compat/go ./wicked_many/go ./wicked_each/go`. Runtime contracts live in the existing wicked_compat CI suite and import the generated Each fixture, so existing CI executes them. +- Run both binaries on isolated copies of the non-opt-in fixtures and real + alva-backend/synthdb input at recorded revisions; require byte equality. + Normalize only the version header if the two version strings differ. +- Broaden focused compiler/AST/protocol checks only for changes in those paths. +- `git diff --check`; read all modified golden/generated files. + +B1 is proved by fixture and real-consumer regeneration, including cached many, +mutation/invalidate, scalar and interface cases. B2/B4 require generation and +compile checks for Queries/ReadOnlyQueries and no replica exposure when disabled. +B3/B5/B6/F2 require generated-method behavior tests for ordering, complete/early +stop, error precedence, source/Close errors, empty/nil/cancel/deadline/panic, +retention and lifetime. F1 requires invalid option/command/safety/collision +negative cases. Cache+Each tests must show no cache lookup/fill by the companion +while the old collector retains cache behavior. + +## 6. Human Decisions and Interaction + +The owner approved the current design and requested progress, including +continuing local work before the temporary Stumble token is configured. This +plan records the previously reviewed callback signature, control flow, resource +semantics and compatibility matrix, plus routine source-local implementation +choices. No new product behavior is inferred from token availability. + +Credentials are project-scoped. The existing alva-bot01 identity has pull-only +access to Stumble/sqlc and wpgx. This task uses the owner-provided temporary credential +only for sqlc branch/PR work and CI reads. Its contents must never appear +in chat, logs, git or review artifacts. + +## 7. Outcome and Evidence + +The completed product content was verified at `49ac2682cf881acaf52c66fa3df4eedec2617607`, +against `e0d9cae63e18e46c50e6bba7e17f6f1341f36df4`. Each is an independent, +opt-in generated consumer; no wpgx or library dependency changes were necessary. +CI follow-up C1 updates the Go patch version in go.mod and existing workflows. +GUIDE and generated godoc describe the API and resource contract. + +All final local checks passed, serially with `GOTOOLCHAIN=go1.26.11 GOWORK=off GOMAXPROCS=2`: + +- Repository root: `go build -p=2 ./...` and + `go test -p=2 -count=1 ./internal/cmd ./internal/codegen/wicked ./internal/compiler ./internal/sql/astutils ./internal/plugin`. +- `internal/endtoend/testdata`: `go build -p=2 ./...` and + `go test -race -p=2 -count=1 ./wicked_compat/go ./wicked_many/go ./wicked_each/go`. + The latter used SQLC_EACH_TEST_DSN for an owned disposable PostgreSQL instance, + including wpgx v0.3.1. No production/shared database was used. +- Isolated runtime modules: `go test -mod=mod -p=2 -count=1 ./...` with the + same PG integration enabled, for wpgx v0.3.4, v0.4.8, v0.4.9 and v0.5.0. +- Clean candidate regeneration of wicked_each, `buf lint`, `git diff --check`, + and `git diff --exit-code` after generation. Buf's existing DEFAULT-category + deprecation warning is unrelated and remains unchanged. + +The baseline binary was built from e0d9cae before template changes. Legacy +many goldens, including cached struct parameters and a data-modifying CTE, +were generated by that immutable baseline. Compatibility tests pass with and +without interfaces. Final candidate binary provenance is `vcs.revision=49ac268`, +`vcs.modified=false`, SHA256 +`06fc5b654399d68bfcbbf7309162d5444634644da0f5a8d0d914ae27a5b09765`. +Both binaries report the same version header, so no normalization was needed. + +Eight immutable SQL/config input snapshots generated 1,031 Go files with +identical names and contents under both binaries; original worktrees were not +modified. This also proves cache/invalidate/timeout and Dump/Load output remains +unchanged in those consumers. + +| Consumer | Input revision | Generated Go files | Differences | +|---|---|---:|---:| +| synthdb | e9c563190e | 12 | 0 | +| alfs | 0bce08940b | 30 | 0 | +| alva-backend | 8c1e7b545d | 605 | 0 | +| jagent | 0d9c077e78 | 9 | 0 | +| worldline | 7e1f8b563f | 168 | 0 | +| trex | 8fcf54971c | 36 | 0 | +| connectors | 463b3ec43f | 15 | 0 | +| llm-data | ddc23400cd | 156 | 0 | + +| ID | Approved intent and implementation | Evidence | Status | +|---|---|---|---| +| B1 | Preserve legacy methods, interfaces and output | Baseline goldens, interface on/off, 1,031-file comparison | DONE | +| B2 | Generate opted-in companions and replica exposure | Compiled fixture, generation/routing tests | DONE | +| B3 | Typed synchronous consumer, fresh row, no collector | Executed order/retention/scalar/struct tests | DONE | +| B4 | Reuse routing, context, CountIntent; bypass cache | Replica, effective-context, poisoned-cache and intent tests | DONE | +| B5 | Drain before own cancel; preserve primary/late errors | Fake Rows error/panic/order cases and real PG transaction/pool checks | DONE | +| B6 | Empty selection and callback lifetime | Empty/deadline/context-lifetime tests; explicit API docs | DONE | +| F1 | Reject nil visitors and unsafe/incompatible opt-ins | Nil visitor side-effect checks; option/command/fact/name negative tests | DONE | +| F2 | Preserve source/scan/callback/close/context failures | Executed failure matrix and PG abort check | DONE | +| D1-D4 | Approved companion API, separate interface, no runtime release, syntactic safety | Templates, proto/shim facts, full independent review | DONE | +| R1-R4 | Cancellation, connection lifetime, cache cost, codec ownership and bool meaning | GUIDE/godoc and scoped runtime tests | DONE | +| R5-R6 | Release before downstream adoption | Documented staged adoption; no consumer change in this PR | DONE | + +The PG check used a localhost-only postgres:16-alpine container capped at one +CPU and 512 MiB. Each test creates/drops a unique owned schema, proves reuse +of the same transaction after stop/ordinary visitor error, and proves connection +replacement after explicit abort. Older wpgx transaction wrappers can overwrite +callback errors during failed rollback; Each's own primary error is asserted +separately, without changing that pre-existing runtime behavior. + +No full Alva service-stack E2E was requested. Full repository CI is left to +GitHub; local scoped integration and generated-runtime tests cover this contract. + +### Review and dispositions + +Both agents previously explicitly accepted the complete net diff at **49ac2682cf881acaf52c66fa3df4eedec2617607**: +Codex main `baa9cfcd-d88f-424e-a8a3-6e095ee3d37b` and Claude reviewer +`aee3fbde-9a50-4c30-94fe-ea3d7d1e4de6` (native conversation +`af103b26-bc43-4187-80b6-a68a4e6613c8`). Same VM `env-woddv6j0`, owner and +unchanged treeParentId were verified, including the parent's children listing +with no further pages. The original creation request was +`604f3b3c-fd56-4c95-bd32-77d60702dcc7`. Latest final review delivery request was +`d4ae62ca-dc77-4d25-91b5-cedfb1e4795e`; acceptance comes from the actual report, +not the delivery receipt. The a119f55 verification completed 2026-11-11 10:22:30 PST; +C1 verification and renewed Claude acceptance subsequently completed the same +US Pacific morning, recorded in the security-patch reports below. There are no unresolved +actionable findings. Evidence-only checklist/sections 7-8 updates do not change +the accepted product content. + +- Initial M1-M2: generated runtime tests now run through the existing wicked_compat + CI entrypoint; local checks use explicit packages and an owned PG container. +- M3-M4: baseline fixtures cover cached struct params and modifying CTEs; + fail-closed safety facts reject mutations, unknown CTE statements and SELECT INTO. +- M5: deterministic visitor naming handles SQL parameters and full Go type identifiers. +- S1-S7: cache bypass, cleanup/error ordering, version/consumer matrices, locking + reads and resource/stop semantics are tested or documented; no new query import. +- Author A1-A2, found after first acceptance of 5420baf: fixed custom/generic + type shadowing and helper/query-constant declaration collisions, added focused + regressions, reran final checks and obtained renewed full-diff acceptance. +- Optional final O1-O4: tied comparison evidence to a clean binary revision, + removed stale wording, added SELECT INTO fact coverage and isolated PG schema. +- Claude independently built clean a119f55, matched both fixture goldens, + regenerated synthdb/alva-backend (617 files) without differences, ran focused + generator/runtime tests, and checked the complete diff. Other version/PG/consumer + checks were inspected from the author's evidence rather than claimed as rerun. + +Local review artifacts are retained in the dedicated task scratch directory. +Their hashes preserve provenance; summaries and both acceptances are recorded +above so the record does not depend on those files remaining accessible. + +| Artifact | SHA256 | +|---|---| +| reviewer-creation.json | `9bd5056157d1fb2ba58e55bc1931ed76158687a3f8f71925f7798bea809d7acb` | +| implementation-review-initial.md | `17fdc100e3a7273a4f102c5134647e021ad86aafb4415d951f9c25611a4ca2c4` | +| implementation-code-review.md | `e13a90a1939b328b6bde93bafede2077c3b847d346199e450719796c01916f63` | +| implementation-code-review-final.md | `adaf6e5a09ef32f9065aa88bc6e8e8146c603a475ef651ccdb5f49d27693bf5b` | +| author-final-review.md | `40f4ea5af13545d576e344c2e7564e758511885a1120759cc474d7b781082253` | +| implementation-final-verification.md | `edf1778f3cbbeab7f002ae9ccf19bb23a56ace8f6296a9911faa59317ee85efb` | +| consumer-compat/results-a119f55.json | `ce752d46c70cac6bb3b691769e1edb5f29af6017ab3bdf6ca512277d47f72a1a` | +| runtime-matrix/results.json | `151e539eb962343739b2905e6a7d43e3b274a20aed1382a3f058345f63b33980` | + +## 8. Remaining Work + +Published ready-for-review PR [#24](https://github.com/Stumble/sqlc/pull/24) +on branch `yumin-xia/many-each-hooks`. Current-head CI and feedback are monitored +on the PR; their live status is authoritative. Initial publication succeeded +2026-11-11 10:26 PST using the task-specific owner credential, without changing +the shared GitHub identity. +The owner retains merge and release authority. Downstream migration of the six +handwritten readers follows an approved generator release and must preserve +per-reader abort/drain policies and SQL single-value guards. Existing feed-search +work is untouched. No runtime release or database migration is required. + + +CI follow-up C1 (2026-11-11 US Pacific): current-head Windows cross-build +failed while downloading grpc from proxy.golang.org (HTTP/2 INTERNAL_ERROR), +which cancelled the other matrix builds. The vulnerability job independently +reported GO-2026-6859 in the existing Go 1.26.10 standard library, fixed in +1.26.11. The official [Go release history](https://go.dev/doc/devel/release#go1.26.11) +records that security patch on 2026-11-10. Update the root build/release minimum +and every existing CI Go pin to 1.26.11, keeping the same Go minor version. +No library dependency or generated API changes. This necessary CI/security +follow-up passed fresh generation/build/runtime checks and renewed complete +cross-agent review at 49ac268. Earlier acceptances remain historical. +`GOTOOLCHAIN=go1.26.11 GOWORK=off GOMAXPROCS=2 go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...` +passed with 0 reachable vulnerabilities. The scanner also lists 2 imported-package +and 2 required-module vulnerabilities not called by this code; none were +suppressed. The new clean binary again generated all 1,031 consumer files +without differences. Go 1.26.11 root/focused/fixture builds, race and real PG +checks also passed. Claude independently rebuilt exact 49ac268 using Go1.26.11, +matched fixture goldens, regenerated 605 alva-backend files without differences +and ran focused generator/runtime checks. No actionable finding remains; the +current-head CI matrix and vulnerability scan rerun after pushing. Initial-head +repository-wide tests and bookstore compatibility/runtime CI had passed. + +C1 final review evidence (same verified Codex parent/Claude child and VM): + +| Artifact | SHA256 | +|---|---| +| implementation-code-review-security.md | `9a3e118a7136af827aa5b0c9613513c5d8b0c99040fbaa029b396b04ae69e336` | +| author-security-review.md | `05e49acfd1040ea520479787d48e2b5657bac6338fb303ce9cdbe54ea1c0291d` | +| security-patch-verification.md | `4b03f270323de3f56f2d449226f91f82f7808951380cdab39e9bb1ef9b19d279` | +| security-patch-local-checks.log | `ef26ba4e279161c4a7d0d281d0a2bbaeda250cb47504b63a2adacb0f52b0913e` | +| consumer-compat/results.json | `eecb640bbadfdb0704656bc29f194af57fe92f67bd194d28f5998f60ca814b73` | + +C2 publication blocker (2026-11-11 US Pacific): GitHub rejected the push of +the reviewed C1 follow-up because the temporary PAT lacks `workflow` scope. +The published PR remains at 18ed706; the security patch and its review/evidence +are retained locally. Repository push/admin role does not confer a missing PAT +scope. The PR body records this distinction. At that point workflow permission was required before publication; this +blocker is now resolved as recorded below. +No permission bypass or release/merge was attempted. + +The owned disposable PG container was removed and its absence verified after +all checks. The completed dedicated Claude reviewer was closed by its creating +parent after preserving both acceptances and report hashes. Closed state was +verified with unchanged native ID/treeParentId, live=false and retained parent +children listing. It had no cron or continuing responsibility. Review history +can be reopened if later CI requires another product fix. + +- implementation-review-completion.json: SHA256 `de2f4be5c48df3e0aa8cfe0daac6286deb28fe18fd437116a2c3e9dc82cabdc0`. + +- implementation-review-close.json: SHA256 `5e4550142cbddb59778cdfdc14a7e3fc664120356f4d0a207480a83d1f7376d0`. + +- implementation-review-closed-state.json: SHA256 `ae205f0fc61be5fe5d93f844aa6bf0b46cbe470ea66e037a696e62efaf329234`. + +- implementation-review-closed-tree.json: SHA256 `7b1f154eee28e7603a7736faaade4de9d65f6f69224610efc881e030a049a8ce`. + +- postgres-cleanup.json: SHA256 `f63b430740a027b5afb8b008b5f5704e2b0239f8f83e2c88d8b7476c5c4652c3`. + + +Owner-requested final reconfirmation (2026-11-11 US Pacific): the owner added +workflow permission. An actual push of 1416a5b, including the workflow changes, +succeeded; PR #24's head was verified through GitHub. C2 is resolved. Builds and +checks now run on the new published head; live PR status remains authoritative. + +At the owner's explicit request, the creating parent reopened the same tracked +Claude reviewer session on the same VM, preserving native conversation +`af103b26-bc43-4187-80b6-a68a4e6613c8`, child ID and treeParentId. The reviewer +reverified its identity and the parent's complete children listing. Both Codex +and Claude **explicitly endorse the design and accept the complete net diff +`e0d9cae63e18e46c50e6bba7e17f6f1341f36df4..1416a5bde7a109d76de00c7d1dcda219d0221c3a`**. +There is no unresolved actionable finding. Later changes in this final evidence +commit are confined to changelog sections 7-8. + +Claude's new report distinguishes full source audit across the implementation +rounds, independently executed fixture/generator/runtime/consumer checks, and +inspection of the author's PG/race/runtime-version/1,031-file evidence. For this +reconfirmation it proved non-document content matches the verified 49ac268 +byte for byte, reread key implementation/design choices and audited all new +evidence prose. It did not claim to rerun all tests or remote CI. The endorsed +design preserves exact legacy signatures with a typed Each companion, keeps +policy in the visitor, separates normal stop from error, centralizes cleanup, +bypasses cache for request-specific consumption and retains syntactic safety +and existing routing/transaction constraints. Its limitations remain explicit. + +Optional O1 is intentionally unchanged, independently accepted by Claude: +Each and the slice method share the SQL operation label and CountIntent policy. +Close-based wpgx latency includes callback work, and explicit cancellation may +appear as a context-canceled DB error under that label. Downstream adoption +should account for this in metrics/alerts. Separate mode labels remain a possible +future observability choice; no correctness/compatibility change is required. + +The follow-up delivery request was `594bc92b-e9d7-49e1-bd51-030beb61d352`, +with factual-status/disposition request `6bc7631a-1e53-4bd7-bd5d-033b6387ff40`. +The actual revised report, rather than delivery, supplies the acceptance. +Both result summaries/hashes are preserved here before parent-managed reviewer +completion. The dedicated reviewer has no continuing watch/cron responsibility. + +| Final reconfirmation artifact | SHA256 | +|---|---| +| owner-reconfirmation-main.md | `a7c9bf99385e2b7a8388bc39274a13f2f0d68001bd45ff296e8b4b8b7d9e70e2` | +| owner-reconfirmation-review.md | `a7f40e374a2dda69957874f596ed66e7100d7d6361e167d06a3c50c77a8dca22` | +| owner-reconfirmation-reopened-state.json | `26168ce4a6e463f0f2ca6e81c310e310b71788a422d8bae969ef4fd2497402cb` | +| owner-reconfirmation-tree.json | `d6f65be59db2f0ba30bb28cfcbafbfd629a193a9202a8e76cfb5bdbaf73cca04` | +| owner-reconfirmation-delivery.json | `090aaf878111fcd283d2dbfe19e7a29eb1cbf75cb83fe6fc4559e9e62df090a3` | diff --git a/go.mod b/go.mod index 49baed89e6..f8ff927ecc 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sqlc-dev/sqlc -go 1.26.10 +go 1.26.11 require ( github.com/antlr4-go/antlr/v4 v4.13.1 diff --git a/internal/cmd/shim.go b/internal/cmd/shim.go index 446d6d5f01..433d018e23 100644 --- a/internal/cmd/shim.go +++ b/internal/cmd/shim.go @@ -7,6 +7,7 @@ import ( "github.com/sqlc-dev/sqlc/internal/info" "github.com/sqlc-dev/sqlc/internal/plugin" "github.com/sqlc-dev/sqlc/internal/sql/ast" + "github.com/sqlc-dev/sqlc/internal/sql/astutils" "github.com/sqlc-dev/sqlc/internal/sql/catalog" ) @@ -238,10 +239,31 @@ func codeGenRequest(r *compiler.Result, settings config.CombinedSettings) *plugi PrimarySchemaSql: r.Wicked.PrimarySchemaSQL, PrimaryRelation: &plugin.Identifier{Catalog: rel.Catalog, Schema: rel.Schema, Name: rel.Name}, QueryIsSelect: make(map[string]bool, len(r.Queries)), + QueryHasMutation: make(map[string]bool, len(r.Queries)), } for _, q := range r.Queries { _, isSelect := q.RawStmt.Stmt.(*ast.SelectStmt) facts.QueryIsSelect[q.Metadata.Name] = isSelect + hasMutation := false + astutils.Walk(astutils.VisitorFunc(func(node ast.Node) { + switch n := node.(type) { + case *ast.InsertStmt, *ast.UpdateStmt, *ast.DeleteStmt: + hasMutation = true + case *ast.CommonTableExpr: + // Unsupported CTE statements (for example MERGE in a + // parser version without that node) cannot opt into reads. + switch n.Ctequery.(type) { + case *ast.SelectStmt, *ast.InsertStmt, *ast.UpdateStmt, *ast.DeleteStmt: + default: + hasMutation = true + } + case *ast.SelectStmt: + if n.IntoClause != nil { + hasMutation = true + } + } + }), q.RawStmt.Stmt) + facts.QueryHasMutation[q.Metadata.Name] = hasMutation } req.BackendMetadata = &plugin.GenerateRequest_Wicked{Wicked: facts} } diff --git a/internal/cmd/wicked_each_test.go b/internal/cmd/wicked_each_test.go new file mode 100644 index 0000000000..7777569213 --- /dev/null +++ b/internal/cmd/wicked_each_test.go @@ -0,0 +1,110 @@ +package cmd + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func generateEachFixture(t *testing.T, query, settings string) (map[string]string, string, error) { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "schema.sql": "CREATE TABLE books (id bigint PRIMARY KEY, value bytea NOT NULL);", + "query.sql": query, + "sqlc.yaml": "version: '2'\nsql:\n- schema: schema.sql\n queries: query.sql\n engine: postgresql\n gen:\n go:\n sql_package: wpgx\n package: books\n out: books\n" + settings, + } + for name, source := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(source), 0600); err != nil { + t.Fatal(err) + } + } + var stderr bytes.Buffer + output, err := Generate(context.Background(), dir, "", &Options{Env: Env{NoRemote: true}, Stderr: &stderr}) + return output, stderr.String(), err +} + +func TestWickedEachGeneration(t *testing.T) { + query := "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: true\nSELECT id, value FROM books WHERE id >= @visit ORDER BY id;\n" + output, stderr, err := generateEachFixture(t, query, " emit_interface: true\n") + if err != nil { + t.Fatalf("generate: %v: %s", err, stderr) + } + var source, iface string + for name, value := range output { + switch filepath.Base(name) { + case "query.sql.go": + source = value + case "querier.go": + iface = value + } + } + for _, want := range []string{"func (q *Queries) ListBooksEach", "func (q *ReadOnlyQueries) ListBooksEach", "visit int64, visit1 func(context.Context, Book)"} { + if !strings.Contains(source, want) { + t.Errorf("missing %q", want) + } + } + if !strings.Contains(iface, "type EachQuerier interface") { + t.Fatal("missing separate EachQuerier") + } + start := strings.Index(iface, "type Querier interface") + if start < 0 { + t.Fatal("missing legacy Querier") + } + legacy, _, _ := strings.Cut(strings.TrimPrefix(iface[start:], "type Querier interface"), "\n}") + if strings.Contains(legacy, "ListBooksEach") { + t.Fatal("legacy Querier changed") + } +} + +func TestWickedEachValidation(t *testing.T) { + for _, tc := range []struct{ name, query, want string }{ + {"exec", "-- name: ListBooks :exec\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books;", "each requires a read-only :many"}, + {"empty_value", "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each:\nSELECT * FROM books;", "invalid each value"}, + {"one", "-- name: GetBook :one\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books WHERE id = 1;", "each requires a read-only :many"}, + {"mutation", "-- name: PutBook :many\n-- -- timeout: 1s\n-- -- each: true\nINSERT INTO books (id, value) VALUES (1, ''::bytea) RETURNING *;", "each requires a read-only :many"}, + {"cte", "-- name: PutBook :many\n-- -- timeout: 1s\n-- -- each: true\nWITH changed AS (DELETE FROM books RETURNING *) SELECT * FROM changed;", "each requires a read-only :many"}, + {"nested_cte", "-- name: PutBook :many\n-- -- timeout: 1s\n-- -- each: true\nWITH changed AS (INSERT INTO books (id, value) VALUES (1, ''::bytea) RETURNING *) SELECT * FROM (SELECT * FROM changed) AS nested;", "each requires a read-only :many"}, + {"value", "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: yes\nSELECT * FROM books;", "invalid each value"}, + {"helper_constant_collision", "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books;\n-- name: _ListBooksEach :many\n-- -- timeout: 1s\nSELECT * FROM books;", "Each companion name conflicts"}, + {"name_collision", "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books;\n-- name: ListBooksEach :many\n-- -- timeout: 1s\nSELECT * FROM books;", "Each companion name conflicts"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, stderr, err := generateEachFixture(t, tc.query, "") + if err == nil || !strings.Contains(stderr, tc.want) { + t.Fatalf("err=%v stderr=%s, want %s", err, stderr, tc.want) + } + }) + } +} + +func TestWickedEachDisabled(t *testing.T) { + output, stderr, err := generateEachFixture(t, "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: false\nSELECT * FROM books;", " emit_interface: true\n") + if err != nil { + t.Fatalf("generate: %v: %s", err, stderr) + } + for _, source := range output { + if strings.Contains(source, "ListBooksEach(") || strings.Contains(source, "type EachQuerier") { + t.Fatal("disabled companion was emitted") + } + } +} + +func TestWickedEachInterfaceNameCollision(t *testing.T) { + query := "-- name: EachQuerier :many\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books;" + _, stderr, err := generateEachFixture(t, query, " emit_interface: true\n emit_exported_queries: true\n") + if err == nil || !strings.Contains(stderr, "Each companion name conflicts") { + t.Fatalf("err=%v stderr=%s", err, stderr) + } +} + +func TestWickedEachModelNameCollision(t *testing.T) { + query := "-- name: ListBooks :many\n-- -- timeout: 1s\n-- -- each: true\nSELECT * FROM books;" + _, stderr, err := generateEachFixture(t, query, " emit_interface: true\n rename:\n book: EachQuerier\n") + if err == nil || !strings.Contains(stderr, "Each companion name conflicts with model") { + t.Fatalf("err=%v stderr=%s", err, stderr) + } +} diff --git a/internal/cmd/wicked_many_test.go b/internal/cmd/wicked_many_test.go new file mode 100644 index 0000000000..09c85a2425 --- /dev/null +++ b/internal/cmd/wicked_many_test.go @@ -0,0 +1,61 @@ +package cmd + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// The golden was generated before adding Each. Compare bytes so an opt-in +// feature cannot quietly refactor legacy collectors, caching or invalidation. +func TestWickedManyCompatibility(t *testing.T) { + fixture := filepath.Join("..", "endtoend", "testdata", "wicked_many") + for _, emitInterface := range []bool{true, false} { + t.Run(map[bool]string{true: "interface", false: "no_interface"}[emitInterface], func(t *testing.T) { + dir := t.TempDir() + for _, name := range []string{"sqlc.yaml", "schema.sql", "query.sql"} { + data, err := os.ReadFile(filepath.Join(fixture, name)) + if err != nil { + t.Fatal(err) + } + if name == "sqlc.yaml" && !emitInterface { + data = bytes.Replace(data, []byte("emit_interface: true"), []byte("emit_interface: false"), 1) + } + if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil { + t.Fatal(err) + } + } + var stderr bytes.Buffer + output, err := Generate(context.Background(), dir, "", &Options{Env: Env{NoRemote: true}, Stderr: &stderr}) + if err != nil { + t.Fatalf("generate: %v: %s", err, &stderr) + } + entries, err := os.ReadDir(filepath.Join(fixture, "go")) + if err != nil { + t.Fatal(err) + } + wantCount := 0 + for _, entry := range entries { + if !strings.HasSuffix(entry.Name(), ".go") || (!emitInterface && entry.Name() == "querier.go") { + continue + } + wantCount++ + want, err := os.ReadFile(filepath.Join(fixture, "go", entry.Name())) + if err != nil { + t.Fatal(err) + } + name := filepath.Join(dir, "go", entry.Name()) + got, exists := output[name] + if !exists || !bytes.Equal([]byte(got), want) { + t.Errorf("legacy output changed: %s (exists=%v)", name, exists) + } + } + if len(output) != wantCount { + t.Errorf("files = %d, want %d", len(output), wantCount) + } + }) + } +} diff --git a/internal/cmd/wicked_test.go b/internal/cmd/wicked_test.go index b6884c5a59..ee6e04c930 100644 --- a/internal/cmd/wicked_test.go +++ b/internal/cmd/wicked_test.go @@ -16,8 +16,10 @@ import ( "github.com/sqlc-dev/sqlc/internal/codegen/wicked" "github.com/sqlc-dev/sqlc/internal/compiler" "github.com/sqlc-dev/sqlc/internal/config" + "github.com/sqlc-dev/sqlc/internal/metadata" "github.com/sqlc-dev/sqlc/internal/opts" "github.com/sqlc-dev/sqlc/internal/plugin" + "github.com/sqlc-dev/sqlc/internal/sql/ast" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -106,6 +108,22 @@ func TestWickedProtocolFacts(t *testing.T) { if v, present := facts.QueryIsSelect["CreateBook"]; !present || v { t.Fatal("INSERT RETURNING is not a SELECT") } + if facts.QueryHasMutation["GetBook"] || !facts.QueryHasMutation["CreateBook"] { + t.Fatalf("mutation facts = %v", facts.QueryHasMutation) + } + for name, statement := range map[string]*ast.SelectStmt{ + "unsupported CTE": {WithClause: &ast.WithClause{Ctes: &ast.List{Items: []ast.Node{&ast.CommonTableExpr{Ctequery: &ast.TODO{}}}}}}, + "SELECT INTO": {IntoClause: &ast.IntoClause{}}, + } { + unsupported := *c.Result() + unsupported.Queries = []*compiler.Query{{ + Metadata: metadata.Metadata{Name: "Unsupported", Cmd: ":many"}, + RawStmt: &ast.RawStmt{Stmt: statement}, + }} + if !codeGenRequest(&unsupported, combined).GetWicked().QueryHasMutation["Unsupported"] { + t.Fatalf("%s was classified as a read", name) + } + } blob, err := proto.Marshal(req) if err != nil { t.Fatal(err) @@ -128,6 +146,13 @@ func TestWickedProtocolFacts(t *testing.T) { if !proto.Equal(before, req) { t.Fatal("generator modified its input request") } + withoutSafety := proto.Clone(req).(*plugin.GenerateRequest) + withoutSafety.GetWicked().QueryHasMutation = nil + withoutSafety.Queries[0].Cmd = ":many" + withoutSafety.Queries[0].Comments = append(withoutSafety.Queries[0].Comments, "-- each: true") + if _, err := wicked.Generate(context.Background(), withoutSafety); err == nil || !strings.Contains(err.Error(), "statement safety metadata") { + t.Fatalf("missing safety facts err=%v", err) + } standard := proto.Clone(req).(*plugin.GenerateRequest) standard.BackendMetadata = nil blob, err = (protojson.MarshalOptions{EmitUnpopulated: true}).Marshal(standard) diff --git a/internal/codegen/wicked/gen.go b/internal/codegen/wicked/gen.go index 8890c0cb47..aace51a602 100644 --- a/internal/codegen/wicked/gen.go +++ b/internal/codegen/wicked/gen.go @@ -35,6 +35,7 @@ type tmplCtx struct { EmitDBTags bool EmitPreparedQueries bool EmitInterface bool + HasEach bool EmitEmptySlices bool EmitMethodsWithDBArgument bool EmitEnumValidMethod bool @@ -170,6 +171,11 @@ func Generate(ctx context.Context, req *plugin.GenerateRequest) (*plugin.Generat } func validate(options *opts.Options, enums []Enum, structs []Struct, queries []Query) error { + if hasEach(queries) { + if err := validateEachNames(options, enums, structs, queries); err != nil { + return err + } + } enumNames := make(map[string]struct{}) for _, enum := range enums { enumNames[enum.Name] = struct{}{} @@ -212,6 +218,7 @@ func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum, DumpLoader: dumploader, RawSchemaSQL: req.GetWicked().PrimarySchemaSql, EmitInterface: false, + HasEach: hasEach(queries), EmitJSONTags: true, JsonTagsIDUppercase: false, EmitDBTags: false, @@ -449,3 +456,66 @@ func filterUnusedStructs(enums []Enum, structs []Struct, queries []Query) ([]Enu return keepEnums, keepStructs } + +func hasEach(queries []Query) bool { + for _, query := range queries { + if query.Option.Each { + return true + } + } + return false +} + +// Check only declarations introduced by Each. Existing queries without the +// annotation retain the original naming rules and output. +func validateEachNames(options *opts.Options, enums []Enum, structs []Struct, queries []Query) error { + methods := map[string]bool{ + "WithTx": true, "WithCache": true, "AsReadOnly": true, + "UseReplica": true, "GetCache": true, "GetConn": true, + "Dump": true, "Load": true, + } + declarations := make(map[string]string) + for _, enum := range enums { + declarations[enum.Name] = "enum" + declarations["Null"+enum.Name] = "enum" + for _, constant := range enum.Constants { + declarations[constant.Name] = "enum constant" + } + } + for _, strct := range structs { + declarations[strct.Name] = "model" + } + for _, query := range queries { + methods[query.MethodName] = true + if query.Cmd != metadata.CmdCopyFrom { + declarations[query.ConstantName] = "query constant" + } + if query.Cmd == metadata.CmdOne || query.Cmd == metadata.CmdMany { + declarations["_"+query.MethodName] = "helper" + } + if query.Arg.EmitStruct() { + declarations[query.Arg.Type()] = "parameter type" + } + if query.Ret.EmitStruct() { + declarations[query.Ret.Type()] = "row type" + } + } + for _, query := range queries { + if !query.Option.Each { + continue + } + name := query.MethodName + "Each" + if methods[name] { + return fmt.Errorf("%s/%s: Each companion name conflicts: %s", options.Package, query.MethodName, name) + } + if kind := declarations["_"+name]; kind != "" { + return fmt.Errorf("%s/%s: Each companion name conflicts with %s: _%s", options.Package, query.MethodName, kind, name) + } + } + if options.EmitInterface { + if kind := declarations["EachQuerier"]; kind != "" { + return fmt.Errorf("Each companion name conflicts with %s: EachQuerier", kind) + } + } + return nil +} diff --git a/internal/codegen/wicked/option.go b/internal/codegen/wicked/option.go index f4bed97ce4..2492de81d3 100644 --- a/internal/codegen/wicked/option.go +++ b/internal/codegen/wicked/option.go @@ -12,6 +12,7 @@ const ( WpgxOptionKeyCountIntent = "count_intent" WpgxOptionKeyTimeout = "timeout" WpgxOptionKeyAllowReplica = "allow_replica" + WpgxOptionKeyEach = "each" ) type WPgxOption struct { @@ -20,6 +21,7 @@ type WPgxOption struct { CountIntent bool Timeout time.Duration AllowReplica bool + Each bool } func parseOption(options map[string]string, queryNames map[string]bool) (rv WPgxOption, err error) { @@ -59,6 +61,11 @@ func parseOption(options map[string]string, queryNames map[string]bool) (rv WPgx if rv.Timeout < 1*time.Millisecond { return rv, fmt.Errorf("timeout duration too short: %s", v) } + case WpgxOptionKeyEach: + if v != "true" && v != "false" { + return rv, fmt.Errorf("invalid each value: %s", v) + } + rv.Each = v == "true" case WpgxOptionKeyAllowReplica: if v == "true" { rv.AllowReplica = true diff --git a/internal/codegen/wicked/options_test.go b/internal/codegen/wicked/options_test.go index 2b1a4c4cd3..65fa66b2c2 100644 --- a/internal/codegen/wicked/options_test.go +++ b/internal/codegen/wicked/options_test.go @@ -113,3 +113,23 @@ func TestInvalidQueryOptions(t *testing.T) { }) } } + +func TestEachVisitorNames(t *testing.T) { + for _, tc := range []struct{ typ, arg, want string }{ + {"int64", "", "visit"}, + {"visit", "", "visit1"}, + {"*visit", "", "visit1"}, + {"map[string]visit.Item", "", "visit1"}, + {"Box[visit.Value]", "", "visit1"}, + {"visit.Box[visit1.Value]", "visit2", "visit3"}, + {"int64", "visit", "visit1"}, + } { + q := Query{Ret: QueryValue{Name: "row", Typ: tc.typ}} + if tc.arg != "" { + q.Arg = QueryValue{Name: tc.arg, Typ: "int64"} + } + if got := q.EachVisitName(); got != tc.want { + t.Errorf("type=%s arg=%s got=%s want=%s", tc.typ, tc.arg, got, tc.want) + } + } +} diff --git a/internal/codegen/wicked/query.go b/internal/codegen/wicked/query.go index 3f3c023755..179532aae7 100644 --- a/internal/codegen/wicked/query.go +++ b/internal/codegen/wicked/query.go @@ -2,6 +2,8 @@ package wicked import ( "fmt" + goast "go/ast" + "go/parser" "strings" "github.com/sqlc-dev/sqlc/internal/codegen/golang/opts" @@ -430,3 +432,34 @@ type InvalidateParam struct { } func (v QueryValue) IsTypePointer() bool { return strings.HasPrefix(v.Type(), "*") } + +// EachVisitName avoids collisions with scalar or expanded SQL parameters. +func (q Query) EachVisitName() string { + used := map[string]bool{q.Ret.Name: true} + // A visitor parameter can shadow a type or package used by new(T), + // including identifiers nested in generic, array or map types. + if typ, err := parser.ParseExpr(q.Ret.Type()); err == nil { + goast.Inspect(typ, func(node goast.Node) bool { + if ident, ok := node.(*goast.Ident); ok { + used[ident.Name] = true + } + return true + }) + } + for _, arg := range q.Arg.Pairs() { + used[arg.Name] = true + } + name := "visit" + for suffix := 1; used[name]; suffix++ { + name = fmt.Sprintf("visit%d", suffix) + } + return name +} + +// EachScan reuses the existing decoder with a local name independent of SQL +// column names, which may also be control-flow names such as more or qctx. +func (q Query) EachScan() string { + ret := q.Ret + ret.Name = "eachRow" + return ret.Scan() +} diff --git a/internal/codegen/wicked/result.go b/internal/codegen/wicked/result.go index 6f0888d5a4..9c3251156d 100644 --- a/internal/codegen/wicked/result.go +++ b/internal/codegen/wicked/result.go @@ -363,6 +363,12 @@ func buildQueries(req *plugin.GenerateRequest, options *opts.Options, structs [] if err != nil { return nil, fmt.Errorf("%s/%s: %w", options.Package, query.Name, err) } + if gq.Option.Each { + hasMutation, known := req.GetWicked().QueryHasMutation[query.Name] + if gq.Cmd != metadata.CmdMany || !isSelect || !known || hasMutation { + return nil, fmt.Errorf("%s/%s: each requires a read-only :many with statement safety metadata", options.Package, query.Name) + } + } qs = append(qs, gq) } sort.Slice(qs, func(i, j int) bool { return qs[i].MethodName < qs[j].MethodName }) diff --git a/internal/codegen/wicked/templates/wpgx/interfaceCode.tmpl b/internal/codegen/wicked/templates/wpgx/interfaceCode.tmpl index 3517b9cff3..5e28993351 100644 --- a/internal/codegen/wicked/templates/wpgx/interfaceCode.tmpl +++ b/internal/codegen/wicked/templates/wpgx/interfaceCode.tmpl @@ -9,4 +9,14 @@ type Querier interface { {{end}} } var _ Querier = (*Queries)(nil) +{{if .HasEach}} + +// EachQuerier is separate so existing Querier implementations remain valid. +type EachQuerier interface { +{{range .GoQueries}}{{if .Option.Each}} + {{.MethodName}}Each(ctx context.Context, {{if .Arg.Pair}}{{.Arg.Pair}},{{end}} {{.EachVisitName}} func(context.Context, {{.Ret.Type}}) (more bool, err error)) error +{{end}}{{end}} +} +var _ EachQuerier = (*Queries)(nil) +{{end}} {{end}} diff --git a/internal/codegen/wicked/templates/wpgx/queryCode.tmpl b/internal/codegen/wicked/templates/wpgx/queryCode.tmpl index a2305372d0..38679fc11d 100644 --- a/internal/codegen/wicked/templates/wpgx/queryCode.tmpl +++ b/internal/codegen/wicked/templates/wpgx/queryCode.tmpl @@ -227,6 +227,55 @@ func _{{.MethodName}}(ctx context.Context, q {{.ConnType}}, {{.Arg.Pair}} {{.Inv {{- end }} return items, err } +{{if .Option.Each}} + +// {{.MethodName}}Each visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) {{.MethodName}}Each(ctx context.Context, {{if .Arg.Pair}}{{.Arg.Pair}},{{end}} {{.EachVisitName}} func(context.Context, {{.Ret.Type}}) (more bool, err error)) error { + return _{{.MethodName}}Each(ctx, q.AsReadOnly(), {{if .Arg.Name}}{{.Arg.Name}},{{end}} {{.EachVisitName}}) +} + +{{if .AllowReplica}} +// {{.MethodName}}Each has the same consumption and lifetime contract as Queries.{{.MethodName}}Each. +func (q *ReadOnlyQueries) {{.MethodName}}Each(ctx context.Context, {{if .Arg.Pair}}{{.Arg.Pair}},{{end}} {{.EachVisitName}} func(context.Context, {{.Ret.Type}}) (more bool, err error)) error { + return _{{.MethodName}}Each(ctx, q, {{if .Arg.Name}}{{.Arg.Name}},{{end}} {{.EachVisitName}}) +} +{{end}} + +func _{{.MethodName}}Each(ctx context.Context, q CacheQuerierConn, {{if .Arg.Pair}}{{.Arg.Pair}},{{end}} {{.EachVisitName}} func(context.Context, {{.Ret.Type}}) (more bool, err error)) error { + if {{.EachVisitName}} == nil { + return fmt.Errorf("{{.MethodName}}Each: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond * {{.Option.Timeout.Milliseconds}}) + defer cancel() + {{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() + for rows.Next() { + if err := 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 !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. + rows.Close() + if err := rows.Err(); err != nil { return err } + return qctx.Err() +} +{{end}} {{end}} {{if eq .Cmd ":exec"}} diff --git a/internal/endtoend/testdata/wicked_compat/go/each_postgres_test.go b/internal/endtoend/testdata/wicked_compat/go/each_postgres_test.go new file mode 100644 index 0000000000..7522e2afbe --- /dev/null +++ b/internal/endtoend/testdata/wicked_compat/go/each_postgres_test.go @@ -0,0 +1,127 @@ +package compat_test + +import ( + "context" + "errors" + "fmt" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5" + eachgen "github.com/sqlc-dev/sqlc/endtoend/wicked_each/go" + "github.com/stumble/wpgx" +) + +// Optional scoped integration check; the standard contract suite needs no DB. +func TestGeneratedEachPostgres(t *testing.T) { + dsn := os.Getenv("SQLC_EACH_TEST_DSN") + if dsn == "" { + t.Skip("set SQLC_EACH_TEST_DSN to a disposable PostgreSQL database") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cfg, err := pgx.ParseConfig(dsn) + if err != nil { + t.Fatal(err) + } + setup, err := pgx.Connect(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer setup.Close(ctx) + schema := pgx.Identifier{fmt.Sprintf("sqlc_each_%d", time.Now().UnixNano())}.Sanitize() + if _, err := setup.Exec(ctx, "CREATE SCHEMA "+schema); err != nil { + t.Fatal(err) + } + defer func() { + cleanup, stop := context.WithTimeout(context.Background(), 10*time.Second) + defer stop() + if _, err := setup.Exec(cleanup, "DROP SCHEMA "+schema+" CASCADE"); err != nil { + t.Errorf("schema cleanup: %v", err) + } + }() + pool, err := wpgx.NewPool(ctx, &wpgx.Config{ + Username: cfg.User, Password: cfg.Password, Host: cfg.Host, Port: int(cfg.Port), DBName: cfg.Database, + MaxConns: 1, MinConns: 0, MaxConnLifetime: time.Minute, MaxConnIdleTime: time.Minute, AppName: "sqlc_each_test", + BeforeAcquire: func(ctx context.Context, conn *pgx.Conn) bool { + _, err := conn.Exec(ctx, "SET search_path TO "+schema) + return err == nil + }, + }) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + conn := pool.WConn() + if _, err := conn.WExec(ctx, "setup", "CREATE TABLE books (id bigint PRIMARY KEY, value bytea NOT NULL)"); err != nil { + t.Fatal(err) + } + // More than one network buffer remains unread when the visitor first runs. + if _, err := conn.WExec(ctx, "seed", "INSERT INTO books SELECT n, decode(repeat('61', 131072), 'hex') FROM generate_series(1,64) n"); err != nil { + t.Fatal(err) + } + q := eachgen.New(conn, nil) + primary := errors.New("policy rejection") + for _, failVisitor := range []bool{false, true} { + _, err := pool.Transact(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly}, func(ctx context.Context, tx *wpgx.WTx) (any, error) { + count := 0 + err := q.WithTx(tx).ListBooksEach(ctx, 0, func(context.Context, eachgen.Book) (bool, error) { + count++ + if failVisitor { + return false, primary + } + return false, nil + }) + if count != 1 { + t.Fatalf("visitor count=%d", count) + } + if failVisitor { + if !errors.Is(err, primary) { + t.Fatalf("visitor err=%v", err) + } + } else if err != nil { + t.Fatal(err) + } + var one int + if err := tx.WQueryRow(ctx, "probe", "SELECT 1").Scan(&one); err != nil { + t.Fatalf("drained transaction unusable: %v", err) + } + if one != 1 { + t.Fatalf("probe=%d", one) + } + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + } + var originalPID int + _, err = pool.Transact(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly}, func(ctx context.Context, tx *wpgx.WTx) (any, error) { + if err := tx.WQueryRow(ctx, "pid", "SELECT pg_backend_pid()").Scan(&originalPID); err != nil { + return nil, err + } + readCtx, abort := context.WithCancel(ctx) + defer abort() + err := q.WithTx(tx).ListBooksEach(readCtx, 0, func(context.Context, eachgen.Book) (bool, error) { + abort() + return false, primary + }) + if !errors.Is(err, primary) { + t.Fatalf("Each lost abort's primary error: %v", err) + } + return nil, err + }) + if err == nil { + t.Fatal("aborted transaction succeeded") + } + // Older wpgx may replace the callback error on failed rollback; Each's + // primary error is asserted inside the callback independently of that API. + var replacementPID int + if err := conn.WQueryRow(ctx, "replacement", "SELECT pg_backend_pid()").Scan(&replacementPID); err != nil { + t.Fatal(err) + } + if originalPID == replacementPID { + t.Fatal("explicitly aborted connection was not replaced") + } +} diff --git a/internal/endtoend/testdata/wicked_compat/go/each_runtime_test.go b/internal/endtoend/testdata/wicked_compat/go/each_runtime_test.go new file mode 100644 index 0000000000..c7fa08e91d --- /dev/null +++ b/internal/endtoend/testdata/wicked_compat/go/each_runtime_test.go @@ -0,0 +1,341 @@ +package compat_test + +// Keep this cross-package contract suite in the existing wicked CI entrypoint. +// It executes the generated Each fixture rather than reimplementing its loop. +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + eachgen "github.com/sqlc-dev/sqlc/endtoend/wicked_each/go" + "github.com/stumble/dcache" +) + +type eachRows struct { + data []eachgen.Book + index int + closed bool + closeCanceled bool + ctx context.Context + scanErr, sourceErr, closeErr, finalErr error + failAfter int +} + +func (r *eachRows) Close() { + if r.closed { + return + } + r.closeCanceled = r.ctx.Err() != nil + r.closed = true + if r.finalErr == nil { + r.finalErr = r.closeErr + } + if r.finalErr == nil { + r.finalErr = r.ctx.Err() + } +} +func (r *eachRows) Err() error { return r.finalErr } +func (r *eachRows) Next() bool { + if r.closed { + return false + } + if r.sourceErr != nil && r.index == r.failAfter { + r.finalErr = r.sourceErr + r.Close() + return false + } + if r.index == len(r.data) { + r.Close() + return false + } + r.index++ + return true +} +func (r *eachRows) Scan(dest ...any) error { + if r.scanErr != nil { + return r.scanErr + } + row := r.data[r.index-1] + *dest[0].(*int64) = row.ID + if len(dest) > 1 { + *dest[1].(*[]byte) = append([]byte(nil), row.Value...) + } + return nil +} +func (*eachRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} } +func (*eachRows) FieldDescriptions() []pgconn.FieldDescription { return nil } +func (*eachRows) Values() ([]any, error) { panic("unexpected Values") } +func (*eachRows) RawValues() [][]byte { return nil } +func (*eachRows) Conn() *pgx.Conn { return nil } +func (*eachRows) TypeMap() *pgtype.Map { return nil } + +type eachConn struct { + rows *eachRows + calls int + intents []string + name string + args []any + queryErr error +} + +func (c *eachConn) WQuery(ctx context.Context, name, sql string, args ...any) (pgx.Rows, error) { + c.calls++ + c.name, c.args = name, args + c.rows.ctx = ctx + if c.queryErr != nil { + return nil, c.queryErr + } + if err := ctx.Err(); err != nil { + return nil, err + } + return c.rows, nil +} +func (*eachConn) WQueryRow(context.Context, string, string, ...any) pgx.Row { + panic("unexpected WQueryRow") +} +func (c *eachConn) CountIntent(name string) { c.intents = append(c.intents, name) } +func (*eachConn) WExec(context.Context, string, string, ...any) (pgconn.CommandTag, error) { + panic("unexpected WExec") +} +func (*eachConn) WCopyFrom(context.Context, string, pgx.Identifier, []string, pgx.CopyFromSource) (int64, error) { + panic("unexpected WCopyFrom") +} +func (*eachConn) PostExec(func() error) error { panic("unexpected PostExec") } + +func newEachConn() *eachConn { + return &eachConn{rows: &eachRows{data: []eachgen.Book{ + {ID: 1, Value: []byte("one")}, + {ID: 2, Value: []byte("two")}, + {ID: 3, Value: []byte("three")}, + }}} +} + +func TestGeneratedEachVisitsAndOwnsLifecycle(t *testing.T) { + for _, readOnly := range []bool{false, true} { + t.Run(map[bool]string{false: "queries", true: "readonly"}[readOnly], func(t *testing.T) { + conn := newEachConn() + q := eachgen.New(conn, nil) + var got []eachgen.Book + var visitCtx context.Context + visit := func(ctx context.Context, row eachgen.Book) (bool, error) { + if _, ok := ctx.Deadline(); !ok { + t.Fatal("visitor lacks query deadline") + } + visitCtx = ctx + got = append(got, row) + return true, nil + } + var err error + if readOnly { + err = q.AsReadOnly().ListBooksEach(context.Background(), 1, visit) + } else { + err = q.ListBooksEach(context.Background(), 1, visit) + } + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, conn.rows.data) { + t.Fatalf("rows=%v", got) + } + if !conn.rows.closed || conn.rows.closeCanceled { + t.Fatal("rows were not drained before cancellation") + } + if visitCtx.Err() != context.Canceled { + t.Fatal("query context outlived Each") + } + if conn.calls != 1 || !reflect.DeepEqual(conn.intents, []string{"eachgen.ListBooks"}) || !reflect.DeepEqual(conn.args, []any{int64(1)}) { + t.Fatalf("calls=%d intents=%v args=%v", conn.calls, conn.intents, conn.args) + } + got[0].Value[0] = 'X' + if string(got[1].Value) != "two" { + t.Fatal("retained rows alias") + } + }) + } +} + +func TestGeneratedEachStopAndErrors(t *testing.T) { + primary := errors.New("primary") + cleanup := errors.New("close-only failure") + for _, tc := range []struct { + name string + stop bool + visitorErr, scanErr, sourceErr, closeErr, queryErr error + want error + visits int + }{ + {name: "stop", stop: true, visits: 1}, + {name: "stop_close_error", stop: true, closeErr: cleanup, want: cleanup, visits: 1}, + {name: "visitor_error", visitorErr: primary, want: primary, visits: 1}, + {name: "visitor_wins_over_cleanup", visitorErr: primary, closeErr: cleanup, want: primary, visits: 1}, + {name: "scan_error", scanErr: primary, closeErr: cleanup, want: primary}, + {name: "source_error", sourceErr: primary, want: primary, visits: 1}, + {name: "end_close_error", closeErr: cleanup, want: cleanup, visits: 3}, + {name: "query_error", queryErr: primary, want: primary}, + } { + t.Run(tc.name, func(t *testing.T) { + conn := newEachConn() + conn.rows.scanErr, conn.rows.sourceErr, conn.rows.closeErr = tc.scanErr, tc.sourceErr, tc.closeErr + conn.rows.failAfter = 1 + conn.queryErr = tc.queryErr + visits := 0 + err := eachgen.New(conn, nil).ListBooksEach(context.Background(), 0, func(context.Context, eachgen.Book) (bool, error) { + visits++ + return !tc.stop, tc.visitorErr + }) + if !errors.Is(err, tc.want) || visits != tc.visits { + t.Fatalf("err=%v visits=%d, want %v/%d", err, visits, tc.want, tc.visits) + } + if tc.queryErr == nil && (!conn.rows.closed || conn.rows.closeCanceled) { + t.Fatal("ordinary errors must drain before own cancellation") + } + }) + } +} + +func TestGeneratedEachNilAndEmpty(t *testing.T) { + conn := newEachConn() + q := eachgen.New(conn, nil) + if err := q.ListBooksEach(context.Background(), 0, nil); err == nil { + t.Fatal("nil visitor accepted") + } + if conn.calls != 0 || len(conn.intents) != 0 { + t.Fatal("nil visitor reached connection") + } + conn.rows.data = nil + err := q.ListBooksEach(context.Background(), 0, func(context.Context, eachgen.Book) (bool, error) { + t.Fatal("empty result called visitor") + return false, nil + }) + if err != nil || !conn.rows.closed { + t.Fatalf("empty err=%v closed=%v", err, conn.rows.closed) + } +} + +func TestGeneratedEachCancellation(t *testing.T) { + primary := errors.New("read policy rejected row") + for _, tc := range []struct { + name string + preCancel, deadline, returnPrimary bool + }{ + {name: "before_query", preCancel: true}, + {name: "deadline_in_visitor", deadline: true}, + {name: "explicit_abort", returnPrimary: true}, + {name: "cancel_normal_stop"}, + } { + t.Run(tc.name, func(t *testing.T) { + var ctx context.Context + var cancel context.CancelFunc + if tc.deadline { + ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond) + } else { + ctx, cancel = context.WithCancel(context.Background()) + } + defer cancel() + if tc.preCancel { + cancel() + } + conn := newEachConn() + visits := 0 + err := eachgen.New(conn, nil).ListBooksEach(ctx, 0, func(ctx context.Context, row eachgen.Book) (bool, error) { + visits++ + if tc.deadline { + <-ctx.Done() + } else { + cancel() + } + if tc.returnPrimary { + return false, primary + } + return false, nil + }) + want := error(context.Canceled) + if tc.deadline { + want = context.DeadlineExceeded + } + if tc.returnPrimary { + want = primary + } + if !errors.Is(err, want) { + t.Fatalf("err=%v want=%v", err, want) + } + if tc.preCancel { + if visits != 0 { + t.Fatal("cancelled query called visitor") + } + } else if !conn.rows.closed || !conn.rows.closeCanceled { + t.Fatal("explicit abort/deadline must close under cancellation") + } + }) + } +} + +func TestGeneratedEachPanic(t *testing.T) { + conn := newEachConn() + marker := &struct{}{} + defer func() { + if recover() != marker { + t.Fatal("visitor panic not propagated") + } + if !conn.rows.closed || conn.rows.closeCanceled || conn.rows.ctx.Err() != context.Canceled { + t.Fatal("panic cleanup/lifetime order wrong") + } + }() + _ = eachgen.New(conn, nil).ListBooksEach(context.Background(), 0, func(context.Context, eachgen.Book) (bool, error) { panic(marker) }) +} + +func TestGeneratedEachScalarParamsReplicaAndCache(t *testing.T) { + for _, scalar := range []bool{false, true} { + conn := newEachConn() + q := eachgen.New(conn, nil) + var got []int64 + visit := func(_ context.Context, id int64) (bool, error) { got = append(got, id); return true, nil } + var err error + if scalar { + err = q.ListIDsEach(context.Background(), visit) + } else { + err = q.ListNamedScalarEach(context.Background(), visit) + } + if err != nil || !reflect.DeepEqual(got, []int64{1, 2, 3}) { + t.Fatalf("scalar=%v err=%v rows=%v", scalar, err, got) + } + } + conn := newEachConn() + // An unconfigured cache would fail if touched. Each must bypass it entirely. + q := eachgen.New(conn, new(dcache.DCache)) + err := q.ListCachedBooksEach(context.Background(), func(context.Context, eachgen.Book) (bool, error) { return false, nil }) + if err != nil || conn.calls != 1 { + t.Fatalf("cache bypass err=%v calls=%d", err, conn.calls) + } + conn = newEachConn() + q = eachgen.New(conn, nil) + if err := q.ListPrimaryBooksEach(context.Background(), func(context.Context, eachgen.Book) (bool, error) { return false, nil }); err != nil { + t.Fatal(err) + } + if len(conn.intents) != 0 { + t.Fatal("disabled CountIntent called") + } + if _, ok := reflect.TypeOf(q.AsReadOnly()).MethodByName("ListPrimaryBooksEach"); ok { + t.Fatal("primary-only method exposed on readonly receiver") + } + conn = newEachConn() + q = eachgen.New(conn, nil) + if err := q.ListRangeEach(context.Background(), eachgen.ListRangeParams{FromID: 1, ToID: 3}, func(context.Context, eachgen.Book) (bool, error) { return false, nil }); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(conn.args, []any{int64(1), int64(3)}) { + t.Fatalf("Params args=%v", conn.args) + } + replica := newEachConn() + if err := q.UseReplica(replica).ListBooksEach(context.Background(), 0, func(context.Context, eachgen.Book) (bool, error) { return false, nil }); err != nil { + t.Fatal(err) + } + if replica.calls != 1 || conn.calls != 1 { + t.Fatal("replica routing changed") + } +} diff --git a/internal/endtoend/testdata/wicked_each/go/db.go b/internal/endtoend/testdata/wicked_each/go/db.go new file mode 100644 index 0000000000..9ae78dedb1 --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/go/db.go @@ -0,0 +1,96 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package eachgen + +import ( + "github.com/stumble/dcache" + "github.com/stumble/wpgx" +) + +// BeforeDump allows you to edit result before dump. +type BeforeDump func(m *Book) + +type CacheQuerierConn interface { + GetCache() *dcache.DCache + GetConn() wpgx.WQuerier +} + +type CacheWGConn interface { + GetCache() *dcache.DCache + GetConn() wpgx.WGConn +} + +func New(db wpgx.WGConn, cache *dcache.DCache) *Queries { + return &Queries{db: db, cache: cache} +} + +type Queries struct { + db wpgx.WGConn + cache *dcache.DCache +} + +var _ CacheWGConn = (*Queries)(nil) + +func (q *Queries) GetCache() *dcache.DCache { + return q.cache +} + +func (q *Queries) GetConn() wpgx.WGConn { + return q.db +} + +func (q *Queries) AsReadOnly() *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: q.db, + cache: q.cache, + } +} + +func (q *Queries) WithTx(tx *wpgx.WTx) *Queries { + return &Queries{ + db: tx, + cache: q.cache, + } +} + +func (q *Queries) WithCache(cache *dcache.DCache) *Queries { + return &Queries{ + db: q.db, + cache: cache, + } +} + +func (q *Queries) UseReplica(replicaQuerier wpgx.WQuerier) *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: replicaQuerier, + cache: q.cache, + } +} + +type ReadOnlyQueries struct { + db wpgx.WQuerier + cache *dcache.DCache +} + +var _ CacheQuerierConn = (*ReadOnlyQueries)(nil) + +func (q *ReadOnlyQueries) WithCache(cache *dcache.DCache) *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: q.db, + cache: cache, + } +} + +func (q *ReadOnlyQueries) GetCache() *dcache.DCache { + return q.cache +} + +func (q *ReadOnlyQueries) GetConn() wpgx.WQuerier { + return q.db +} + +var Schema = ` +CREATE TABLE books (id bigint PRIMARY KEY, value bytea NOT NULL); +` diff --git a/internal/endtoend/testdata/wicked_each/go/models.go b/internal/endtoend/testdata/wicked_each/go/models.go new file mode 100644 index 0000000000..8beaf29b48 --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/go/models.go @@ -0,0 +1,12 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package eachgen + +import () + +type Book struct { + ID int64 `json:"id"` + Value []byte `json:"value"` +} diff --git a/internal/endtoend/testdata/wicked_each/go/querier.go b/internal/endtoend/testdata/wicked_each/go/querier.go new file mode 100644 index 0000000000..349799984c --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/go/querier.go @@ -0,0 +1,42 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package eachgen + +import ( + "context" +) + +type Querier interface { + ListBooks(ctx context.Context, visit int64) ([]Book, error) + + ListCachedBooks(ctx context.Context) ([]Book, error) + + ListIDs(ctx context.Context) ([]int64, error) + + ListNamedScalar(ctx context.Context) ([]int64, error) + + ListPrimaryBooks(ctx context.Context) ([]Book, error) + + ListRange(ctx context.Context, arg ListRangeParams) ([]Book, error) +} + +var _ Querier = (*Queries)(nil) + +// EachQuerier is separate so existing Querier implementations remain valid. +type EachQuerier interface { + ListBooksEach(ctx context.Context, visit int64, visit1 func(context.Context, Book) (more bool, err error)) error + + ListCachedBooksEach(ctx context.Context, visit func(context.Context, Book) (more bool, err error)) error + + ListIDsEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error + + ListNamedScalarEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error + + ListPrimaryBooksEach(ctx context.Context, visit func(context.Context, Book) (more bool, err error)) error + + ListRangeEach(ctx context.Context, arg ListRangeParams, visit func(context.Context, Book) (more bool, err error)) error +} + +var _ EachQuerier = (*Queries)(nil) diff --git a/internal/endtoend/testdata/wicked_each/go/query.sql.go b/internal/endtoend/testdata/wicked_each/go/query.sql.go new file mode 100644 index 0000000000..47ec342a91 --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/go/query.sql.go @@ -0,0 +1,669 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package eachgen + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "sync" + "time" + + "github.com/rs/zerolog/log" +) + +const listBooks = `-- name: ListBooks :many +SELECT id, value FROM books WHERE id >= $1 ORDER BY id +` + +// -- timeout: 1s +// -- each: true +func (q *Queries) ListBooks(ctx context.Context, visit int64) ([]Book, error) { + return _ListBooks(ctx, q.AsReadOnly(), visit) +} + +func (q *ReadOnlyQueries) ListBooks(ctx context.Context, visit int64) ([]Book, error) { + return _ListBooks(ctx, q, visit) +} + +func _ListBooks(ctx context.Context, q CacheQuerierConn, visit int64) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListBooks") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListBooks", listBooks, visit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +// ListBooksEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListBooksEach(ctx context.Context, visit int64, visit1 func(context.Context, Book) (more bool, err error)) error { + return _ListBooksEach(ctx, q.AsReadOnly(), visit, visit1) +} + +// ListBooksEach has the same consumption and lifetime contract as Queries.ListBooksEach. +func (q *ReadOnlyQueries) ListBooksEach(ctx context.Context, visit int64, visit1 func(context.Context, Book) (more bool, err error)) error { + return _ListBooksEach(ctx, q, visit, visit1) +} + +func _ListBooksEach(ctx context.Context, q CacheQuerierConn, visit int64, visit1 func(context.Context, Book) (more bool, err error)) error { + if visit1 == nil { + return fmt.Errorf("ListBooksEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListBooks") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListBooks", listBooks, visit) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *Book = new(Book) + if err := rows.Scan(&eachRow.ID, &eachRow.Value); err != nil { + return err + } + more, err := visit1(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +const listCachedBooks = `-- name: ListCachedBooks :many +SELECT id, value FROM books ORDER BY id +` + +// -- timeout: 1s +// -- cache: 5s +// -- each: true +func (q *Queries) ListCachedBooks(ctx context.Context) ([]Book, error) { + return _ListCachedBooks(ctx, q.AsReadOnly()) +} + +func (q *ReadOnlyQueries) ListCachedBooks(ctx context.Context) ([]Book, error) { + return _ListCachedBooks(ctx, q) +} + +func _ListCachedBooks(ctx context.Context, q CacheQuerierConn) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListCachedBooks") + dbRead := func() (any, time.Duration, error) { + cacheDuration := time.Duration(time.Millisecond * 5000) + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListCachedBooks", listCachedBooks) + if err != nil { + return []Book(nil), 0, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return []Book(nil), 0, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return []Book(nil), 0, err + } + return items, cacheDuration, nil + } + if q.GetCache() == nil { + items, _, err := dbRead() + return items.([]Book), err + } + var items []Book + err := q.GetCache().GetWithTtl(qctx, "eachgen:ListCachedBooks:", &items, dbRead, false, false) + if err != nil { + return nil, err + } + + return items, err +} + +// ListCachedBooksEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListCachedBooksEach(ctx context.Context, visit func(context.Context, Book) (more bool, err error)) error { + return _ListCachedBooksEach(ctx, q.AsReadOnly(), visit) +} + +// ListCachedBooksEach has the same consumption and lifetime contract as Queries.ListCachedBooksEach. +func (q *ReadOnlyQueries) ListCachedBooksEach(ctx context.Context, visit func(context.Context, Book) (more bool, err error)) error { + return _ListCachedBooksEach(ctx, q, visit) +} + +func _ListCachedBooksEach(ctx context.Context, q CacheQuerierConn, visit func(context.Context, Book) (more bool, err error)) error { + if visit == nil { + return fmt.Errorf("ListCachedBooksEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListCachedBooks") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListCachedBooks", listCachedBooks) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *Book = new(Book) + if err := rows.Scan(&eachRow.ID, &eachRow.Value); err != nil { + return err + } + more, err := visit(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +const listIDs = `-- name: ListIDs :many +SELECT id FROM books ORDER BY id +` + +// -- timeout: 1s +// -- each: true +func (q *Queries) ListIDs(ctx context.Context) ([]int64, error) { + return _ListIDs(ctx, q.AsReadOnly()) +} + +func (q *ReadOnlyQueries) ListIDs(ctx context.Context) ([]int64, error) { + return _ListIDs(ctx, q) +} + +func _ListIDs(ctx context.Context, q CacheQuerierConn) ([]int64, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListIDs") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListIDs", listIDs) + if err != nil { + return nil, err + } + defer rows.Close() + var items []int64 + for rows.Next() { + var id *int64 = new(int64) + if err := rows.Scan(id); err != nil { + return nil, err + } + items = append(items, *id) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +// ListIDsEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListIDsEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error { + return _ListIDsEach(ctx, q.AsReadOnly(), visit) +} + +// ListIDsEach has the same consumption and lifetime contract as Queries.ListIDsEach. +func (q *ReadOnlyQueries) ListIDsEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error { + return _ListIDsEach(ctx, q, visit) +} + +func _ListIDsEach(ctx context.Context, q CacheQuerierConn, visit func(context.Context, int64) (more bool, err error)) error { + if visit == nil { + return fmt.Errorf("ListIDsEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListIDs") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListIDs", listIDs) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *int64 = new(int64) + if err := rows.Scan(eachRow); err != nil { + return err + } + more, err := visit(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +const listNamedScalar = `-- name: ListNamedScalar :many +SELECT id AS more FROM books ORDER BY id +` + +// -- timeout: 1s +// -- each: true +func (q *Queries) ListNamedScalar(ctx context.Context) ([]int64, error) { + return _ListNamedScalar(ctx, q.AsReadOnly()) +} + +func (q *ReadOnlyQueries) ListNamedScalar(ctx context.Context) ([]int64, error) { + return _ListNamedScalar(ctx, q) +} + +func _ListNamedScalar(ctx context.Context, q CacheQuerierConn) ([]int64, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListNamedScalar") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListNamedScalar", listNamedScalar) + if err != nil { + return nil, err + } + defer rows.Close() + var items []int64 + for rows.Next() { + var more *int64 = new(int64) + if err := rows.Scan(more); err != nil { + return nil, err + } + items = append(items, *more) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +// ListNamedScalarEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListNamedScalarEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error { + return _ListNamedScalarEach(ctx, q.AsReadOnly(), visit) +} + +// ListNamedScalarEach has the same consumption and lifetime contract as Queries.ListNamedScalarEach. +func (q *ReadOnlyQueries) ListNamedScalarEach(ctx context.Context, visit func(context.Context, int64) (more bool, err error)) error { + return _ListNamedScalarEach(ctx, q, visit) +} + +func _ListNamedScalarEach(ctx context.Context, q CacheQuerierConn, visit func(context.Context, int64) (more bool, err error)) error { + if visit == nil { + return fmt.Errorf("ListNamedScalarEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListNamedScalar") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListNamedScalar", listNamedScalar) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *int64 = new(int64) + if err := rows.Scan(eachRow); err != nil { + return err + } + more, err := visit(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +const listPrimaryBooks = `-- name: ListPrimaryBooks :many +SELECT id, value FROM books ORDER BY id +` + +// -- timeout: 1s +// -- allow_replica: false +// -- count_intent: false +// -- each: true +func (q *Queries) ListPrimaryBooks(ctx context.Context) ([]Book, error) { + return _ListPrimaryBooks(ctx, q.AsReadOnly()) +} + +func _ListPrimaryBooks(ctx context.Context, q CacheQuerierConn) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListPrimaryBooks", listPrimaryBooks) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +// ListPrimaryBooksEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListPrimaryBooksEach(ctx context.Context, visit func(context.Context, Book) (more bool, err error)) error { + return _ListPrimaryBooksEach(ctx, q.AsReadOnly(), visit) +} + +func _ListPrimaryBooksEach(ctx context.Context, q CacheQuerierConn, visit func(context.Context, Book) (more bool, err error)) error { + if visit == nil { + return fmt.Errorf("ListPrimaryBooksEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListPrimaryBooks", listPrimaryBooks) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *Book = new(Book) + if err := rows.Scan(&eachRow.ID, &eachRow.Value); err != nil { + return err + } + more, err := visit(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +const listRange = `-- name: ListRange :many +SELECT id, value FROM books WHERE id BETWEEN $1 AND $2 ORDER BY id +` + +type ListRangeParams struct { + FromID int64 + ToID int64 +} + +// -- timeout: 1s +// -- each: true +func (q *Queries) ListRange(ctx context.Context, arg ListRangeParams) ([]Book, error) { + return _ListRange(ctx, q.AsReadOnly(), arg) +} + +func (q *ReadOnlyQueries) ListRange(ctx context.Context, arg ListRangeParams) ([]Book, error) { + return _ListRange(ctx, q, arg) +} + +func _ListRange(ctx context.Context, q CacheQuerierConn, arg ListRangeParams) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListRange") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListRange", listRange, arg.FromID, arg.ToID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +// ListRangeEach visits rows in query order without collecting a result slice. +// 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 +// 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. +func (q *Queries) ListRangeEach(ctx context.Context, arg ListRangeParams, visit func(context.Context, Book) (more bool, err error)) error { + return _ListRangeEach(ctx, q.AsReadOnly(), arg, visit) +} + +// ListRangeEach has the same consumption and lifetime contract as Queries.ListRangeEach. +func (q *ReadOnlyQueries) ListRangeEach(ctx context.Context, arg ListRangeParams, visit func(context.Context, Book) (more bool, err error)) error { + return _ListRangeEach(ctx, q, arg, visit) +} + +func _ListRangeEach(ctx context.Context, q CacheQuerierConn, arg ListRangeParams, visit func(context.Context, Book) (more bool, err error)) error { + if visit == nil { + return fmt.Errorf("ListRangeEach: nil visitor") + } + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("eachgen.ListRange") + rows, err := q.GetConn().WQuery(qctx, "eachgen.ListRange", listRange, arg.FromID, arg.ToID) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := qctx.Err(); err != nil { + return err + } + var eachRow *Book = new(Book) + if err := rows.Scan(&eachRow.ID, &eachRow.Value); err != nil { + return err + } + more, err := visit(qctx, *eachRow) + if err != nil { + return err + } + if err := 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. + rows.Close() + if err := rows.Err(); err != nil { + return err + } + return qctx.Err() +} + +//// auto generated functions + +func (q *Queries) Dump(ctx context.Context, beforeDump ...BeforeDump) ([]byte, error) { + sql := "SELECT id,value FROM \"books\" ORDER BY id ASC;" + rows, err := q.db.WQuery(ctx, "eachgen.Dump", sql) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var v Book + if err := rows.Scan(&v.ID, &v.Value); err != nil { + return nil, err + } + for _, applyBeforeDump := range beforeDump { + applyBeforeDump(&v) + } + items = append(items, v) + } + if err := rows.Err(); err != nil { + return nil, err + } + bytes, err := json.MarshalIndent(items, "", " ") + if err != nil { + return nil, err + } + return bytes, nil +} + +func (q *Queries) Load(ctx context.Context, data []byte) error { + sql := "INSERT INTO \"books\" (id,value) VALUES ($1,$2);" + rows := make([]Book, 0) + err := json.Unmarshal(data, &rows) + if err != nil { + return err + } + for _, row := range rows { + _, err := q.db.WExec(ctx, "eachgen.Load", sql, row.ID, row.Value) + if err != nil { + return err + } + } + return nil +} + +func hashIfLong(v string) string { + if len(v) > 64 { + hash := sha256.Sum256([]byte(v)) + return "h(" + hex.EncodeToString(hash[:]) + ")" + } + return v +} + +func ptrStr[T any](v *T) string { + if v == nil { + return "" + } + return fmt.Sprintf("%+v", *v) +} + +// eliminate unused error +var _ = log.Logger +var _ = fmt.Sprintf("") +var _ = time.Now() +var _ = json.RawMessage{} +var _ = sha256.Sum256(nil) +var _ = hex.EncodeToString(nil) +var _ = sync.WaitGroup{} diff --git a/internal/endtoend/testdata/wicked_each/query.sql b/internal/endtoend/testdata/wicked_each/query.sql new file mode 100644 index 0000000000..fcc67eddf9 --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/query.sql @@ -0,0 +1,32 @@ +-- name: ListBooks :many +-- -- timeout: 1s +-- -- each: true +SELECT id, value FROM books WHERE id >= @visit ORDER BY id; + +-- name: ListCachedBooks :many +-- -- timeout: 1s +-- -- cache: 5s +-- -- each: true +SELECT id, value FROM books ORDER BY id; + +-- name: ListIDs :many +-- -- timeout: 1s +-- -- each: true +SELECT id FROM books ORDER BY id; + +-- name: ListNamedScalar :many +-- -- timeout: 1s +-- -- each: true +SELECT id AS more FROM books ORDER BY id; + +-- name: ListPrimaryBooks :many +-- -- timeout: 1s +-- -- allow_replica: false +-- -- count_intent: false +-- -- each: true +SELECT id, value FROM books ORDER BY id; + +-- name: ListRange :many +-- -- timeout: 1s +-- -- each: true +SELECT id, value FROM books WHERE id BETWEEN @from_id AND @to_id ORDER BY id; diff --git a/internal/endtoend/testdata/wicked_each/schema.sql b/internal/endtoend/testdata/wicked_each/schema.sql new file mode 100644 index 0000000000..cb1bbfdb1d --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/schema.sql @@ -0,0 +1 @@ +CREATE TABLE books (id bigint PRIMARY KEY, value bytea NOT NULL); diff --git a/internal/endtoend/testdata/wicked_each/sqlc.yaml b/internal/endtoend/testdata/wicked_each/sqlc.yaml new file mode 100644 index 0000000000..56a83d3843 --- /dev/null +++ b/internal/endtoend/testdata/wicked_each/sqlc.yaml @@ -0,0 +1,11 @@ +version: '2' +sql: +- schema: schema.sql + queries: query.sql + engine: postgresql + gen: + go: + sql_package: wpgx + package: eachgen + out: go + emit_interface: true diff --git a/internal/endtoend/testdata/wicked_many/go/db.go b/internal/endtoend/testdata/wicked_many/go/db.go new file mode 100644 index 0000000000..43affcc992 --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/go/db.go @@ -0,0 +1,99 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package manycompat + +import ( + "github.com/stumble/dcache" + "github.com/stumble/wpgx" +) + +// BeforeDump allows you to edit result before dump. +type BeforeDump func(m *Book) + +type CacheQuerierConn interface { + GetCache() *dcache.DCache + GetConn() wpgx.WQuerier +} + +type CacheWGConn interface { + GetCache() *dcache.DCache + GetConn() wpgx.WGConn +} + +func New(db wpgx.WGConn, cache *dcache.DCache) *Queries { + return &Queries{db: db, cache: cache} +} + +type Queries struct { + db wpgx.WGConn + cache *dcache.DCache +} + +var _ CacheWGConn = (*Queries)(nil) + +func (q *Queries) GetCache() *dcache.DCache { + return q.cache +} + +func (q *Queries) GetConn() wpgx.WGConn { + return q.db +} + +func (q *Queries) AsReadOnly() *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: q.db, + cache: q.cache, + } +} + +func (q *Queries) WithTx(tx *wpgx.WTx) *Queries { + return &Queries{ + db: tx, + cache: q.cache, + } +} + +func (q *Queries) WithCache(cache *dcache.DCache) *Queries { + return &Queries{ + db: q.db, + cache: cache, + } +} + +func (q *Queries) UseReplica(replicaQuerier wpgx.WQuerier) *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: replicaQuerier, + cache: q.cache, + } +} + +type ReadOnlyQueries struct { + db wpgx.WQuerier + cache *dcache.DCache +} + +var _ CacheQuerierConn = (*ReadOnlyQueries)(nil) + +func (q *ReadOnlyQueries) WithCache(cache *dcache.DCache) *ReadOnlyQueries { + return &ReadOnlyQueries{ + db: q.db, + cache: cache, + } +} + +func (q *ReadOnlyQueries) GetCache() *dcache.DCache { + return q.cache +} + +func (q *ReadOnlyQueries) GetConn() wpgx.WQuerier { + return q.db +} + +var Schema = ` +CREATE TABLE books ( + id bigint PRIMARY KEY, + value bytea NOT NULL +); +` diff --git a/internal/endtoend/testdata/wicked_many/go/models.go b/internal/endtoend/testdata/wicked_many/go/models.go new file mode 100644 index 0000000000..c024ad0db7 --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/go/models.go @@ -0,0 +1,12 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package manycompat + +import () + +type Book struct { + ID int64 `json:"id"` + Value []byte `json:"value"` +} diff --git a/internal/endtoend/testdata/wicked_many/go/querier.go b/internal/endtoend/testdata/wicked_many/go/querier.go new file mode 100644 index 0000000000..a0e0449200 --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/go/querier.go @@ -0,0 +1,27 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package manycompat + +import ( + "context" +) + +type Querier interface { + DeleteAndList(ctx context.Context, beforeID int64) ([]DeleteAndListRow, error) + + ListBooks(ctx context.Context, minID int64) ([]Book, error) + + ListCachedBooks(ctx context.Context) ([]Book, error) + + ListCachedRange(ctx context.Context, arg ListCachedRangeParams) ([]Book, error) + + ListIDs(ctx context.Context) ([]int64, error) + + ListPrimaryBooks(ctx context.Context) ([]Book, error) + + PutBooks(ctx context.Context, arg PutBooksParams) ([]Book, error) +} + +var _ Querier = (*Queries)(nil) diff --git a/internal/endtoend/testdata/wicked_many/go/query.sql.go b/internal/endtoend/testdata/wicked_many/go/query.sql.go new file mode 100644 index 0000000000..1e42118616 --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/go/query.sql.go @@ -0,0 +1,414 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: query.sql + +package manycompat + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "sync" + "time" + + "github.com/rs/zerolog/log" +) + +const deleteAndList = `-- name: DeleteAndList :many +WITH changed AS (DELETE FROM books WHERE id < $1 RETURNING id, value) +SELECT id, value FROM changed ORDER BY id +` + +type DeleteAndListRow struct { + ID int64 + Value []byte +} + +// -- timeout: 1s +func (q *Queries) DeleteAndList(ctx context.Context, beforeID int64) ([]DeleteAndListRow, error) { + return _DeleteAndList(ctx, q.AsReadOnly(), beforeID) +} + +func (q *ReadOnlyQueries) DeleteAndList(ctx context.Context, beforeID int64) ([]DeleteAndListRow, error) { + return _DeleteAndList(ctx, q, beforeID) +} + +func _DeleteAndList(ctx context.Context, q CacheQuerierConn, beforeID int64) ([]DeleteAndListRow, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("manycompat.DeleteAndList") + rows, err := q.GetConn().WQuery(qctx, "manycompat.DeleteAndList", deleteAndList, beforeID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []DeleteAndListRow + for rows.Next() { + var i *DeleteAndListRow = new(DeleteAndListRow) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +const listBooks = `-- name: ListBooks :many +SELECT id, value FROM books WHERE id >= $1 ORDER BY id +` + +// -- timeout: 1s +func (q *Queries) ListBooks(ctx context.Context, minID int64) ([]Book, error) { + return _ListBooks(ctx, q.AsReadOnly(), minID) +} + +func (q *ReadOnlyQueries) ListBooks(ctx context.Context, minID int64) ([]Book, error) { + return _ListBooks(ctx, q, minID) +} + +func _ListBooks(ctx context.Context, q CacheQuerierConn, minID int64) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("manycompat.ListBooks") + rows, err := q.GetConn().WQuery(qctx, "manycompat.ListBooks", listBooks, minID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +const listCachedBooks = `-- name: ListCachedBooks :many +SELECT id, value FROM books ORDER BY id +` + +// -- timeout: 1s +// -- cache: 5s +func (q *Queries) ListCachedBooks(ctx context.Context) ([]Book, error) { + return _ListCachedBooks(ctx, q.AsReadOnly()) +} + +func (q *ReadOnlyQueries) ListCachedBooks(ctx context.Context) ([]Book, error) { + return _ListCachedBooks(ctx, q) +} + +func _ListCachedBooks(ctx context.Context, q CacheQuerierConn) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("manycompat.ListCachedBooks") + dbRead := func() (any, time.Duration, error) { + cacheDuration := time.Duration(time.Millisecond * 5000) + rows, err := q.GetConn().WQuery(qctx, "manycompat.ListCachedBooks", listCachedBooks) + if err != nil { + return []Book(nil), 0, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return []Book(nil), 0, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return []Book(nil), 0, err + } + return items, cacheDuration, nil + } + if q.GetCache() == nil { + items, _, err := dbRead() + return items.([]Book), err + } + var items []Book + err := q.GetCache().GetWithTtl(qctx, "manycompat:ListCachedBooks:", &items, dbRead, false, false) + if err != nil { + return nil, err + } + + return items, err +} + +const listCachedRange = `-- name: ListCachedRange :many +SELECT id, value FROM books WHERE id >= $1 AND id <= $2 ORDER BY id +` + +type ListCachedRangeParams struct { + FromID int64 + ToID int64 +} + +// CacheKey - cache key +func (arg ListCachedRangeParams) CacheKey() string { + prefix := "manycompat:ListCachedRange:" + return prefix + hashIfLong(fmt.Sprintf("%+v,%+v", arg.FromID, arg.ToID)) +} + +// -- timeout: 1s +// -- cache: 5s +func (q *Queries) ListCachedRange(ctx context.Context, arg ListCachedRangeParams) ([]Book, error) { + return _ListCachedRange(ctx, q.AsReadOnly(), arg) +} + +func (q *ReadOnlyQueries) ListCachedRange(ctx context.Context, arg ListCachedRangeParams) ([]Book, error) { + return _ListCachedRange(ctx, q, arg) +} + +func _ListCachedRange(ctx context.Context, q CacheQuerierConn, arg ListCachedRangeParams) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("manycompat.ListCachedRange") + dbRead := func() (any, time.Duration, error) { + cacheDuration := time.Duration(time.Millisecond * 5000) + rows, err := q.GetConn().WQuery(qctx, "manycompat.ListCachedRange", listCachedRange, arg.FromID, arg.ToID) + if err != nil { + return []Book(nil), 0, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return []Book(nil), 0, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return []Book(nil), 0, err + } + return items, cacheDuration, nil + } + if q.GetCache() == nil { + items, _, err := dbRead() + return items.([]Book), err + } + var items []Book + err := q.GetCache().GetWithTtl(qctx, arg.CacheKey(), &items, dbRead, false, false) + if err != nil { + return nil, err + } + + return items, err +} + +const listIDs = `-- name: ListIDs :many +SELECT id FROM books ORDER BY id +` + +// -- timeout: 1s +func (q *Queries) ListIDs(ctx context.Context) ([]int64, error) { + return _ListIDs(ctx, q.AsReadOnly()) +} + +func (q *ReadOnlyQueries) ListIDs(ctx context.Context) ([]int64, error) { + return _ListIDs(ctx, q) +} + +func _ListIDs(ctx context.Context, q CacheQuerierConn) ([]int64, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + q.GetConn().CountIntent("manycompat.ListIDs") + rows, err := q.GetConn().WQuery(qctx, "manycompat.ListIDs", listIDs) + if err != nil { + return nil, err + } + defer rows.Close() + var items []int64 + for rows.Next() { + var id *int64 = new(int64) + if err := rows.Scan(id); err != nil { + return nil, err + } + items = append(items, *id) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +const listPrimaryBooks = `-- name: ListPrimaryBooks :many +SELECT id, value FROM books ORDER BY id +` + +// -- timeout: 1s +// -- allow_replica: false +// -- count_intent: false +func (q *Queries) ListPrimaryBooks(ctx context.Context) ([]Book, error) { + return _ListPrimaryBooks(ctx, q.AsReadOnly()) +} + +func _ListPrimaryBooks(ctx context.Context, q CacheQuerierConn) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + rows, err := q.GetConn().WQuery(qctx, "manycompat.ListPrimaryBooks", listPrimaryBooks) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return items, err +} + +const putBooks = `-- name: PutBooks :many +INSERT INTO books (id, value) VALUES ($1, $2) +ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value +RETURNING id, value +` + +type PutBooksParams struct { + ID int64 + Value []byte +} + +// -- timeout: 1s +// -- invalidate: [ListCachedBooks] +func (q *Queries) PutBooks(ctx context.Context, arg PutBooksParams) ([]Book, error) { + return _PutBooks(ctx, q, arg) +} + +func _PutBooks(ctx context.Context, q CacheWGConn, arg PutBooksParams) ([]Book, error) { + qctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000) + defer cancel() + rows, err := q.GetConn().WQuery(qctx, "manycompat.PutBooks", putBooks, arg.ID, arg.Value) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var i *Book = new(Book) + if err := rows.Scan(&i.ID, &i.Value); err != nil { + return nil, err + } + items = append(items, *i) + } + if err := rows.Err(); err != nil { + return nil, err + } + + // invalidate + _ = q.GetConn().PostExec(func() error { + if q.GetCache() == nil { + return nil + } + anyErr := make(chan error, 1) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + key := "manycompat:ListCachedBooks:" + invalidateErr := q.GetCache().Invalidate(ctx, key) + if invalidateErr != nil { + log.Ctx(ctx).Error().Err(invalidateErr).Msgf( + "Failed to invalidate: %s", key) + anyErr <- invalidateErr + } + }() + wg.Wait() + close(anyErr) + return <-anyErr + }) + return items, err +} + +//// auto generated functions + +func (q *Queries) Dump(ctx context.Context, beforeDump ...BeforeDump) ([]byte, error) { + sql := "SELECT id,value FROM \"books\" ORDER BY id ASC;" + rows, err := q.db.WQuery(ctx, "manycompat.Dump", sql) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Book + for rows.Next() { + var v Book + if err := rows.Scan(&v.ID, &v.Value); err != nil { + return nil, err + } + for _, applyBeforeDump := range beforeDump { + applyBeforeDump(&v) + } + items = append(items, v) + } + if err := rows.Err(); err != nil { + return nil, err + } + bytes, err := json.MarshalIndent(items, "", " ") + if err != nil { + return nil, err + } + return bytes, nil +} + +func (q *Queries) Load(ctx context.Context, data []byte) error { + sql := "INSERT INTO \"books\" (id,value) VALUES ($1,$2);" + rows := make([]Book, 0) + err := json.Unmarshal(data, &rows) + if err != nil { + return err + } + for _, row := range rows { + _, err := q.db.WExec(ctx, "manycompat.Load", sql, row.ID, row.Value) + if err != nil { + return err + } + } + return nil +} + +func hashIfLong(v string) string { + if len(v) > 64 { + hash := sha256.Sum256([]byte(v)) + return "h(" + hex.EncodeToString(hash[:]) + ")" + } + return v +} + +func ptrStr[T any](v *T) string { + if v == nil { + return "" + } + return fmt.Sprintf("%+v", *v) +} + +// eliminate unused error +var _ = log.Logger +var _ = fmt.Sprintf("") +var _ = time.Now() +var _ = json.RawMessage{} +var _ = sha256.Sum256(nil) +var _ = hex.EncodeToString(nil) +var _ = sync.WaitGroup{} diff --git a/internal/endtoend/testdata/wicked_many/query.sql b/internal/endtoend/testdata/wicked_many/query.sql new file mode 100644 index 0000000000..d33832b51f --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/query.sql @@ -0,0 +1,35 @@ +-- name: ListBooks :many +-- -- timeout: 1s +SELECT id, value FROM books WHERE id >= @min_id ORDER BY id; + +-- name: ListCachedBooks :many +-- -- timeout: 1s +-- -- cache: 5s +SELECT id, value FROM books ORDER BY id; + +-- name: ListPrimaryBooks :many +-- -- timeout: 1s +-- -- allow_replica: false +-- -- count_intent: false +SELECT id, value FROM books ORDER BY id; + +-- name: ListIDs :many +-- -- timeout: 1s +SELECT id FROM books ORDER BY id; + +-- name: PutBooks :many +-- -- timeout: 1s +-- -- invalidate: [ListCachedBooks] +INSERT INTO books (id, value) VALUES (@id, @value) +ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value +RETURNING id, value; + +-- name: ListCachedRange :many +-- -- timeout: 1s +-- -- cache: 5s +SELECT id, value FROM books WHERE id >= @from_id AND id <= @to_id ORDER BY id; + +-- name: DeleteAndList :many +-- -- timeout: 1s +WITH changed AS (DELETE FROM books WHERE id < @before_id RETURNING *) +SELECT id, value FROM changed ORDER BY id; diff --git a/internal/endtoend/testdata/wicked_many/schema.sql b/internal/endtoend/testdata/wicked_many/schema.sql new file mode 100644 index 0000000000..82a3ca334e --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/schema.sql @@ -0,0 +1,4 @@ +CREATE TABLE books ( + id bigint PRIMARY KEY, + value bytea NOT NULL +); diff --git a/internal/endtoend/testdata/wicked_many/sqlc.yaml b/internal/endtoend/testdata/wicked_many/sqlc.yaml new file mode 100644 index 0000000000..ec99ac721c --- /dev/null +++ b/internal/endtoend/testdata/wicked_many/sqlc.yaml @@ -0,0 +1,11 @@ +version: '2' +sql: +- schema: schema.sql + queries: query.sql + engine: postgresql + gen: + go: + sql_package: wpgx + package: manycompat + out: go + emit_interface: true diff --git a/internal/plugin/codegen.pb.go b/internal/plugin/codegen.pb.go index c82aedc46f..3f6cf6c1a3 100644 --- a/internal/plugin/codegen.pb.go +++ b/internal/plugin/codegen.pb.go @@ -1090,6 +1090,9 @@ type WickedMetadata struct { PrimaryRelation *Identifier `protobuf:"bytes,3,opt,name=primary_relation,json=primaryRelation,proto3" json:"primary_relation,omitempty"` // This means a top-level SELECT, not a proof that a query is read-only. QueryIsSelect map[string]bool `protobuf:"bytes,4,rep,name=query_is_select,json=queryIsSelect,proto3" json:"query_is_select,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` + // A conservative rejection fact: writes, SELECT INTO or unsupported CTE statements. + // This is not a proof that called functions are free of side effects. + QueryHasMutation map[string]bool `protobuf:"bytes,5,rep,name=query_has_mutation,json=queryHasMutation,proto3" json:"query_has_mutation,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` } func (x *WickedMetadata) Reset() { @@ -1152,6 +1155,13 @@ func (x *WickedMetadata) GetQueryIsSelect() map[string]bool { return nil } +func (x *WickedMetadata) GetQueryHasMutation() map[string]bool { + if x != nil { + return x.QueryHasMutation + } + return nil +} + type GenerateResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1459,7 +1469,7 @@ var file_plugin_codegen_proto_rawDesc = []byte{ 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x57, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x48, 0x00, 0x52, 0x06, 0x77, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x42, 0x12, 0x0a, 0x10, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, - 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x22, 0xc2, 0x02, 0x0a, 0x0e, 0x57, 0x69, + 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x22, 0xe3, 0x03, 0x0a, 0x0e, 0x57, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x2e, 0x0a, 0x13, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x70, 0x72, 0x69, 0x6d, 0x61, @@ -1475,28 +1485,38 @@ var file_plugin_codegen_proto_rawDesc = []byte{ 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x57, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x49, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0d, 0x71, - 0x75, 0x65, 0x72, 0x79, 0x49, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x1a, 0x40, 0x0a, 0x12, - 0x51, 0x75, 0x65, 0x72, 0x79, 0x49, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x45, 0x6e, 0x74, - 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x36, - 0x0a, 0x10, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x22, 0x0a, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x0c, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x52, - 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x32, 0x4f, 0x0a, 0x0e, 0x43, 0x6f, 0x64, 0x65, 0x67, 0x65, - 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3d, 0x0a, 0x08, 0x47, 0x65, 0x6e, 0x65, - 0x72, 0x61, 0x74, 0x65, 0x12, 0x17, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x47, 0x65, - 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, - 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x7c, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x42, 0x0c, 0x43, 0x6f, 0x64, 0x65, 0x67, 0x65, 0x6e, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x73, 0x71, 0x6c, 0x63, 0x2d, 0x64, 0x65, 0x76, 0x2f, 0x73, 0x71, 0x6c, 0x63, 0x2f, - 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0xa2, - 0x02, 0x03, 0x50, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0xca, 0x02, - 0x06, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0xe2, 0x02, 0x12, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, 0x50, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x75, 0x65, 0x72, 0x79, 0x49, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x12, 0x5a, 0x0a, 0x12, + 0x71, 0x75, 0x65, 0x72, 0x79, 0x5f, 0x68, 0x61, 0x73, 0x5f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, + 0x6e, 0x2e, 0x57, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, + 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x48, 0x61, 0x73, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x10, 0x71, 0x75, 0x65, 0x72, 0x79, 0x48, 0x61, 0x73, + 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x40, 0x0a, 0x12, 0x51, 0x75, 0x65, 0x72, + 0x79, 0x49, 0x73, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, + 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, + 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x43, 0x0a, 0x15, 0x51, 0x75, + 0x65, 0x72, 0x79, 0x48, 0x61, 0x73, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, + 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, + 0x36, 0x0a, 0x10, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x22, 0x0a, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x46, 0x69, 0x6c, 0x65, + 0x52, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x32, 0x4f, 0x0a, 0x0e, 0x43, 0x6f, 0x64, 0x65, 0x67, + 0x65, 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3d, 0x0a, 0x08, 0x47, 0x65, 0x6e, + 0x65, 0x72, 0x61, 0x74, 0x65, 0x12, 0x17, 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x47, + 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, + 0x2e, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x7c, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x2e, + 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x42, 0x0c, 0x43, 0x6f, 0x64, 0x65, 0x67, 0x65, 0x6e, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x73, 0x71, 0x6c, 0x63, 0x2d, 0x64, 0x65, 0x76, 0x2f, 0x73, 0x71, 0x6c, 0x63, + 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0xa2, 0x02, 0x03, 0x50, 0x58, 0x58, 0xaa, 0x02, 0x06, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0xca, + 0x02, 0x06, 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0xe2, 0x02, 0x12, 0x50, 0x6c, 0x75, 0x67, 0x69, + 0x6e, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x06, + 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1511,7 +1531,7 @@ func file_plugin_codegen_proto_rawDescGZIP() []byte { return file_plugin_codegen_proto_rawDescData } -var file_plugin_codegen_proto_msgTypes = make([]protoimpl.MessageInfo, 18) +var file_plugin_codegen_proto_msgTypes = make([]protoimpl.MessageInfo, 19) var file_plugin_codegen_proto_goTypes = []interface{}{ (*File)(nil), // 0: plugin.File (*Settings)(nil), // 1: plugin.Settings @@ -1531,6 +1551,7 @@ var file_plugin_codegen_proto_goTypes = []interface{}{ (*Codegen_Process)(nil), // 15: plugin.Codegen.Process (*Codegen_WASM)(nil), // 16: plugin.Codegen.WASM nil, // 17: plugin.WickedMetadata.QueryIsSelectEntry + nil, // 18: plugin.WickedMetadata.QueryHasMutationEntry } var file_plugin_codegen_proto_depIdxs = []int32{ 2, // 0: plugin.Settings.codegen:type_name -> plugin.Codegen @@ -1555,14 +1576,15 @@ var file_plugin_codegen_proto_depIdxs = []int32{ 13, // 19: plugin.GenerateRequest.wicked:type_name -> plugin.WickedMetadata 8, // 20: plugin.WickedMetadata.primary_relation:type_name -> plugin.Identifier 17, // 21: plugin.WickedMetadata.query_is_select:type_name -> plugin.WickedMetadata.QueryIsSelectEntry - 0, // 22: plugin.GenerateResponse.files:type_name -> plugin.File - 12, // 23: plugin.CodegenService.Generate:input_type -> plugin.GenerateRequest - 14, // 24: plugin.CodegenService.Generate:output_type -> plugin.GenerateResponse - 24, // [24:25] is the sub-list for method output_type - 23, // [23:24] is the sub-list for method input_type - 23, // [23:23] is the sub-list for extension type_name - 23, // [23:23] is the sub-list for extension extendee - 0, // [0:23] is the sub-list for field type_name + 18, // 22: plugin.WickedMetadata.query_has_mutation:type_name -> plugin.WickedMetadata.QueryHasMutationEntry + 0, // 23: plugin.GenerateResponse.files:type_name -> plugin.File + 12, // 24: plugin.CodegenService.Generate:input_type -> plugin.GenerateRequest + 14, // 25: plugin.CodegenService.Generate:output_type -> plugin.GenerateResponse + 25, // [25:26] is the sub-list for method output_type + 24, // [24:25] is the sub-list for method input_type + 24, // [24:24] is the sub-list for extension type_name + 24, // [24:24] is the sub-list for extension extendee + 0, // [0:24] is the sub-list for field type_name } func init() { file_plugin_codegen_proto_init() } @@ -1785,7 +1807,7 @@ func file_plugin_codegen_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_plugin_codegen_proto_rawDesc, NumEnums: 0, - NumMessages: 18, + NumMessages: 19, NumExtensions: 0, NumServices: 1, }, diff --git a/protos/plugin/codegen.proto b/protos/plugin/codegen.proto index 1acf052aa8..b2483a8169 100644 --- a/protos/plugin/codegen.proto +++ b/protos/plugin/codegen.proto @@ -145,6 +145,9 @@ message WickedMetadata { Identifier primary_relation = 3; // This means a top-level SELECT, not a proof that a query is read-only. map query_is_select = 4; + // A conservative rejection fact: writes, SELECT INTO or unsupported CTE statements. + // This is not a proof that called functions are free of side effects. + map query_has_mutation = 5; } message GenerateResponse {