Repository navigation
feat(sql-runtime): add callback-based transaction API - #346
Conversation
📝 WalkthroughWalkthroughAdds transactional APIs: RuntimeConnection.destroy, TransactionContext (with invalidation), a withTransaction helper implementing acquire/commit/rollback/destroy semantics, Postgres client transaction integration, and tests (unit, type, and E2E) covering lifecycle and error flows. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as Caller
participant Runtime as Runtime
participant DriverConn as Driver Connection
participant TxCtx as TransactionContext
participant Callback as Callback
Caller->>Runtime: withTransaction(runtime, fn)
activate Runtime
Runtime->>DriverConn: acquireConnection()
activate DriverConn
DriverConn-->>Runtime: connection
Runtime->>DriverConn: beginTransaction()
activate TxCtx
Runtime->>Callback: fn(txCtx)
activate Callback
Callback->>TxCtx: tx.execute(...) / iterate(...)
TxCtx-->>Callback: results / async iterable
Callback-->>Runtime: return or throw
deactivate Callback
alt success
Runtime->>DriverConn: commit()
DriverConn-->>Runtime: commit ok
else failure
Runtime->>DriverConn: rollback()
DriverConn-->>Runtime: rollback ok / rollback error
end
alt connection suspect or teardown failed
Runtime->>DriverConn: destroy(reason)
else normal
Runtime->>DriverConn: release()
end
deactivate TxCtx
deactivate DriverConn
deactivate Runtime
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@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/runtime-executor
@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: |
## PR Stack: Transaction API | PR | Description | Base | |---|---|---| | **#345** (this) | 📄 Spec, plan, and ADR | `main` | | #346 | ⚙️ Core transaction runtime + `db.transaction()` + `tx.sql` | `#345` | | #347 | 🔗 Wire `tx.orm` into transactions | `#346` | Part of https://linear.app/prisma-company/issue/TML-1912/orm-transaction-support --- ## Summary Adds the foundational design documents for the **ORM Client Transaction API** (`db.transaction(callback)`): - **Spec** — full feature specification for `db.transaction()` on `PostgresClient` - **Plan** — 4-milestone delivery plan with acceptance criteria traceability matrix - **ADR 187** — architecture decision on how transaction-scoped streams handle post-commit consumption ## Spec highlights The API follows a **callback-scoped** pattern — no dangling transactions, guaranteed cleanup: ```ts await db.transaction(async (tx) => { await tx.orm.account.where({ id: fromId }).update({ balance: fromBalance - amount }); const plan = tx.sql.from(tables.auditLog).insert({ action: 'transfer', amount }).build(); await tx.execute(plan); }); ``` The transaction context exposes three surfaces: - `tx.orm` — full ORM collection API bound to the transaction connection - `tx.sql` — typed SQL builder (`Db<TContract>`) bound to the same connection - `tx.execute(plan)` — execute a built plan directly Explicit **non-goals**: configurable isolation levels, savepoints/nesting, automatic retry, interactive begin/commit/rollback handle, timeout, MongoDB support. ## Plan | Milestone | Scope | Status | |---|---|---| | M1 — Transaction runtime plumbing | `withTransaction` helper, `db.transaction()`, `tx.sql`, unit + e2e tests | ✅ Done | | M2 — ORM integration | `tx.orm` wiring, `withMutationScope` fallback, nested-mutation e2e tests | ✅ Done | | M3 — Type safety & edge cases | Type-level tests, `PromiseLike` drain, post-commit invalidation, lazy connect | ☐ Pending | | M4 — Close-out | Acceptance criteria verification, doc finalization, project cleanup | ☐ Pending | ## ADR 187: Transaction-scoped streams use invalidation, not buffering **Decision**: When a transaction ends, the scoped `RuntimeQueryable` sets an `invalidated` flag. Any `AsyncIterableResult` consumed after that point throws a clear error rather than hitting a released connection. **Rejected alternatives**: eager buffering (silently changes semantics), type-level prevention (breaks inference), pre-commit tracking (rejects valid patterns), do nothing (confusing errors). The ADR includes a wire-protocol safety analysis confirming that unconsumed result streams cannot hide database errors or cause an incorrect COMMIT in Postgres. ## Files - `projects/orm-client-transaction-api/spec.md` (new) - `projects/orm-client-transaction-api/plan.md` (new) - `docs/architecture docs/adrs/ADR 187 - Transaction-scoped streams use invalidation not buffering.md` (new) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added guidance on transaction-scoped streaming behavior, including error handling for results accessed outside the transaction scope and best practices for consuming results within transactions. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
f4da1a0 to
f189362
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
test/e2e/framework/test/transaction.test.ts (2)
12-12: Use shared timeout helpers instead of hardcoded values.♻️ Proposed fix
+import { timeouts } from '@prisma-next/test-utils'; + // ... -describe('transaction E2E', { timeout: 30000 }, () => { +describe('transaction E2E', { timeout: timeouts.databaseOperation }, () => {Based on learnings: "use
prisma-next/test-utilstimeout helpers... Usetimeouts.databaseOperationfor database operation scenarios."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/transaction.test.ts` at line 12, Replace the hardcoded timeout 30000 in the describe call for "transaction E2E" with the shared helper timeouts.databaseOperation from prisma-next/test-utils: import the timeouts symbol (e.g., add "import { timeouts } from 'prisma-next/test-utils'") if not present, then update describe('transaction E2E', { timeout: 30000 }, ...) to use { timeout: timeouts.databaseOperation } so the test uses the shared timeout constant.
1-2: Preferpatheovernode:pathfor cross-platform consistency.♻️ Proposed fix
-import { dirname, resolve } from 'node:path'; +import { dirname, resolve } from 'pathe';Based on learnings: "In the prisma/prisma-next repo, prefer using
patheover Node's built-innode:path."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/transaction.test.ts` around lines 1 - 2, Replace usage of Node built-ins with pathe: remove imports of dirname and resolve from 'node:path' and fileURLToPath from 'node:url' and instead import dirname, resolve, and fromFileUrl from 'pathe' (used where fileURLToPath was used). Update any call sites that used fileURLToPath(fileURL) to fromFileUrl(fileURL) so the test uses pathe's cross-platform path helpers (refer to imports at the top of the file).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-extensions/postgres/src/runtime/postgres.ts`:
- Around line 251-260: The spread of txCtx in transaction(...) copies the
current value of the invalidated getter (losing the live getter), so replace the
spread with an object that preserves txCtx as prototype (e.g.,
Object.create(txCtx)) then assign/override the sql property; i.e., construct tx
via Object.create(txCtx) and set tx.sql = txSql so PostgresTransactionContext
keeps the original invalidated getter and other live accessors while still using
the new sql instance for this transaction.
---
Nitpick comments:
In `@test/e2e/framework/test/transaction.test.ts`:
- Line 12: Replace the hardcoded timeout 30000 in the describe call for
"transaction E2E" with the shared helper timeouts.databaseOperation from
prisma-next/test-utils: import the timeouts symbol (e.g., add "import { timeouts
} from 'prisma-next/test-utils'") if not present, then update
describe('transaction E2E', { timeout: 30000 }, ...) to use { timeout:
timeouts.databaseOperation } so the test uses the shared timeout constant.
- Around line 1-2: Replace usage of Node built-ins with pathe: remove imports of
dirname and resolve from 'node:path' and fileURLToPath from 'node:url' and
instead import dirname, resolve, and fromFileUrl from 'pathe' (used where
fileURLToPath was used). Update any call sites that used fileURLToPath(fileURL)
to fromFileUrl(fileURL) so the test uses pathe's cross-platform path helpers
(refer to imports at the top of the file).
🪄 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: 1e64dbcf-5089-47f8-8eec-629aa5e807f3
⛔ Files ignored due to path filters (2)
projects/orm-client-transaction-api/plan.mdis excluded by!projects/**projects/orm-client-transaction-api/spec.mdis excluded by!projects/**
📒 Files selected for processing (7)
packages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-extensions/postgres/src/runtime/postgres.tspackages/3-extensions/postgres/test/postgres.test.tspackages/3-extensions/postgres/test/transaction.types.test-d.tstest/e2e/framework/test/transaction.test.ts
f189362 to
de5e736
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts (1)
120-132:⚠️ Potential issue | 🟠 MajorKeep
SqliteDriver.close()retryable after delegateddestroy()failures.With
release()now delegating todestroy(),SqliteDriver.close()in this same file becomes incorrect: it marks the driver closed before awaitingconn.release(). IfDatabaseSync.close()throws, the handle stays open, but every laterdriver.close()call is a no-op because the state is already'closed'. That strands the connection and makes the new retryable-cleanup contract unreachable through the driver.Proposed fix
async close(): Promise<void> { if (this.#state.kind !== 'connected') return; const { conn } = this.#state; - this.#state = { kind: 'closed' }; await conn.release(); + if (this.#state.kind === 'connected' && this.#state.conn === conn) { + this.#state = { kind: 'closed' }; + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts` around lines 120 - 132, SqliteDriver.close() currently marks the driver closed before awaiting conn.release(), which prevents retries if destroy()/DatabaseSync.close() throws; change close() so it first awaits conn.release() (which delegates to destroy()/#db.close()), and only set the driver's state to 'closed' after release completes successfully; if conn.release() throws, rethrow the error and leave the state as not-closed so subsequent close() calls remain retryable. Update logic referencing SqliteDriver.close(), release(), destroy(), and DatabaseSync.close() accordingly so destroy() still throws normalized errors but does not flip driver state.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-targets/7-drivers/postgres/src/postgres-driver.ts`:
- Around line 348-359: The teardown passed to PostgresConnectionImpl currently
calls releaseLease() before awaiting this.close(), which allows
acquireConnection() to race in and reuse the same direct client while the socket
is still being closed; change the teardown so it awaits driver shutdown (call
and await this.close(), which must wait for direct client .end() and set
`#closed`) before calling releaseLease(), ensuring the lease remains held until
the socket is fully closed and preventing acquireConnection() from observing an
intermediate reusable state; reference PostgresConnectionImpl, releaseLease,
this.close, `#connectionMutex` and acquireConnection when making this change.
---
Outside diff comments:
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts`:
- Around line 120-132: SqliteDriver.close() currently marks the driver closed
before awaiting conn.release(), which prevents retries if
destroy()/DatabaseSync.close() throws; change close() so it first awaits
conn.release() (which delegates to destroy()/#db.close()), and only set the
driver's state to 'closed' after release completes successfully; if
conn.release() throws, rethrow the error and leave the state as not-closed so
subsequent close() calls remain retryable. Update logic referencing
SqliteDriver.close(), release(), destroy(), and DatabaseSync.close() accordingly
so destroy() still throws normalized errors but does not flip driver state.
🪄 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: 4b497fee-c17b-40eb-8431-2546c45c5d39
📒 Files selected for processing (12)
packages/1-framework/4-runtime/runtime-executor/src/runtime-core.tspackages/2-sql/4-lanes/relational-core/src/ast/driver-types.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.types.test-d.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-targets/7-drivers/postgres/src/exports/runtime.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.unbound.test.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tspackages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/2-sql/5-runtime/src/sql-runtime.ts
- Make rollback errors close connections instead of returning them back to the pool. - Attempt rollback on commit failure (similar to what Prisma does).
ca6cb9e to
bbe5b7f
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (3)
packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts (1)
68-68: KeepSqliteConnectionImplprivate; expose a factory instead.Exporting the concrete class widens the module API surface. Prefer a factory returning
SqlConnectionand keep the class internal.As per coding guidelines: "Export interfaces and factory functions for public APIs; keep concrete classes as private implementation details."♻️ Suggested refactor
-export class SqliteConnectionImpl implements SqlConnection { +class SqliteConnectionImpl implements SqlConnection { readonly `#db`: DatabaseSync; ... } + +export function createSqliteConnection(db: DatabaseSync): SqlConnection { + return new SqliteConnectionImpl(db); +}- import { ..., SqliteConnectionImpl } from '../src/sqlite-driver'; + import { ..., createSqliteConnection } from '../src/sqlite-driver'; - const connection = new SqliteConnectionImpl(db); + const connection = createSqliteConnection(db);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts` at line 68, Remove the exported concrete class by making SqliteConnectionImpl non-exported (drop the export) and add an exported factory function (e.g., createSqliteConnection or sqliteConnectionFactory) that returns the SqlConnection interface; update any call sites to use the new factory and keep all implementation details inside the now-internal SqliteConnectionImpl class so the module only exposes SqlConnection and the factory function.test/e2e/framework/test/transaction.test.ts (2)
12-12: Use shared timeout helpers instead of hardcoded values.The hardcoded
30000timeout should use the shared timeout helper for database operations.♻️ Suggested fix
+import { timeouts } from '@prisma-next/test-utils'; ... -describe('transaction E2E', { timeout: 30000 }, () => { +describe('transaction E2E', { timeout: timeouts.databaseOperation }, () => {Based on learnings: "use
prisma-next/test-utilstimeout helpers—specificallytimeouts.databaseOperationfor database operation scenarios."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/transaction.test.ts` at line 12, Replace the hardcoded 30000 timeout on the describe('transaction E2E', ...) call with the shared helper timeouts.databaseOperation from the prisma-next/test-utils package: import the timeouts symbol (e.g. add an import for timeouts from 'prisma-next/test-utils') and change the describe options to use timeout: timeouts.databaseOperation so the test uses the shared database operation timeout constant.
1-2: Preferpatheovernode:pathfor cross-platform consistency.Based on learnings, the repo prefers
patheover Node's built-innode:pathmodule for path operations.♻️ Suggested fix
-import { dirname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { dirname, resolve } from 'pathe'; +import { fileURLToPath } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/transaction.test.ts` around lines 1 - 2, Replace the node:path import with pathe to ensure cross-platform path handling: change "import { dirname, resolve } from 'node:path';" to import those same symbols from 'pathe' (keep using fileURLToPath from 'node:url' as before), and update any usages of dirname or resolve in this file (e.g., in transaction.test.ts where dirname, resolve and fileURLToPath are used) to rely on the pathe implementations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts`:
- Line 68: Remove the exported concrete class by making SqliteConnectionImpl
non-exported (drop the export) and add an exported factory function (e.g.,
createSqliteConnection or sqliteConnectionFactory) that returns the
SqlConnection interface; update any call sites to use the new factory and keep
all implementation details inside the now-internal SqliteConnectionImpl class so
the module only exposes SqlConnection and the factory function.
In `@test/e2e/framework/test/transaction.test.ts`:
- Line 12: Replace the hardcoded 30000 timeout on the describe('transaction
E2E', ...) call with the shared helper timeouts.databaseOperation from the
prisma-next/test-utils package: import the timeouts symbol (e.g. add an import
for timeouts from 'prisma-next/test-utils') and change the describe options to
use timeout: timeouts.databaseOperation so the test uses the shared database
operation timeout constant.
- Around line 1-2: Replace the node:path import with pathe to ensure
cross-platform path handling: change "import { dirname, resolve } from
'node:path';" to import those same symbols from 'pathe' (keep using
fileURLToPath from 'node:url' as before), and update any usages of dirname or
resolve in this file (e.g., in transaction.test.ts where dirname, resolve and
fileURLToPath are used) to rely on the pathe implementations.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: a0571693-0276-453c-bd8d-a47fb3d194c9
⛔ Files ignored due to path filters (2)
projects/orm-client-transaction-api/plan.mdis excluded by!projects/**projects/orm-client-transaction-api/spec.mdis excluded by!projects/**
📒 Files selected for processing (17)
packages/1-framework/4-runtime/runtime-executor/src/runtime-core.tspackages/2-sql/4-lanes/relational-core/src/ast/driver-types.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.tspackages/2-sql/4-lanes/relational-core/test/ast/driver-types.types.test-d.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-extensions/postgres/src/runtime/postgres.tspackages/3-extensions/postgres/test/postgres.test.tspackages/3-extensions/postgres/test/transaction.types.test-d.tspackages/3-targets/7-drivers/postgres/src/exports/runtime.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.unbound.test.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tspackages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.tstest/e2e/framework/test/transaction.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/2-sql/4-lanes/relational-core/test/ast/driver-types.test.ts
- packages/3-targets/7-drivers/postgres/src/exports/runtime.ts
- packages/2-sql/5-runtime/src/exports/index.ts
- packages/3-targets/7-drivers/postgres/test/driver.errors.test.ts
## PR Stack: Transaction API | PR | Description | Base | |---|---|---| | #345 | 📄 Spec, plan, and ADR | `main` | | #346 | ⚙️ Core transaction runtime + `db.transaction()` + `tx.sql` | `#345` | | **#347** (this) | 🔗 Wire `tx.orm` into transactions | `#346` | Closes https://linear.app/prisma-company/issue/TML-1912/orm-transaction-support --- ## Summary Implements **Milestone 2** of the transaction API: wiring `tx.orm` so that ORM collections used inside a `db.transaction()` callback execute against the transaction connection. Also adds relations to the e2e fixture contract to enable nested-mutation integration tests. ## Implementation The production change is **surgical** — ~12 lines in a single file. ### `PostgresTransactionContext` gains `orm` ```ts export interface PostgresTransactionContext<TContract extends Contract<SqlStorage>> extends TransactionContext { readonly sql: Db<TContract>; readonly orm: OrmClient<TContract>; // ← new } ``` ### Transaction-scoped ORM client construction Inside `transaction()`, a new `ormBuilder()` creates an ORM client bound to the transaction's `execute`: ```ts const txOrm: OrmClient<TContract> = ormBuilder({ runtime: { execute(plan) { return txCtx.execute(plan); }, }, context, }); ``` **Key design decision**: The `runtime` object passed to `ormBuilder` exposes **only** `execute()` — it deliberately omits `connection()` and `transaction()`. This ensures `withMutationScope` in the mutation executor naturally falls through to direct scope reuse instead of attempting a nested transaction. **Zero changes to the mutation executor were needed.** ## Tests ### Unit tests (4 new) | Test | Location | Covers | |---|---|---| | `transaction()` provides `orm` on the tx context | `postgres.test.ts` | `tx.orm` is the transaction-scoped proxy | | `tx.orm` has the same type as `db.orm` | `transaction.types.test-d.ts` | Compile-time type equivalence | | `executeNestedCreateMutation()` reuses scope when runtime lacks `transaction` | `mutation-executor.test.ts` | Fast-path: direct `execute` on the transaction runtime | | `withMutationScope` reuses runtime when no `transaction` or `connection` exists | `mutation-executor.test.ts` | Scope reuse without nested transaction | ### E2E integration tests (5 new — real PGlite database) | Test | Covers | |---|---| | ORM create with nested relation mutation commits atomically | `tx.orm.Post.create()` with nested `author: (r) => r.create(...)` — both rows exist | | ORM create with nested relation mutation rolls back on throw | Same nested create + throw — neither row exists | | ORM write then read within the same transaction | Read-your-own-writes: `create()` then `where().first()` sees the row | | Multiple ORM operations in a transaction are atomic | Two posts + user all commit together | | Multiple ORM operations roll back together on throw | Same operations + throw — nothing persists | ## E2E fixture contract changes The fixture contract gained **relations** across all three models to enable nested-mutation tests: | Model | Relation | Type | Join | |---|---|---|---| | `User` | `posts` | `1:N` → `Post` | `User.id` → `Post.userId` | | `Post` | `author` | `N:1` → `User` | `Post.userId` → `User.id` | | `Post` | `comments` | `1:N` → `Comment` | `Post.id` → `Comment.postId` | | `Comment` | `post` | `N:1` → `Post` | `Comment.postId` → `Post.id` | The contract definition was refactored to compose models with `rel.belongsTo()` / `rel.hasMany()` before passing to `defineContract`, using lazy refs (`() => Comment`) for circular relations. ## Design patterns - **Capability elision for scope reuse** — the transaction-scoped runtime is a minimal `{ execute }` object; omitting `transaction()` / `connection()` makes `withMutationScope` fall through naturally - **Interface segregation** — `RuntimeQueryable` passed to `ormBuilder` is a narrowed shape, preventing accidental nested-transaction creation - **Warm-up pattern for PGlite** — e2e helper calls `db.orm.User.first()` before entering transactions to force contract verification (which needs its own connection) outside the transaction, avoiding deadlock on single-connection PGlite ## Files changed - `packages/3-extensions/postgres/src/runtime/postgres.ts` — add `tx.orm` construction - `packages/3-extensions/postgres/test/postgres.test.ts` — 1 unit test - `packages/3-extensions/postgres/test/transaction.types.test-d.ts` — 1 type test - `packages/3-extensions/sql-orm-client/test/mutation-executor.test.ts` — 2 unit tests - `test/e2e/framework/test/transaction-orm.test.ts` — 5 e2e tests (new) - `test/e2e/framework/test/fixtures/contract.ts` — add relations to fixture - `test/e2e/framework/test/fixtures/generated/contract.{d.ts,json}` — regenerated - `test/e2e/framework/package.json` + `pnpm-lock.yaml` — add `@prisma-next/postgres` dev dep - `projects/orm-client-transaction-api/{plan,spec}.md` — mark M2 tasks done <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * ORM client is now available inside transaction contexts, allowing ORM calls to participate in the same transactions as SQL. * **Tests** * Added e2e transaction integration tests covering atomic commits, rollbacks, nested relation mutations, and read-your-own-writes semantics. * Added type-safety checks and unit tests for mutation execution scope and transaction-scoped ORM behavior. * **Chores** * Test framework dependency updated to include the Postgres extension; test fixtures reorganized for relation modeling. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
PR Stack: Transaction API
maindb.transaction()+tx.sql#345tx.orminto transactions#346Refs: https://linear.app/prisma-company/issue/TML-1912/orm-transaction-support
Closes: https://linear.app/prisma-company/issue/TML-2161/orm-sql-dsl-transaction-interop
Summary
Implements Milestone 1 of the transaction API: the core
withTransactionhelper insql-runtime(target-agnostic) and thedb.transaction()surface onPostgresClientwithtx.sqlsupport.Implementation
withTransaction(runtime, fn)—@prisma-next/sql-runtimeA target-agnostic helper that manages the full transaction lifecycle:
TransactionContextinvalidated = true→ commits → releases connectioninvalidated = true→ rolls back → releases connection → re-throwsSafety features:
tx.execute()after the transaction ends throwsRUNTIME.TRANSACTION_CLOSEDAsyncGeneratorwraps every result; consuming rows post-commit throws the same error per-yieldRUNTIME.TRANSACTION_ROLLBACK_FAILEDwith the original error as.causePostgresClient.transaction()+PostgresTransactionContextdb.transaction(fn)delegates towithTransaction, attaching a freshDb<TContract>SQL builder astx.sql. Lazy-initializes the runtime on first call (same asconnect()/runtime()).New public exports from
@prisma-next/sql-runtimeTransactionContext(type)RuntimeConnection,RuntimeTransaction,RuntimeQueryable(types — previously internal)withTransaction(function)Tests
Unit tests —
withTransaction(12 tests)Unit tests — Postgres (3 tests)
transaction()delegates towithTransactionwith the lazy runtimetransaction()providessqlon the transaction contexttransaction()lazily creates runtime beforeconnect()Type-level tests (3 tests)
transactionmethod (no nesting)db.transaction()infers callback return type correctlytx.sqlhas the same type asdb.sqlE2E tests against real Postgres (5 tests)
PromiseLikeauto-drain)AsyncIterableResultconsumed after commitKey design decisions
execute()semantics everywhere (ADR 187)RUNTIME.TRANSACTION_CLOSED,RUNTIME.TRANSACTION_ROLLBACK_FAILEDsql-runtime, adapter addstx.sqlsurfacePostgresTransactionContextomitstransaction, enforced at compile timePromiseLike<R>callback return — auto-drainsAsyncIterableResultwhen returned directlyFiles changed
packages/2-sql/5-runtime/src/sql-runtime.ts—withTransaction,TransactionContextpackages/2-sql/5-runtime/src/exports/index.ts— new exportspackages/2-sql/5-runtime/test/sql-runtime.test.ts— 12 unit testspackages/3-extensions/postgres/src/runtime/postgres.ts—db.transaction(),PostgresTransactionContextpackages/3-extensions/postgres/test/postgres.test.ts— 3 unit testspackages/3-extensions/postgres/test/transaction.types.test-d.ts— 3 type tests (new)test/e2e/framework/test/transaction.test.ts— 5 e2e tests (new)projects/orm-client-transaction-api/{plan,spec}.md— mark M1 tasks doneSummary by CodeRabbit
New Features
Tests