Repository navigation
feat(sql): add prepared statements primitive - #444
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (48)
📝 WalkthroughWalkthroughImplements typed prepared statements end-to-end: AST prepared-param refs and LoweredParam shape, author-facing prepare/PreparedStatement.execute(target, params) surface, runtime prepare/executePrepared execution and streaming/decoding refactor, adapter/renderer updates for prepared refs, Postgres named-cursor + driver prepared handling, SQLite executePrepared passthrough, example CLI usage, and comprehensive unit/integration/e2e tests. ChangesPrepared statements: author surface, runtime, drivers, adapters, and tests
Estimated code review effort: Suggested reviewers:
Poem:
✨ Finishing Touches🧪 Generate unit tests (beta)
|
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
3c3d708 to
f4669d9
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (3)
packages/2-sql/5-runtime/test/marker-verification.test.ts (1)
94-100: ⚡ Quick winMake
executePreparedfail fast in this non-prepared marker suite.Line 94 currently returns a successful async iterator, so an unintended switch to prepared execution could pass silently in this suite.
Suggested patch
- const executePrepared = vi.fn().mockImplementation(async function* () { - yield {} as Record<string, unknown>; - }); + const executePrepared = vi + .fn() + .mockRejectedValue(new Error('executePrepared not used in this test'));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/5-runtime/test/marker-verification.test.ts` around lines 94 - 100, The test's executePrepared mock currently yields an empty result, so if code accidentally switches to prepared execution this suite will still pass; update the executePrepared mock in marker-verification.test.ts (the executePrepared vi.fn() used alongside execute and query) to fail fast — either make the mock implementation throw immediately or return an async iterator that throws on first iteration — so any unintended prepared-path activation causes the test to fail.packages/2-sql/5-runtime/test/prepared.types.test-d.ts (1)
27-27: ⚡ Quick winReplace deprecated
expectTypeOf(...).toMatchTypeOf(...)matcher usage.Line 27 and Line 67 use
toMatchTypeOf, which is deprecated in this repo’s test-d.ts policy. Please switch totoExtend/toEqualTypeOfdepending on intent.♻️ Suggested update
- expectTypeOf<Decl>().toMatchTypeOf<Declaration<FixtureCT>>(); + expectTypeOf<Decl>().toExtend<Declaration<FixtureCT>>(); ... - expectTypeOf(ps.execute(runtime, { userId: 7 })).toMatchTypeOf<AsyncIterable<Row>>(); + expectTypeOf(ps.execute(runtime, { userId: 7 })).toExtend<AsyncIterable<Row>>();As per coding guidelines: "**/*.test-d.ts: Do not use the deprecated
toMatchTypeOf()matcher in Vitest'sexpectTypeOfAPI. UsetoExtend()... andtoEqualTypeOf<T>()for exact matches."Also applies to: 67-67
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/5-runtime/test/prepared.types.test-d.ts` at line 27, Replace the deprecated matcher call expectTypeOf<Decl>().toMatchTypeOf<Declaration<FixtureCT>>() (and the other occurrence using toMatchTypeOf) with the repo-approved matcher: use expectTypeOf<Decl>().toEqualTypeOf<Declaration<FixtureCT>>() if you need an exact type equality, or use expectTypeOf<Decl>().toExtend<Declaration<FixtureCT>>() if you intend a structural/subtype relationship; update both occurrences accordingly (referencing the Decl type and Declaration<FixtureCT> generic to locate the lines).packages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.ts (1)
39-40: ⚡ Quick winUse parameterized query for multi-row INSERT.
The INSERT statement uses string concatenation to build VALUES, which static analysis flagged. While safe here (controlled local data), it violates the parameterized query principle. Use Postgres
unnest()for a clean, fully parameterized multi-row insert.🔒 Proposed fix using unnest pattern
- const insertValues = Array.from({ length: 50 }, (_, i) => `(${i})`).join(', '); - await client.query(`insert into items (n) values ${insertValues}`); + const values = Array.from({ length: 50 }, (_, i) => i); + await client.query('insert into items (n) select * from unnest($1::int[])', [values]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.ts` around lines 39 - 40, The test builds a multi-row INSERT via string concatenation (insertValues) and executes it with client.query, which should be converted to a fully parameterized query; replace the hand-built VALUES string with a parameterized unnest-based insert (pass an array of numbers as a single parameter and use unnest($1::int[]) in the INSERT INTO items (n) SELECT * FROM unnest(...)) so the query uses client.query with parameters instead of string interpolation, keeping the same 0..49 values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/2-sql/5-runtime/test/marker-verification.test.ts`:
- Around line 94-100: The test's executePrepared mock currently yields an empty
result, so if code accidentally switches to prepared execution this suite will
still pass; update the executePrepared mock in marker-verification.test.ts (the
executePrepared vi.fn() used alongside execute and query) to fail fast — either
make the mock implementation throw immediately or return an async iterator that
throws on first iteration — so any unintended prepared-path activation causes
the test to fail.
In `@packages/2-sql/5-runtime/test/prepared.types.test-d.ts`:
- Line 27: Replace the deprecated matcher call
expectTypeOf<Decl>().toMatchTypeOf<Declaration<FixtureCT>>() (and the other
occurrence using toMatchTypeOf) with the repo-approved matcher: use
expectTypeOf<Decl>().toEqualTypeOf<Declaration<FixtureCT>>() if you need an
exact type equality, or use
expectTypeOf<Decl>().toExtend<Declaration<FixtureCT>>() if you intend a
structural/subtype relationship; update both occurrences accordingly
(referencing the Decl type and Declaration<FixtureCT> generic to locate the
lines).
In
`@packages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.ts`:
- Around line 39-40: The test builds a multi-row INSERT via string concatenation
(insertValues) and executes it with client.query, which should be converted to a
fully parameterized query; replace the hand-built VALUES string with a
parameterized unnest-based insert (pass an array of numbers as a single
parameter and use unnest($1::int[]) in the INSERT INTO items (n) SELECT * FROM
unnest(...)) so the query uses client.query with parameters instead of string
interpolation, keeping the same 0..49 values.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 6bf96e58-b1ba-448b-be29-73071509aad2
📒 Files selected for processing (83)
docs/architecture docs/adrs/ADR 210 - Prepared Statements - Author Surface and Driver SPI.mdexamples/prisma-next-demo-sqlite/src/main.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-by-email-prepared.tsexamples/prisma-next-demo/src/main.tsexamples/prisma-next-demo/src/queries/get-user-by-email-prepared.tspackages/2-sql/4-lanes/relational-core/src/ast/driver-types.tspackages/2-sql/4-lanes/relational-core/src/ast/types.tspackages/2-sql/4-lanes/relational-core/src/ast/util.tspackages/2-sql/4-lanes/relational-core/src/expression.tspackages/2-sql/4-lanes/relational-core/src/middleware/param-ref-mutator.tspackages/2-sql/4-lanes/relational-core/src/sql-execution-plan.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.tspackages/2-sql/4-lanes/relational-core/test/middleware/param-ref-mutator.test.tspackages/2-sql/4-lanes/relational-core/test/sql-execution-plan.types.test-d.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.tspackages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.tspackages/2-sql/4-lanes/sql-builder/src/scope.tspackages/2-sql/4-lanes/sql-builder/src/types/grouped-query.tspackages/2-sql/4-lanes/sql-builder/src/types/select-query.tspackages/2-sql/4-lanes/sql-builder/src/types/shared.tspackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/encoding.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/lower-sql-plan.tspackages/2-sql/5-runtime/src/middleware/budgets.tspackages/2-sql/5-runtime/src/prepared/bind-site-params.tspackages/2-sql/5-runtime/src/prepared/encode-prepared.tspackages/2-sql/5-runtime/src/prepared/prepared-statement.tspackages/2-sql/5-runtime/src/prepared/types.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/async-iterable-result.test.tspackages/2-sql/5-runtime/test/before-compile-chain.test.tspackages/2-sql/5-runtime/test/codec-async.test.tspackages/2-sql/5-runtime/test/codec-decode-ctx.test.tspackages/2-sql/5-runtime/test/content-hash.test.tspackages/2-sql/5-runtime/test/decode-error-passthrough.test.tspackages/2-sql/5-runtime/test/intercept-decoding.test.tspackages/2-sql/5-runtime/test/marker-verification.test.tspackages/2-sql/5-runtime/test/marker-vs-intercept-ordering.test.tspackages/2-sql/5-runtime/test/prepared.test.tspackages/2-sql/5-runtime/test/prepared.types.test-d.tspackages/2-sql/5-runtime/test/runtime-ctx-passthrough.test.tspackages/2-sql/5-runtime/test/scope-plumbing.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/sql-runtime-abort.test.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/2-sql/5-runtime/test/utils.tspackages/3-extensions/cipherstash/src/middleware/bulk-encrypt.tspackages/3-extensions/cipherstash/test/helpers.test.tspackages/3-extensions/cipherstash/test/operator-lowering-equality.test.tspackages/3-extensions/cipherstash/test/operator-lowering-text-search.test.tspackages/3-extensions/cipherstash/test/operator-lowering.test.tspackages/3-extensions/postgres/src/runtime/postgres.tspackages/3-extensions/sql-orm-client/src/query-plan-aggregate.tspackages/3-extensions/sql-orm-client/src/query-plan-meta.tspackages/3-extensions/sql-orm-client/src/where-binding.tspackages/3-extensions/sql-orm-client/test/query-plan-aggregate.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tspackages/3-extensions/sql-orm-client/test/raw-compiled-query.test.tspackages/3-extensions/sqlite/src/runtime/sqlite.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/data-transform.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/adapter.test.tspackages/3-targets/6-adapters/postgres/test/migrations/data-transform.test.tspackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/test/adapter.test.tspackages/3-targets/7-drivers/postgres/src/exports/runtime.tspackages/3-targets/7-drivers/postgres/src/named-cursor.tspackages/3-targets/7-drivers/postgres/src/postgres-driver.tspackages/3-targets/7-drivers/postgres/test/driver.errors.test.tspackages/3-targets/7-drivers/postgres/test/driver.prepared.integration.test.tspackages/3-targets/7-drivers/postgres/test/driver.prepared.test.tspackages/3-targets/7-drivers/postgres/test/named-cursor.test.tspackages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.tspackages/3-targets/7-drivers/postgres/vitest.config.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tstest/e2e/framework/test/runtime.prepared.test.tstest/e2e/framework/test/sqlite/prepared.test.tstest/utils/package.jsontest/utils/src/exports/index.tstest/utils/src/lowered-params.tstest/utils/tsdown.config.ts
f4669d9 to
5a0faed
Compare
| paramCount: number, | ||
| ): readonly ParamMetadata[] { | ||
| if (ast === undefined) { | ||
| return new Array(paramCount).fill(NO_METADATA); |
There was a problem hiding this comment.
| return new Array(paramCount).fill(NO_METADATA); | |
| return Array.from({ length: paramCount }).fill(NO_METADATA); |
| return Array.from({ length: paramCount }, (_, i): ParamMetadata => { | ||
| const ref = refs[i]; | ||
| if (!ref) return NO_METADATA; | ||
| if (ref.kind === 'prepared-param-ref') { | ||
| return { codec: { codecId: ref.codecId }, name: ref.name }; | ||
| } | ||
| return { codec: ref.codec, name: ref.name }; | ||
| }); |
There was a problem hiding this comment.
is collectOrderedParamRefs expected to return paramCount refs? could we map over its result instead?
| const stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>( | ||
| exec, | ||
| this.middleware, | ||
| this.ctx, |
There was a problem hiding this comment.
I think this used to use execMiddlewareCtx before extracting streamRows
| const self = this; | ||
| const signal = options?.signal; | ||
| const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal }; | ||
| const execMiddlewareCtx = signal === undefined ? self.ctx : { ...self.ctx, signal }; |
There was a problem hiding this comment.
do we have a way to populate scope here based on the type of queryable?
5a0faed to
54b849a
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/3-targets/7-drivers/postgres/src/postgres-driver.ts`:
- Around line 63-69: The handle allocator currently globals prepared statement
names per driver (createHandleAllocator / HandleAllocator) causing cross-client
collisions; change it to store handles per physical client by replacing the
single incrementing `next` with a per-client map (e.g.,
WeakMap<Client|PoolClient, string>) and move the lookup/mint logic to after you
acquire the concrete client for execution so that `request.handle` is resolved
per-client (lookup in WeakMap, mint a new per-client name if missing) before
checking `client.parsedStatements`/executing the PreparedStatement; update all
uses (including the other occurrences noted at lines ~148-156) to consult this
per-client mapping rather than a single driver-scoped counter.
In
`@packages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.ts`:
- Around line 26-28: The test allocates the dev DB via createDevDatabase()
before creating/connecting the pg.Client but doesn't guarantee database.close()
runs if client.connect() or client.end() throws; ensure database.close() is
always called by moving the try/finally to start immediately after
createDevDatabase() (or wrap createDevDatabase() in its own try/finally), and in
the finally always call await database.close() regardless of client state,
handling/rethrowing client.end() failures separately so a rejected client.end()
cannot short-circuit database.close(); update the code paths around
client.connect(), client.end(), and database.close() (referencing
createDevDatabase, client.connect, client.end, database.close) to enforce this
cleanup.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 2b0e7cad-595b-417d-8a9f-8499de41df8c
📒 Files selected for processing (83)
docs/architecture docs/adrs/ADR 210 - Prepared Statements - Author Surface and Driver SPI.mdexamples/prisma-next-demo-sqlite/src/main.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-by-email-prepared.tsexamples/prisma-next-demo/src/main.tsexamples/prisma-next-demo/src/queries/get-user-by-email-prepared.tspackages/2-sql/4-lanes/relational-core/src/ast/driver-types.tspackages/2-sql/4-lanes/relational-core/src/ast/types.tspackages/2-sql/4-lanes/relational-core/src/ast/util.tspackages/2-sql/4-lanes/relational-core/src/expression.tspackages/2-sql/4-lanes/relational-core/src/middleware/param-ref-mutator.tspackages/2-sql/4-lanes/relational-core/src/sql-execution-plan.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.tspackages/2-sql/4-lanes/relational-core/test/middleware/param-ref-mutator.test.tspackages/2-sql/4-lanes/relational-core/test/sql-execution-plan.types.test-d.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.tspackages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.tspackages/2-sql/4-lanes/sql-builder/src/scope.tspackages/2-sql/4-lanes/sql-builder/src/types/grouped-query.tspackages/2-sql/4-lanes/sql-builder/src/types/select-query.tspackages/2-sql/4-lanes/sql-builder/src/types/shared.tspackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/encoding.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/lower-sql-plan.tspackages/2-sql/5-runtime/src/middleware/budgets.tspackages/2-sql/5-runtime/src/prepared/bind-site-params.tspackages/2-sql/5-runtime/src/prepared/encode-prepared.tspackages/2-sql/5-runtime/src/prepared/prepared-statement.tspackages/2-sql/5-runtime/src/prepared/types.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/async-iterable-result.test.tspackages/2-sql/5-runtime/test/before-compile-chain.test.tspackages/2-sql/5-runtime/test/codec-async.test.tspackages/2-sql/5-runtime/test/codec-decode-ctx.test.tspackages/2-sql/5-runtime/test/content-hash.test.tspackages/2-sql/5-runtime/test/decode-error-passthrough.test.tspackages/2-sql/5-runtime/test/intercept-decoding.test.tspackages/2-sql/5-runtime/test/marker-verification.test.tspackages/2-sql/5-runtime/test/marker-vs-intercept-ordering.test.tspackages/2-sql/5-runtime/test/prepared.test.tspackages/2-sql/5-runtime/test/prepared.types.test-d.tspackages/2-sql/5-runtime/test/runtime-ctx-passthrough.test.tspackages/2-sql/5-runtime/test/scope-plumbing.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/sql-runtime-abort.test.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/2-sql/5-runtime/test/utils.tspackages/3-extensions/cipherstash/src/middleware/bulk-encrypt.tspackages/3-extensions/cipherstash/test/helpers.test.tspackages/3-extensions/cipherstash/test/operator-lowering-equality.test.tspackages/3-extensions/cipherstash/test/operator-lowering-text-search.test.tspackages/3-extensions/cipherstash/test/operator-lowering.test.tspackages/3-extensions/postgres/src/runtime/postgres.tspackages/3-extensions/sql-orm-client/src/query-plan-aggregate.tspackages/3-extensions/sql-orm-client/src/query-plan-meta.tspackages/3-extensions/sql-orm-client/src/where-binding.tspackages/3-extensions/sql-orm-client/test/query-plan-aggregate.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tspackages/3-extensions/sql-orm-client/test/raw-compiled-query.test.tspackages/3-extensions/sqlite/src/runtime/sqlite.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/data-transform.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/adapter.test.tspackages/3-targets/6-adapters/postgres/test/migrations/data-transform.test.tspackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/test/adapter.test.tspackages/3-targets/7-drivers/postgres/src/exports/runtime.tspackages/3-targets/7-drivers/postgres/src/named-cursor.tspackages/3-targets/7-drivers/postgres/src/postgres-driver.tspackages/3-targets/7-drivers/postgres/test/driver.errors.test.tspackages/3-targets/7-drivers/postgres/test/driver.prepared.integration.test.tspackages/3-targets/7-drivers/postgres/test/driver.prepared.test.tspackages/3-targets/7-drivers/postgres/test/named-cursor.test.tspackages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.tspackages/3-targets/7-drivers/postgres/vitest.config.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tstest/e2e/framework/test/runtime.prepared.test.tstest/e2e/framework/test/sqlite/prepared.test.tstest/utils/package.jsontest/utils/src/exports/index.tstest/utils/src/lowered-params.tstest/utils/tsdown.config.ts
✅ Files skipped from review due to trivial changes (2)
- packages/3-targets/7-drivers/postgres/vitest.config.ts
- packages/2-sql/5-runtime/test/intercept-decoding.test.ts
🚧 Files skipped from review as they are similar to previous changes (66)
- examples/prisma-next-demo/src/queries/get-user-by-email-prepared.ts
- packages/3-extensions/sql-orm-client/src/query-plan-meta.ts
- packages/2-sql/5-runtime/test/marker-vs-intercept-ordering.test.ts
- test/utils/src/exports/index.ts
- packages/2-sql/4-lanes/relational-core/src/sql-execution-plan.ts
- packages/2-sql/5-runtime/src/lower-sql-plan.ts
- packages/2-sql/4-lanes/relational-core/test/sql-execution-plan.types.test-d.ts
- packages/2-sql/4-lanes/relational-core/src/ast/driver-types.ts
- packages/2-sql/4-lanes/relational-core/test/utils.ts
- packages/2-sql/5-runtime/test/content-hash.test.ts
- packages/2-sql/5-runtime/src/prepared/bind-site-params.ts
- packages/2-sql/5-runtime/test/runtime-ctx-passthrough.test.ts
- packages/2-sql/5-runtime/test/sql-family-adapter.test.ts
- packages/3-extensions/cipherstash/test/helpers.test.ts
- packages/3-extensions/cipherstash/test/operator-lowering-text-search.test.ts
- test/utils/package.json
- packages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.ts
- packages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.ts
- test/e2e/framework/test/sqlite/prepared.test.ts
- packages/2-sql/4-lanes/sql-builder/src/types/grouped-query.ts
- packages/3-targets/7-drivers/postgres/test/driver.prepared.test.ts
- packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
- packages/2-sql/5-runtime/src/exports/index.ts
- packages/2-sql/4-lanes/relational-core/src/ast/util.ts
- packages/2-sql/5-runtime/src/prepared/encode-prepared.ts
- packages/3-targets/7-drivers/postgres/test/named-cursor.test.ts
- packages/3-extensions/sql-orm-client/test/raw-compiled-query.test.ts
- test/utils/src/lowered-params.ts
- packages/2-sql/4-lanes/sql-builder/src/types/shared.ts
- packages/2-sql/5-runtime/src/middleware/budgets.ts
- packages/2-sql/4-lanes/relational-core/src/middleware/param-ref-mutator.ts
- packages/3-extensions/cipherstash/test/operator-lowering-equality.test.ts
- packages/3-extensions/sqlite/src/runtime/sqlite.ts
- packages/3-targets/6-adapters/postgres/test/adapter.test.ts
- packages/2-sql/5-runtime/src/prepared/prepared-statement.ts
- packages/2-sql/5-runtime/test/prepared.types.test-d.ts
- packages/3-extensions/cipherstash/test/operator-lowering.test.ts
- packages/3-extensions/sql-orm-client/src/query-plan-aggregate.ts
- packages/2-sql/5-runtime/src/prepared/types.ts
- packages/2-sql/5-runtime/test/utils.ts
- packages/2-sql/4-lanes/sql-builder/src/scope.ts
- packages/2-sql/5-runtime/test/sql-runtime-abort.test.ts
- packages/2-sql/4-lanes/relational-core/src/expression.ts
- packages/3-targets/6-adapters/sqlite/test/adapter.test.ts
- packages/2-sql/5-runtime/test/async-iterable-result.test.ts
- packages/3-targets/7-drivers/postgres/test/driver.prepared.integration.test.ts
- packages/3-targets/6-adapters/postgres/test/migrations/data-transform.test.ts
- packages/2-sql/5-runtime/test/decode-error-passthrough.test.ts
- examples/prisma-next-demo/src/main.ts
- packages/2-sql/4-lanes/sql-builder/src/types/select-query.ts
- packages/2-sql/5-runtime/test/codec-decode-ctx.test.ts
- packages/3-extensions/postgres/src/runtime/postgres.ts
- packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts
- packages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.ts
- packages/3-targets/7-drivers/postgres/src/named-cursor.ts
- packages/3-targets/7-drivers/postgres/src/exports/runtime.ts
- packages/3-targets/7-drivers/postgres/test/driver.errors.test.ts
- packages/2-sql/5-runtime/test/codec-async.test.ts
- packages/2-sql/5-runtime/test/sql-runtime.test.ts
- packages/2-sql/5-runtime/src/codecs/decoding.ts
- examples/prisma-next-demo-sqlite/src/main.ts
- packages/2-sql/4-lanes/relational-core/test/middleware/param-ref-mutator.test.ts
- packages/2-sql/5-runtime/test/prepared.test.ts
- test/e2e/framework/test/runtime.prepared.test.ts
- packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
- packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
| function createHandleAllocator(): HandleAllocator { | ||
| // Driver-scoped so a single PreparedStatement reused across multiple | ||
| // Connections/Transactions of the same driver always sees one handle. | ||
| let next = 1; | ||
| return { | ||
| mint: () => `pn_${next++}`, | ||
| }; |
There was a problem hiding this comment.
Store prepared handles per physical client, not one per driver.
This caches a single statement name in request.handle, which breaks pooled reuse. If the same PreparedStatement is first executed on client A as pn_1 and on client B as pn_2, the shared slot can only remember one of them; the next execute on the other client misses parsedStatements, falls into 26000, and keeps churning names/retries instead of actually reusing the prepared plan. The opaque handle needs to carry per-client state (for example, a WeakMap<Client | PoolClient, string>) and the lookup/mint has to happen after acquiring the concrete client for this execution.
Also applies to: 148-156
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/3-targets/7-drivers/postgres/src/postgres-driver.ts` around lines 63
- 69, The handle allocator currently globals prepared statement names per driver
(createHandleAllocator / HandleAllocator) causing cross-client collisions;
change it to store handles per physical client by replacing the single
incrementing `next` with a per-client map (e.g., WeakMap<Client|PoolClient,
string>) and move the lookup/mint logic to after you acquire the concrete client
for execution so that `request.handle` is resolved per-client (lookup in
WeakMap, mint a new per-client name if missing) before checking
`client.parsedStatements`/executing the PreparedStatement; update all uses
(including the other occurrences noted at lines ~148-156) to consult this
per-client mapping rather than a single driver-scoped counter.
There was a problem hiding this comment.
This is incorrect. pg handles reparsing of multiple clients transparently via name property on the statement.
There was a problem hiding this comment.
@SevInf, you're right — I apologize for the incorrect review. Each pg Client maintains its own parsedStatements map, so when a connection that hasn't seen pn_1 executes a named query, pg (and NamedCursor.submitNamed) automatically sends a Parse message for that connection. The single driver-scoped name in request.handle is the correct design: it serves as a stable statement identity, and each physical connection lazily parses it on first use without any cross-client collision. There's no need for per-client name tracking.
✏️ Learnings added
Learnt from: SevInf
Repo: prisma/prisma-next PR: 444
File: packages/3-targets/7-drivers/postgres/src/postgres-driver.ts:63-69
Timestamp: 2026-05-19T17:03:30.809Z
Learning: In the prisma/prisma-next Postgres driver (`packages/3-targets/7-drivers/postgres/src/postgres-driver.ts`), a single driver-scoped prepared-statement name (e.g. `pn_1`) stored in `request.handle` is safe for use across pooled/multiple `pg` clients. Each `pg` `Client` maintains its own `parsedStatements` map; if the name is absent from a given connection's map, `pg` (and `NamedCursor.submitNamed`) automatically sends a Parse message for that connection. Do NOT flag this as a cross-client collision bug — the per-client lazy-parse behavior is intentional and correct.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: wmadden
Repo: prisma/prisma-next PR: 38
File: packages/2-sql/3-tooling/family/src/core/migrations/plan-helpers.ts:40-47
Timestamp: 2025-12-26T23:02:40.679Z
Learning: In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning. Favor reliable, battle-tested functions and ensure dependencies are reviewed for tree-shaking and bundle size. If a lightweight utility suffices, consider modern native approaches or smaller libs.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 191
File: packages/1-framework/3-tooling/cli/src/commands/contract-emit.ts:5-5
Timestamp: 2026-03-01T13:54:21.863Z
Learning: In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling files). Apply this in TypeScript files, replacing imports from 'node:path' with 'pathe' and adjusting API usage accordingly. Ensure consistent usage across all modules and update any affected tests or tooling imports when refactoring.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 234
File: packages/2-sql/4-lanes/sql-lane/test/rich-mutation.test.ts:2-2
Timestamp: 2026-03-23T10:01:15.075Z
Learning: In the prisma/prisma-next repo, prefer using `pathe` over Node’s built-in `node:path`. For any TypeScript file (including tests, test helpers, and integration tooling) replace imports like `import { dirname, join } from 'node:path'` with `import { dirname, join } from 'pathe'`—especially when code reads files/fixtures from disk.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 294
File: packages/2-mongo-family/2-query/query-ast/src/read-plan.ts:4-10
Timestamp: 2026-04-04T10:08:34.220Z
Learning: In prisma/prisma-next, don’t flag declaration-emit/typecheck warnings/errors when a file uses an intentional nominal/branding pattern with a non-exported `declare const <brand>: unique symbol` as a computed property key on an exported interface (e.g., `readonly [__mongoReadPlanRow]: ...` / `readonly [aggregateResultBrand]: ...`). The `unique symbol` must remain unexported to prevent external forging, while the branded property key staying on the exported interface provides compile-time discrimination. If the build correctly emits declaration files for this pattern, treat it as intentional rather than a declaration-emit error.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 293
File: packages/1-framework/1-core/shared/contract/src/canonicalization.ts:203-216
Timestamp: 2026-04-04T12:19:05.250Z
Learning: In the prisma/prisma-next repository, do not treat `Array.prototype.sort` comparators as “potentially non-deterministic” solely because the comparator does not include explicit tie-breaking keys. This is because the repo’s required runtime is Node >= 24, where `Array.prototype.sort` is stable (equal elements retain their original relative order via a stable sort such as TimSort). Therefore, equal-comparing elements should remain deterministic without additional tie-break logic.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 334
File: packages/2-mongo-family/9-family/src/core/control-instance.ts:204-228
Timestamp: 2026-04-13T15:54:52.337Z
Learning: When reviewing TypeScript code in this repo, do not assume a property is potentially `undefined` at a call site just because an arktype schema definition uses the DSL syntax `'key?': 'type'` (a quoted string key with a trailing `?`). This DSL notation is not the same as TypeScript optional properties (`key?: type`). To determine whether `key` is truly optional/undefined-capable, verify the actual exported TypeScript type declaration (e.g., `contract-types.ts`) and the runtime validation schema (e.g., `validate-contract.ts`) for that property; only then should the review flag call-site handling for potential `undefined`.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 339
File: test/integration/test/cli.init-templates.e2e.test.ts:96-96
Timestamp: 2026-04-15T19:33:48.733Z
Learning: In prisma/prisma-next, when writing tests that run TypeScript compilation (e.g., via `tsc --noEmit`), avoid hardcoded timeout numbers (such as `30_000`). Instead, use `prisma-next/test-utils` timeout helpers—specifically `timeouts.typeScriptCompilation` (implemented in `test/utils/src/timeouts.ts`) for `tsc` compilation scenarios. Use `timeouts.spinUpPpgDev` for PostgreSQL server startup and `timeouts.databaseOperation` for database operation scenarios.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 364
File: packages/3-targets/3-targets/postgres/src/core/migrations/operations/data-transform.ts:45-50
Timestamp: 2026-04-22T11:03:41.124Z
Learning: In prisma/prisma-next (including packages/3-targets), avoid code review flags for missing “empty-array guards” or for not enforcing non-empty tuple types on API option types. For example, for a field typed like `DataTransformOptions.run: DataTransformClosure | readonly DataTransformClosure[]`, prefer trusting callers and the existing type contracts rather than requiring extra defensive type narrowing or runtime non-emptiness checks/guards for empty/edge-case inputs.
Learnt from: saevarb
Repo: prisma/prisma-next PR: 394
File: packages/1-framework/3-tooling/migration/src/graph-ops.ts:50-54
Timestamp: 2026-04-29T12:44:59.376Z
Learning: In TypeScript overload implementations, an internal “implementation-only” cast (e.g., `state as unknown as <ReturnType>`) can be safe and intentional when the public overload signatures and their structural typing prevent callers from reaching the implementation with an incompatible type. In these cases, reviewers should not flag the cast as a blind/unsafe cast, since compile-time overload enforcement substitutes for a runtime type guard. Don’t require an added `typeof`/runtime check solely to silence the cast when the overload design already prevents invalid inputs.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 417
File: packages/3-extensions/sql-orm-client/src/types.ts:309-318
Timestamp: 2026-05-08T17:07:07.145Z
Learning: In prisma/prisma-next code, prefer `ifDefined` from `prisma-next/utils/defined` for conditional object spreads instead of inline ternary-based spreads. For example, when building option objects for `ParamRef.of` (or similar codec/param construction), wrap optional values with `ifDefined(...)` so that the spread only includes the property when the value is defined, improving readability and avoiding “{...cond ? {a: b} : {}}”-style patterns. Ensure you import `ifDefined` from `prisma-next/utils/defined` and use it consistently for these conditional spreads.
Learnt from: wmadden
Repo: prisma/prisma-next PR: 474
File: packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts:68-74
Timestamp: 2026-05-11T05:34:02.685Z
Learning: When reviewing code in this repo (prisma/prisma-next) for the `doc-maintenance` rule/no-transient-artefacts guideline, do not flag Linear ticket IDs in source-code comments (e.g., `TML-2397`) as violations. The rule should only consider truly transient artefacts as forbidden—specifically milestone IDs, acceptance-criteria IDs (e.g., `AC11`), and sub-spec section references (e.g., `§ 3.2`).
Learnt from: wmadden
Repo: prisma/prisma-next PR: 485
File: test/integration/test/cli.init-facade-imports.e2e.test.ts:14-14
Timestamp: 2026-05-12T03:36:07.175Z
Learning: In this repo, the doc-maintenance rule allows stable reference IDs in source-code comments—e.g., Linear ticket IDs matching `TML-*` (such as `TML-2485`, `TML-2397`) and ADR references like `ADR 211`. Do not flag `TML-*` ticket ID references in code comments as violations. Instead, violations are limited to transient artifacts such as `projects/<x>/...` paths, milestone-task IDs like `T1.7` / `T2.5.3`, milestone acceptance-criteria codes like `AM12` / `AC-13`, and prose attributions like `M2 review`, `out of scope`, or `sub-spec § 4`—flag those when found in comments.
| const database = await createDevDatabase(); | ||
| const client = new pg.Client({ connectionString: database.connectionString }); | ||
| await client.connect(); |
There was a problem hiding this comment.
Always run database.close() even when client setup/teardown fails.
database is allocated before client.connect(), but the try/finally starts after that call, and the finally also short-circuits if client.end() rejects. Either failure path skips database.close(), which can leak the dev DB and destabilize later integration tests.
Cleanup sketch
- const database = await createDevDatabase();
- const client = new pg.Client({ connectionString: database.connectionString });
- await client.connect();
+ const database = await createDevDatabase();
+ const client = new pg.Client({ connectionString: database.connectionString });
- let parseCompleteCount = 0;
- // biome-ignore lint/suspicious/noExplicitAny: pg.Connection internals are untyped
- const connection = (client as any).connection;
- connection.on('parseComplete', () => {
- parseCompleteCount++;
- });
-
try {
+ await client.connect();
+ let parseCompleteCount = 0;
+ // biome-ignore lint/suspicious/noExplicitAny: pg.Connection internals are untyped
+ const connection = (client as any).connection;
+ connection.on('parseComplete', () => {
+ parseCompleteCount++;
+ });
+
await client.query('create table items (id serial primary key, n int)');
const insertValues = Array.from({ length: 50 }, (_, i) => `(${i})`).join(', ');
await client.query(`insert into items (n) values ${insertValues}`);
@@
} finally {
- await client.end();
- await database.close();
+ try {
+ await client.end();
+ } finally {
+ await database.close();
+ }
}Also applies to: 73-75
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@packages/3-targets/7-drivers/postgres/test/named-cursor.wire.integration.test.ts`
around lines 26 - 28, The test allocates the dev DB via createDevDatabase()
before creating/connecting the pg.Client but doesn't guarantee database.close()
runs if client.connect() or client.end() throws; ensure database.close() is
always called by moving the try/finally to start immediately after
createDevDatabase() (or wrap createDevDatabase() in its own try/finally), and in
the finally always call await database.close() regardless of client state,
handling/rethrowing client.end() failures separately so a rejected client.end()
cannot short-circuit database.close(); update the code paths around
client.connect(), client.end(), and database.close() (referencing
createDevDatabase, client.connect, client.end, database.close) to enforce this
cleanup.
8f770b9 to
54b849a
Compare
Adds runtime.prepare() and db.prepare() author surfaces returning a
reusable PreparedStatement that captures lowered SQL once. The
executePrepared driver SPI receives { sql, params, handle }. Postgres
driver uses pg's name-keyed parsedStatements cache with pn_<n>
handles allocated lazily on first execute; streams via a custom
pg-cursor subclass that sends Parse+Bind for the named statement.
Stale-handle retry on SQLSTATE 26000 / 0A000 (deallocated name;
cached-plan invalid) mints a fresh handle and retries exactly once.
preparedStatements: false driver option falls back to one-shot
parameterized queries (PgBouncer transaction mode).
PreparedStatement.execute(target, params, options?) takes an explicit
RuntimeQueryable (Runtime / RuntimeConnection / RuntimeTransaction /
TransactionContext). The runtime hides the driver handle behind a
per-runtime WeakMap; the PreparedStatement public surface is pure data.
DecodeContext and ParamMetadata are cached at prepare time.
Tightens SqlExecutionPlan.ast to required; adds a stubAst() test helper
for fixtures that previously left ast undefined.
Signed-off-by: Serhii Tatarintsev <[email protected]>
54b849a to
634c6cd
Compare
## Version **0.9.0 → 0.10.0** Lockstep bump across all 82 workspace packages (`package.json` + `pnpm-lock.yaml` workspace specifiers only). Versioning policy: [docs/oss/versioning.md](https://github.com/prisma/prisma-next/blob/main/docs/oss/versioning.md) ## Release notes (since 0.9.0) No additional maintainer flags at pre-flight. Notable changes already on `main` that consumers should plan for when moving to **0.10.0**: - **Breaking — strict `storage.types` deserializer:** On-disk contract snapshots must tag every `storage.types` entry with `kind` (`codec-instance` / `postgres-enum`). Untagged codec triples no longer load. Use the shipped upgrade skills (`prisma-next-upgrade` and `prisma-next-extension-upgrade`, `0.9-to-0.10` entries + `stamp-storage-types-kind.ts` codemod). - **CLI:** Migration surface reorganized (`migrate` verb, `ref` promoted, removed verbs redirect with suggestions); `--version` sourced from `package.json`. - **SQL:** Prepared statements primitive (#444). ## Publish trigger **Merging this PR ships the release:** the push to `main` carries root `version` **0.10.0**, the [Publish to npm](https://github.com/prisma/prisma-next/blob/main/.github/workflows/publish.yml) workflow publishes under dist-tag `latest`, and a matching GitHub Release is created automatically. No separate dispatch step. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Released version 0.10.0 across the platform: core packages, extensions, adapters, drivers, targets, tooling, examples, and test fixtures updated for consistency. * Updated internal dependency alignments and package manifests to match the new release; no functional or script changes to examples or runtime behavior. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/prisma/prisma-next/pull/545?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> Signed-off-by: Will Madden <[email protected]>
closes TML-2381 and TML-2382
Intent
Add a first-class prepared-statement primitive to the SQL DSL that opts users into both kinds of execution reuse: lowering reuse (the AST → SQL pass runs once per
prepare) and server-side parse reuse (PostgresparsedStatementskeeps one named plan per Client). The samePreparedStatementis reusable across runtime, connection, and transaction scopes — produced once, redirected at execute time.Change map
RuntimeQueryablegainsexecutePrepared;preparelowers once and freezes; transaction and connection scopes route through their ownSqlQueryable.pg-cursorsubclass that overrides onlysubmitto send Parse with a name and Bind referencing the named statement.The story
The runtime gains
prepare(declaration, callback). The callback receives bind-siteparamsproxies and returns a plan via.build(). The runtime invokes thebeforeCompilemiddleware chain on the AST exactly once, lowers via the adapter, and freezes{sql, ast, meta, slots}onto aPreparedStatement. No driver I/O.Driver SPI gets
executePrepared({ sql, params, handle }). The driver never sees thePreparedStatementobject — only the lowered SQL, encoded params, and an opaque getter/setter slot. The runtime persists the slot's value in a per-runtimeWeakMap, so the handle is GC'd alongside the user'sPreparedStatementreference.Postgres reuses pg's per-Client
parsedStatementscache. A driver-scoped allocator mintspn_<n>names. First execute writes Parse with the name; subsequent executes on the same Client skip Parse. A different Client (a fresh pool acquisition) auto-Parses on first use.Streaming uses a
pg-cursorsubclass.NamedCursorextendsCursorand overrides onlysubmit— Parse withname, Bind referencing the named statement, then the inherited portal/PortalSuspended/Sync lifecycle handles batched streaming unchanged. The execute path through the driver shares onerunQuery(name?)helper with the ad-hocexecute()path.Stale-handle errors retry once with a fresh name. SQLSTATE
26000(deallocated name, e.g. afterDEALLOCATE ALL) and0A000("cached plan must not change result type" after DDL) are both healed by minting a newpn_<n>and retrying. The same retry layer wraps both the streaming and buffered paths so the behaviour is identical regardless ofcursor.disabled.PreparedStatement.execute(target, params)always names its scope. Thetargetis aRuntimeQueryable(Runtime, RuntimeConnection, RuntimeTransaction, or TransactionContext). Each scope implementsexecutePreparedand routes through theSqlQueryableit is backed by. The same prepared statement is reusable across scopes — prepare once, run against the runtime for one request and against an active transaction for another. There is no implicit binding back to the runtime that produced it.Behavior changes & evidence
Adds
runtime.prepare(declaration, callback)returning aPreparedStatement<Params, Row>. Lowers exactly once; no driver I/O. ThrowsRUNTIME.PREPARE_UNUSED_PARAMwhen a declared param is unreferenced by the callback's plan.Adds
SqlQueryable.executePrepared({ sql, params, handle })to the driver SPI. The runtime never hands thePreparedStatementto the driver. The handle slot is opaque to the runtime, populated lazily on first execute.relational-coreAdds Postgres-backed streaming for named prepared statements.
NamedCursorextendspg-cursorand overrides onlysubmitso Parse carries a name (and is skipped on subsequent submits whenconnection.parsedStatementsalready records it). Bind references the named statement; PortalSuspended/Close/Sync are inherited.Adds stale-handle retry on SQLSTATE 26000 and 0A000. A fresh
pn_<n>is minted and the execute is retried exactly once. Any other SQLSTATE is re-surfaced unchanged. If a row was already yielded (mid-stream error), the retry is suppressed to avoid duplicate rows.withStaleHandleRetry,isStalePreparedStatementError)DEALLOCATE ALLbetween executes (26000), column-type swap withSELECT *(0A000)Adds
preparedStatements: falsedriver opt-out. Skips server-side prepare entirely; routes through the same cursor/buffered path as ad-hoc execute. Lowering reuse on thePreparedStatementis the only win retained, intended for transaction-mode poolers.PreparedStatement.execute(target, params)requires an explicit target. EachRuntimeQueryablescope (Runtime, RuntimeConnection, RuntimeTransaction, TransactionContext) implementsexecutePreparedand routes through its ownSqlQueryable. The prepared statement is pure data — no runtime captured at construction.RuntimeQueryable,wrapTransaction,withTransaction'stxContext), prepared-statement.tswithTransaction(...)sees the tx's uncommitted writes; the same PS run against the runtime after commit sees the committed row.Compatibility / migration / risk
ps.execute(target, params)is new — the previous M2 surfaceps.execute(params)was never released, so there is no migration burden for external callers. Two example queries underexamples/and existing E2E tests were updated.@types/pg-cursorinternals dependency.NamedCursorreads/writes pg-cursor's runtime-only fields (_portal,_conf,_result,_ifNoData,_rowDescription). These have been stable since 2014 and are consumed by pg-cursor's own handlers, so the implicit contract is not new — but a future pg-cursor major could break it. The pg version is pinned via the workspace catalog.connection.parsedStatements. Not declared on@types/pg'sConnection(set byClient, notConnection). The cast is local and one field deep.Follow-ups / open questions
insert({...})andupdate({...})acceptTInput, notExpression. A prepared INSERT that takesparams.emailfrom the prepare callback doesn't typecheck today. Out of scope for this PR; tracked separately.Map<number, StatementSync>is not landed in this PR.Non-goals / intentionally out of scope
PreparedStatementreference plus the connection.dispose()/DEALLOCATE. Server-side state is bounded by(distinct PreparedStatements) × (connections that have executed each one)and self-heals on connection recycle.PREPAREat pool init. First execute per connection pays the Parse cost.Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Examples
Tests