Repository navigation
Conversation
TML-1834 Runtime DX: ExecutionStack + ExecutionContext foundation
SummaryEstablish the core runtime composition primitives used throughout Runtime DX:
This ticket exists to track the foundation work and ensure downstream Runtime DX changes build on a stable, documented surface. Scope
Acceptance criteria
Follow-ups (if needed)
|
WalkthroughAdds a descriptor-only ExecutionStack and instantiation flow, renames RuntimeContext → ExecutionContext, introduces createExecutionContext and stackInstance-driven runtime creation (createRuntime accepts CreateRuntimeOptions with stackInstance), and propagates stack/ExecutionContext wiring across core packages, examples, tests, docs, and packaging. Changes
Sequence Diagram(s)sequenceDiagram
participant Dev as Developer
participant StackAPI as ExecutionStack\ncreateExecutionStack
participant Instantiator as ExecutionStackInstance\ninstantiateExecutionStack
participant ContextFactory as ExecutionContext\ncreateExecutionContext
participant RuntimeFactory as Runtime\ncreateRuntime
participant DB as Database
Dev->>StackAPI: createExecutionStack({ target, adapter, driver?, extensionPacks? })
StackAPI-->>Dev: ExecutionStack (descriptors)
Dev->>Instantiator: instantiateExecutionStack(ExecutionStack)
Instantiator-->>Dev: ExecutionStackInstance (target/adapter/extension instances)
Dev->>ContextFactory: createExecutionContext({ contract, stackInstance })
ContextFactory-->>Dev: ExecutionContext (codecs, operations, types)
Dev->>RuntimeFactory: createRuntime({ stackInstance, contract, context, driverOptions?, verify?, plugins? })
RuntimeFactory-->>Dev: Runtime
Dev->>RuntimeFactory: runtime.execute(plan)
RuntimeFactory->>DB: execute SQL via driver
DB-->>RuntimeFactory: results
RuntimeFactory-->>Dev: results
Comment |
This stack of pull requests is managed by Graphite. Learn more about stacking. |
a6d4742 to
7d971b6
Compare
edd6733 to
65360c8
Compare
65360c8 to
6849d80
Compare
There was a problem hiding this comment.
Actionable comments posted: 20
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
examples/prisma-next-demo/src/queries/dml-operations.ts (1)
5-25: Return the first row without buffering. Only the first row is used, so you can stream and return immediately to avoid extra allocations. Consider applying the same pattern toupdateUseranddeleteUser.♻️ Proposed refactor
- const rows: Array<{ id: number; email: string }> = []; - for await (const row of runtime.execute(plan)) { - rows.push(row as { id: number; email: string }); - } - - return rows[0]; + for await (const row of runtime.execute(plan)) { + return row as { id: number; email: string }; + } + + return undefined;examples/prisma-next-demo/src/main-no-emit.ts (1)
52-93: Handle config/runtime errors inside the try block.Line 53–54 can throw before the
try, which bypasses the error handler and leavesruntimeundefined forfinally. Wrap these in thetryand guard the close.Suggested fix
async function main() { - const { databaseUrl } = loadAppConfig(); - const runtime = getRuntime(databaseUrl); + let runtime: ReturnType<typeof getRuntime> | undefined; try { + const { databaseUrl } = loadAppConfig(); + runtime = getRuntime(databaseUrl); if (cmd === 'users') { const limit = args[0] ? Number.parseInt(args[0], 10) : 10; const users = await getUsers(runtime, limit); console.log(JSON.stringify(users, null, 2)); @@ } catch (error) { console.error('Error:', error); process.exit(1); } finally { - await runtime.close(); + if (runtime) await runtime.close(); } }packages/2-sql/5-runtime/test/async-iterable-result.test.ts (1)
225-229: Consider using object matcher for cleaner assertions.Per coding guidelines, prefer object matchers over multiple individual
expect().toBe()calls when checking related values.♻️ Suggested refactor
- expect(rows.length).toBe(1); - if (rows[0]) { - expect(typeof rows[0].id).toBe('number'); - expect(typeof rows[0].email).toBe('string'); - } + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + id: expect.any(Number), + email: expect.any(String), + });packages/2-sql/3-tooling/family/src/core/runtime-instance.ts (1)
11-15: ConsolidateSqlRuntimeDriverInstancetype definition.
SqlRuntimeDriverInstanceis defined identically in both this file (lines 11-15) andpackages/2-sql/5-runtime/src/sql-context.ts(lines 120-124). The canonical source is@prisma-next/sql-runtime. Replace the duplicate definition with a re-export to match the pattern already used forSqlRuntimeAdapterInstanceon line 18:Suggested change
-export type SqlRuntimeDriverInstance<TTargetId extends string = string> = RuntimeDriverInstance< - 'sql', - TTargetId -> & - SqlDriver; // Re-export SqlRuntimeAdapterInstance from sql-runtime for consumers export type { SqlRuntimeAdapterInstance } from '@prisma-next/sql-runtime'; +export type { SqlRuntimeDriverInstance } from '@prisma-next/sql-runtime';Also remove the now-unused
SqlDriverimport from line 5.
🤖 Fix all issues with AI agents
In `@examples/prisma-next-demo/scripts/seed.ts`:
- Around line 157-165: Wrap the body of main() in a try/finally so
runtime.close() is always awaited (call runtime.close() in the finally block)
and remove direct process.exit(1) from the top-level catch; instead set
process.exitCode = 1 in the catch block so cleanup runs (update references in
main, runtime.close, and the top-level .catch handler accordingly).
In `@examples/prisma-next-demo/src/entry.ts`:
- Line 154: The code is using a blind cast "contractJson as unknown as
ContractIR" in the assignment to app.innerHTML = renderContract(contractJson as
unknown as ContractIR); instead add a small runtime check before calling
renderContract: implement/locate a type-guard (e.g., isContractIR) or a
lightweight validator for the ContractIR shape and call renderContract only if
isContractIR(contractJson); if validation fails, log or render an error instead.
Update both occurrences (the line setting app.innerHTML and the other occurrence
at 161) to use the guard and avoid the double-cast. Ensure the symbol names
mentioned (contractJson, renderContract, ContractIR, isContractIR) are used so
reviewers can find and apply the change.
- Line 159: Remove the debug console.log statement by deleting the
console.log(newContract) line in entry.ts; if you need to persist or inspect
newContract instead, replace it with an appropriate logger call (e.g.,
processLogger.info or similar) or return/store newContract from the surrounding
function, but do not leave the raw console.log in the code.
In `@examples/prisma-next-demo/test/runtime.offline.integration.test.ts`:
- Around line 45-62: The test saves and restores process.env['DATABASE_URL']
using a truthy check that fails for an empty string; change the restore
conditional to check for undefined instead (e.g., use original !== undefined) so
the exact prior value (including '') is preserved when resetting process.env;
update the finally block that references original and process.env to use this
undefined check, keeping the surrounding logic in the 'imports query roots
without env config' test that calls loadModules and inspects executionContext,
sql, and tables unchanged.
- Around line 18-43: The test must always call runtime.close() even on failures;
wrap the test body that creates runtime (createRuntime / runtime.execute) in a
try/finally so runtime.close() is invoked in finally. Specifically, after
creating runtime in the 'builds plans without driver options' test, move the
assertions and the for-await block into the try block and call await
runtime.close() inside the finally block to guarantee cleanup if assertions
reject.
In `@examples/prisma-orm-demo/package.json`:
- Line 37: The package "@prisma-next/core-execution-plane" is used at runtime
(imported in src/prisma-next/runtime.ts) but is declared as a devDependency;
move it from devDependencies to dependencies in package.json so it is installed
in production. Update package.json by removing the
"@prisma-next/core-execution-plane": "workspace:*" entry under devDependencies
and adding the same entry under dependencies, ensuring the runtime import in
runtime.ts continues to resolve.
In `@examples/prisma-orm-demo/src/prisma-next/runtime.ts`:
- Line 30: The call to validateContract lacks a concrete generic type; import
the Contract type from contract.d.ts and call
validateContract<Contract>(contractJson) instead of
validateContract(contractJson) so TypeScript can infer the correct contract
shape. Update the imports to include Contract and replace the validateContract
invocation (the symbol validateContract and the variable contractJson) with the
generic form validateContract<Contract>(contractJson).
In `@packages/1-framework/1-core/runtime/execution-plane/test/stack.test.ts`:
- Around line 47-57: Replace the multiple related assertions in the test that
call expect(stack.target).toBe(target), expect(stack.adapter).toBe(adapter),
expect(stack.driver).toBeUndefined(), and
expect(stack.extensionPacks).toEqual([]) with a single object matcher using
toMatchObject on the stack returned by createExecutionStack; assert that stack
matches { target, adapter, driver: undefined, extensionPacks: [] } so the
grouped properties are validated in one assertion while keeping the test
behavior unchanged.
- Around line 127-137: Group the related instance property assertions by
replacing the multiple expect(...) checks with a single object match: after
calling instantiateExecutionStack(stack) assert that the resulting instance
matches an object shape containing stack, target, adapter, and extensionPacks
using toMatchObject; keep the individual call-count assertions for targetCreate,
adapterCreate, and extensionCreate, and reference instantiateExecutionStack,
instance, stack, targetInstance, adapterInstance, and extensionInstance when
forming the expected object for toMatchObject (e.g., { stack, target:
targetInstance, adapter: adapterInstance, extensionPacks: [extensionInstance]
}).
In `@packages/2-sql/3-tooling/family/README.md`:
- Around line 120-124: Clarify the phrase "identity-only" for the ./runtime
entrypoint by explicitly listing what it exports (e.g., type definitions, family
ID constants, descriptor/identity objects) and note that it does NOT export
runtime creation helpers; reference the runtime factory functions shown
(`createExecutionStack`, `instantiateExecutionStack`, `createExecutionContext`,
`createRuntime`) as the correct APIs in `@prisma-next/sql-runtime`, and add a
link to ADR 152 for the stack/context/runtime factory pattern to provide
architectural context.
- Around line 120-124: Add the missing dependency entry for
`@prisma-next/sql-runtime` to the README Dependencies section so the documented
factory functions (createExecutionStack, instantiateExecutionStack,
createExecutionContext, createRuntime) are reflected in the dependency list;
update the Dependencies block to include `@prisma-next/sql-runtime` with a brief
note or version specifier consistent with other entries so readers can find the
package that exports those factory functions.
In `@packages/2-sql/3-tooling/family/test/runtime-descriptor.test.ts`:
- Around line 21-45: The test currently uses single-step casts for mocked
descriptor/instance objects; replace each occurrence of "as
RuntimeTargetDescriptor<'sql','postgres'>", "as
RuntimeAdapterDescriptor<'sql','postgres',SqlRuntimeAdapterInstance<'postgres'>>",
"as
RuntimeDriverDescriptor<'sql','postgres',SqlRuntimeDriverInstance<'postgres'>>"
and the inline "as SqlRuntimeAdapterInstance<'postgres'>" / "as
SqlRuntimeDriverInstance<'postgres'>" with double casts via "as unknown as
<Type>" so the mocked returns in the create() functions are explicitly marked as
unsafe test mocks (e.g., change the casts on the target, adapter, driver
descriptors and the adapter/driver create() return values to use as unknown as
...).
In `@packages/2-sql/4-lanes/sql-lane/README.md`:
- Around line 72-79: Update the two markdown links that contain raw ampersands
to use URL-encoded %26: replace "4.%20Runtime%20&%20Plugin%20Framework.md" with
"4.%20Runtime%20%26%20Plugin%20Framework.md" in the Query Lanes / Runtime link
and replace
"ADR%20140%20-%20Package%20Layering%20&%20Target-Family%20Namespacing.md" with
"ADR%20140%20-%20Package%20Layering%20%26%20Target-Family%20Namespacing.md" in
the Related ADRs entry so both links match the %26 encoding convention.
In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 182-186: The current loop over result.missingExtensionPackIds
throws on the first packId, hiding other missing packs; update the logic in
sql-context.ts where result.missingExtensionPackIds is iterated (the for (const
packId of result.missingExtensionPackIds) block) to collect all missing pack IDs
into an array (or join them) and after the loop throw a single Error that lists
every missing extension pack (include packId values in the error message) so
users see a consolidated message rather than one at a time.
In `@packages/2-sql/5-runtime/src/sql-runtime.ts`:
- Around line 209-211: In the async generator method async *execute() the
initial yield* [] is redundant and should be removed because it yields nothing
before immediately throwing missingDriver(); update the execute function to drop
the yield* [] expression and simply throw missingDriver() from within the async
*execute() body so the generator behavior is correct and not confusing.
- Around line 261-276: The code redundantly calls createOfflineDriver() twice;
change the initialization and branching so createOfflineDriver() is only called
when needed: remove the initial assignment let driver: SqlDriver =
createOfflineDriver(); and instead declare let driver: SqlDriver; then keep the
existing if (stack.stack.driver) { if (driverOptions === undefined) { driver =
createOfflineDriver(); } else { const driverInstance =
stack.stack.driver.create(driverOptions); if (!isSqlDriver(driverInstance)) {
throw runtimeError('RUNTIME.INVALID_DRIVER_INSTANCE', 'Execution stack driver
does not implement SqlDriver interface.'); } driver = driverInstance; } } else {
driver = createOfflineDriver(); } so createOfflineDriver() runs only when there
is no stack.stack.driver or when driverOptions is undefined for that driver.
In `@packages/2-sql/5-runtime/test/async-iterable-result.test.ts`:
- Around line 78-129: Tests duplicate stack and runtime setup; extract a helper
factory to build the driver/adapter stack and runtime to eliminate repetition.
Create a function (e.g., createTestStackOrRuntime) that accepts the adapter and
driver (or uses defaults) and returns the created stack, stackInstance, context,
and runtime by encapsulating the existing calls to createExecutionStack,
instantiateExecutionStack, createExecutionContext, and createRuntime (and the
driverDescriptor construction), then replace the duplicated blocks in both tests
with calls to that helper.
In `@packages/2-sql/5-runtime/test/execution-stack.test.ts`:
- Around line 110-124: The mock driver is directly cast to
SqlRuntimeDriverInstance<'postgres'> which violates the testing guideline; in
the create() return use a double-cast via unknown to avoid unsafe direct casting
— replace the final cast on the merged object (the one referencing driver and
create()) with "as unknown as SqlRuntimeDriverInstance<'postgres'>", keeping the
same object shape (familyId, targetId, driver) and preserving the create()
function signature.
In `@packages/2-sql/5-runtime/test/sql-runtime.test.ts`:
- Around line 227-276: The target/adaptor descriptor objects are duplicated
across multiple tests; extract them into helper factories (e.g.,
createTestTargetDescriptor() and createTestAdapterDescriptor(adapter)) and use
those helpers in tests instead of inlining the same objects; implement
createTestTargetDescriptor to return the
RuntimeTargetDescriptor<'sql','postgres'> object and createTestAdapterDescriptor
to accept the result of createStubAdapter and return the
RuntimeAdapterDescriptor<'sql','postgres',SqlRuntimeAdapterInstance<'postgres'>>
(matching the current create() behavior), then replace the inline
targetDescriptor/adapterDescriptor occurrences in the tests with calls to these
helpers.
- Around line 443-493: The test currently only asserts that runtime is defined
but should call into the runtime to trigger the offline-driver failure; update
the test to invoke runtime.execute (e.g., await expect(runtime.execute({
operation: 'query', sql: 'SELECT 1' } as
any)).rejects.toThrowError(RUNTIME.DRIVER_MISSING) or otherwise assert the
thrown error matches RUNTIME.DRIVER_MISSING) so that the offline driver path in
createRuntime/instantiateExecutionStack is exercised and the expected
RUNTIME.DRIVER_MISSING error is asserted. Ensure you import or reference the
RUNTIME constant used by the runtime's error (and use await expect(...).rejects
for async execution).
♻️ Duplicate comments (5)
examples/prisma-next-demo/test/utils/control-client.ts (1)
101-111: Consider importing the execution context from the app module.This test utility recreates the execution stack and context locally, but the app likely already has an
execution-contextmodule that exports a reusable context. Importing from the app would reduce duplication and ensure test utilities stay aligned with the app's configuration.packages/2-sql/5-runtime/vitest.config.ts (1)
30-30: Lowering coverage thresholds should be temporary.The reduction from 85% to 83% is acknowledged with a TODO to restore after adding tests. Ensure this is tracked and addressed promptly to avoid coverage regression becoming permanent.
packages/2-sql/5-runtime/README.md (2)
13-13: Remove "env-free" terminology.Per previous review feedback, this wording is unclear. Consider rephrasing to describe the actual characteristic, e.g., "stateless" or "configuration-independent" if that's the intent.
Suggested fix
-The SQL runtime package implements the SQL family runtime by composing `@prisma-next/runtime-executor` with SQL-specific adapters, drivers, and codecs. It provides the public runtime API for SQL-based databases, including execution-plane composition via `ExecutionStack` and env-free `ExecutionContext` creation for query lanes. +The SQL runtime package implements the SQL family runtime by composing `@prisma-next/runtime-executor` with SQL-specific adapters, drivers, and codecs. It provides the public runtime API for SQL-based databases, including execution-plane composition via `ExecutionStack` and `ExecutionContext` creation for query lanes.
21-22: Same issue: remove "env-free" terminology.Suggested fix
- **Execution Stack Composition**: Compose runtime descriptors into a reusable `ExecutionStack` -- **Execution Context Creation**: Build env-free contexts for query lanes (contract + registries + types) +- **Execution Context Creation**: Build contexts for query lanes (contract + registries + types)packages/2-sql/5-runtime/src/sql-runtime.ts (1)
288-295: Single overload with identical signature is unnecessary.The overload declaration (lines 288-290) has the same signature as the implementation (lines 292-294). A single function without the overload declaration would suffice.
Proposed simplification
-export function createRuntime<TContract extends SqlContract<SqlStorage>, TTargetId extends string>( - options: RuntimeStackOptions<TContract, TTargetId>, -): Runtime; - export function createRuntime<TContract extends SqlContract<SqlStorage>, TTargetId extends string>( options: RuntimeStackOptions<TContract, TTargetId>, ): Runtime { return createRuntimeFromStack(options); }
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/2-sql/4-lanes/orm-lane/test/orm.builder.test.ts (1)
107-149: Consider using object matchers for plan assertions.Per coding guidelines, prefer
toMatchObjectover multiple individual assertions when checking 2+ related values. The current pattern with separate casts could be simplified:♻️ Suggested refactor for plan assertions
it('builds plan with findMany', () => { const builder = (o as unknown as { user: () => unknown }).user(); const plan = ( builder as { findMany: (options?: { params?: Record<string, unknown> }) => unknown } ).findMany({ params: {} }); - expect(plan).toBeDefined(); - expect((plan as { meta: { lane: string } }).meta.lane).toBe('orm'); - expect((plan as { ast: { kind: string } }).ast?.kind).toBe('select'); + expect(plan).toMatchObject({ + meta: { lane: 'orm' }, + ast: { kind: 'select' }, + }); }); it('builds plan with findFirst', () => { const builder = (o as unknown as { user: () => unknown }).user(); const plan = ( builder as { findFirst: (options?: { params?: Record<string, unknown> }) => unknown } ).findFirst({ params: {} }); - expect(plan).toBeDefined(); - expect((plan as { meta: { lane: string } }).meta.lane).toBe('orm'); - expect((plan as { ast: { limit: number } }).ast?.limit).toBe(1); + expect(plan).toMatchObject({ + meta: { lane: 'orm' }, + ast: { limit: 1 }, + }); });Note: This is a pre-existing pattern, not introduced by this PR's changes.
packages/2-sql/3-tooling/family/src/core/runtime-instance.ts (1)
17-18: Move runtime re-export out ofsrc/core.Re-exporting
SqlRuntimeAdapterInstancefrom@prisma-next/sql-runtimepulls a runtime-plane dependency into the shared/core layer and violates the “re-exports only in exports/” rule. Please relocate this export to the runtime entrypoint (e.g.,src/exports/runtime.ts) and keepsrc/corefree of runtime imports.As per coding guidelines, shared-core code must avoid runtime-plane imports and re-exports outside `exports/`.🛠️ Proposed change (remove from core)
-// Re-export SqlRuntimeAdapterInstance from sql-runtime for consumers -export type { SqlRuntimeAdapterInstance } from '@prisma-next/sql-runtime';
🤖 Fix all issues with AI agents
In `@packages/2-sql/3-tooling/family/src/core/runtime-descriptor.ts`:
- Around line 4-13: The create() implementation on sqlRuntimeFamilyDescriptor
violates the RuntimeFamilyDescriptor generic signature by omitting the required
options parameter; update the create method to accept the generic-parameterized
options object (TTargetId generic) matching the interface — i.e., change
create() to create<TTargetId extends string>(options: { target:
RuntimeTargetDescriptor<'sql', TTargetId>; adapter:
RuntimeAdapterDescriptor<'sql', TTargetId>; driver:
RuntimeDriverDescriptor<'sql', TTargetId>; extensionPacks: readonly
RuntimeExtensionDescriptor<'sql', TTargetId>[]; }): SqlRuntimeFamilyInstance —
and inside the function call or forward options to
createSqlRuntimeFamilyInstance (or accept and ignore options if truly unused) so
the signature conforms to RuntimeFamilyDescriptor.
In `@packages/2-sql/5-runtime/test/utils.ts`:
- Around line 186-198: Add an explicit return type to the
createTestStackInstance function to avoid relying on inference: annotate its
signature with the concrete return type (for example use ReturnType<typeof
instantiateExecutionStack> or the actual ExecutionStack instance type) so
callers and future changes are checked by the compiler; update the function
signature that currently declares createTestStackInstance(...) to include that
return type and ensure the body still returns instantiateExecutionStack(stack).
In `@test/integration/utils/framework-components.ts`:
- Around line 47-50: Remove the redundant comment "// Runtime descriptors for
use with createExecutionStack" above the exported descriptors; the variables
postgresTargetRuntimeDescriptor, postgresAdapterRuntimeDescriptor, and
pgvectorExtensionRuntimeDescriptor already convey intent and the comment will
become stale if APIs change (e.g., createExecutionStack), so delete the comment
line and keep the three export statements as-is.
♻️ Duplicate comments (4)
packages/2-sql/5-runtime/src/sql-runtime.ts (2)
272-274: Consider usingifDefined()helper for conditional spreading.Per past review feedback, there may be a helper for this pattern. If
ifDefined()is available, it could simplify these lines.#!/bin/bash # Search for ifDefined helper in the codebase rg -n 'export.*ifDefined|function ifDefined' --type=ts
208-211: Remove redundantyield* []before throwing.The
yield* []yields nothing and serves no purpose before the error is thrown. This was flagged in a previous review.Proposed simplification
async *execute() { - yield* []; throw missingDriver(); },packages/2-sql/5-runtime/README.md (1)
13-13: Remove "env-free" terminology.The term "env-free" appears here and on line 22. This terminology was flagged in a previous review as meaningless and should be stripped from the repo.
Proposed fix
-The SQL runtime package implements the SQL family runtime by composing `@prisma-next/runtime-executor` with SQL-specific adapters, drivers, and codecs. It provides the public runtime API for SQL-based databases, including execution-plane composition via `ExecutionStack` and env-free `ExecutionContext` creation for query lanes. +The SQL runtime package implements the SQL family runtime by composing `@prisma-next/runtime-executor` with SQL-specific adapters, drivers, and codecs. It provides the public runtime API for SQL-based databases, including execution-plane composition via `ExecutionStack` and `ExecutionContext` creation for query lanes.Line 22:
-- **Execution Context Creation**: Build env-free contexts for query lanes (contract + registries + types) +- **Execution Context Creation**: Build contexts for query lanes (contract + registries + types)packages/2-sql/5-runtime/src/sql-context.ts (1)
122-162: Consider collecting all missing extension packs before throwing.The loop throws on the first missing extension pack, which means users only see one error at a time. Consider collecting all missing pack IDs and throwing a single error listing all of them for better developer experience.
♻️ Proposed fix to report all missing packs at once
- for (const packId of result.missingExtensionPackIds) { - throw new Error( - `Contract requires extension pack '${packId}', but runtime descriptors do not provide a matching component.`, - ); + if (result.missingExtensionPackIds.length > 0) { + const packList = result.missingExtensionPackIds.map(id => `'${id}'`).join(', '); + throw new Error( + `Contract requires extension pack(s) ${packList}, but runtime descriptors do not provide matching component(s).`, + ); }
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/2-sql/5-runtime/test/parameterized-types.test.ts`:
- Around line 1-4: The test currently duplicates stack wiring by directly
importing and using createExecutionStack and instantiateExecutionStack; replace
that setup with the shared helper createTestContext from the test utils to avoid
duplication: import createTestContext (and any needed options) and use it to
obtain the execution stack/context for the tests instead of calling
createExecutionStack/instantiateExecutionStack directly, updating the tests that
reference those symbols (createExecutionStack, instantiateExecutionStack) to use
the context API returned by createTestContext.
♻️ Duplicate comments (10)
packages/2-sql/5-runtime/README.md (1)
13-13: Remove “env-free” wording per prior guidance.Please strip “env-free” from these references to align with earlier review feedback.
Also applies to: 21-22
examples/prisma-next-demo/test/runtime.offline.integration.test.ts (2)
19-43: Wrap test body intry/finallyto ensureruntime.close()always runs.If an assertion fails before line 42, the runtime won't be closed, potentially leaving resources dangling.
✅ Suggested fix
it('builds plans without driver options', async () => { const { executionStackInstance, executionContext, sql, tables } = await loadModules(); const runtime = createRuntime({ stackInstance: executionStackInstance, contract: executionContext.contract, context: executionContext, verify: { mode: 'onFirstUse', requireMarker: false }, }); + try { const plan = sql.from(tables.user).select({ id: tables.user.columns.id }).limit(1).build(); expect(plan).toMatchObject({ ast: { kind: 'select' }, meta: { lane: 'dsl' }, }); await expect(async () => { for await (const _row of runtime.execute(plan)) { // offline runtime should not execute } }).rejects.toMatchObject({ code: 'RUNTIME.DRIVER_MISSING' }); - - await runtime.close(); + } finally { + await runtime.close(); + } });
56-61: RestoreDATABASE_URLeven if it was an empty string.The truthy check
if (original)skips restoring whenDATABASE_URLwas''. Useoriginal !== undefinedto preserve the exact prior value.✅ Suggested fix
} finally { - if (original) { + if (original !== undefined) { process.env['DATABASE_URL'] = original; } else { delete process.env['DATABASE_URL']; } }packages/2-sql/5-runtime/src/sql-context.ts (1)
122-162: LGTM! Validation function properly checks contract-stack compatibility.
assertExecutionStackContractRequirementscorrectly validates:
- Family match (SQL family)
- Target match (e.g., postgres)
- Extension pack requirements
Note: The loop at lines 157-161 still throws on the first missing extension pack rather than collecting all missing packs, as flagged in a previous review. This is a minor UX consideration but doesn't affect correctness.
packages/2-sql/5-runtime/test/utils.ts (1)
186-198: Consider adding an explicit return type forcreateTestStackInstance.The function relies on type inference for its return type. Adding an explicit return type would improve documentation and catch breaking changes earlier, as noted in a previous review.
♻️ Suggested improvement
export function createTestStackInstance(options?: { extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>; driver?: RuntimeDriverDescriptor<'sql', 'postgres', SqlRuntimeDriverInstance<'postgres'>>; -}) { +}): ReturnType<typeof instantiateExecutionStack> { const stack = createExecutionStack({packages/2-sql/5-runtime/test/execution-stack.test.ts (1)
96-124: Use a double-cast for the mock driver instance.Direct casting for mocks violates the testing guideline.
As per coding guidelines, mocks in tests should use double-casts.♻️ Suggested fix
- return Object.assign( - { - familyId: 'sql' as const, - targetId: 'postgres' as const, - }, - driver, - ) as SqlRuntimeDriverInstance<'postgres'>; + return Object.assign( + { + familyId: 'sql' as const, + targetId: 'postgres' as const, + }, + driver, + ) as unknown as SqlRuntimeDriverInstance<'postgres'>;packages/2-sql/5-runtime/test/async-iterable-result.test.ts (1)
78-122: Consider extracting shared stack/runtime setup.Both tests repeat the same driver/stack/context wiring; a helper would reduce duplication and maintenance.
♻️ Sketch of helper extraction
+function createTestRuntime(driver: MockDriver) { + const adapter = createStubAdapter(); + const driverDescriptor: RuntimeDriverDescriptor<'sql', 'postgres'> = { + kind: 'driver', + id: 'test-driver', + version: '0.0.1', + familyId: 'sql' as const, + targetId: 'postgres' as const, + create() { + return Object.assign(driver, { + familyId: 'sql' as const, + targetId: 'postgres' as const, + }); + }, + }; + const stack = createExecutionStack({ + target: { + kind: 'target', + id: 'postgres', + version: '0.0.1', + familyId: 'sql' as const, + targetId: 'postgres' as const, + create() { + return { familyId: 'sql' as const, targetId: 'postgres' as const }; + }, + }, + adapter: { + kind: 'adapter', + id: 'test-adapter', + version: '0.0.1', + familyId: 'sql' as const, + targetId: 'postgres' as const, + create() { + return Object.assign( + { familyId: 'sql' as const, targetId: 'postgres' as const }, + adapter, + ); + }, + }, + driver: driverDescriptor, + extensionPacks: [], + }); + const stackInstance = instantiateExecutionStack(stack); + const context = createExecutionContext({ contract: fixtureContract, stackInstance }); + const runtime = createRuntime({ + stackInstance, + contract: fixtureContract, + context, + driverOptions: {}, + verify: { mode: 'onFirstUse', requireMarker: false }, + }); + return { runtime }; +}Also applies to: 157-201
examples/prisma-orm-demo/src/prisma-next/runtime.ts (1)
7-16: Type the contract when callingvalidateContract.The contract is validated without a concrete contract type, which collapses inference in downstream runtime/context typing. Import the generated
Contracttype and call the generic form.
As per coding guidelines.✅ Proposed fix
+import type { Contract } from './contract.d'; import contractJson from './contract.json' with { type: 'json' }; -const contract = validateContract(contractJson); +const contract = validateContract<Contract>(contractJson);Also applies to: 30-30
packages/2-sql/5-runtime/test/sql-runtime.test.ts (1)
443-493: Test name says offline driver throws, but no failure is asserted.The test only checks that a runtime is created. It should trigger execution (or connect) and assert the
RUNTIME.DRIVER_MISSINGerror.
As per previous review feedback.✅ Proposed fix
const runtime = createRuntime({ stackInstance, contract: testContract, // No driverOptions - uses offline driver verify: { mode: 'onFirstUse', requireMarker: false }, }); // The runtime is created, but operations will fail expect(runtime).toBeDefined(); + + const mockPlan = { + sql: 'SELECT 1', + params: [], + refs: { tables: [], columns: [] }, + }; + await expect(async () => { + for await (const _row of runtime.execute(mockPlan as any)) { + // no-op + } + }).rejects.toMatchObject({ code: 'RUNTIME.DRIVER_MISSING' });packages/2-sql/5-runtime/src/sql-runtime.ts (1)
198-212: Remove the redundantyield* []in the offline driver.The generator yields nothing before throwing, so the
yield* []is a no-op.♻️ Proposed simplification
async *execute() { - yield* []; throw missingDriver(); },
1ff0a33 to
09c7652
Compare
Document RUNTIME.DRIVER_OPTIONS_WITHOUT_DESCRIPTOR and RUNTIME.INVALID_DRIVER_INSTANCE alongside existing error codes.
- Update sql-family README to clarify ./runtime is identity-only and point to sql-runtime for factory functions - Use process.exitCode instead of process.exit(1) in seed script to allow event loop cleanup
Separate the inline type import into a dedicated import type statement to comply with the no-inline-imports rule.
Remove duplicate type definition from runtime-instance.ts and re-export from @prisma-next/sql-runtime where the canonical definition lives.
ae382cb to
c2838f2
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)
examples/prisma-next-demo/src/entry.ts (1)
44-50: Avoid optional chaining for validated fields.
Line 49 usesfield?.column, which can render"undefined"and conflicts with the validated-contract expectation. Prefer direct access (or an explicit fallback if validation is not guaranteed). As per coding guidelines, prefer assertions over defensive checks after validation.♻️ Proposed tweak
- <span class="col-type">→ ${field?.column}</span> + <span class="col-type">→ ${field.column}</span>
🤖 Fix all issues with AI agents
In `@examples/prisma-next-demo/test/runtime.offline.integration.test.ts`:
- Around line 1-34: Remove the redundant null-check in the finally block: since
runtime is always assigned by createRuntime before the try, replace the
conditional block that checks if (runtime) before calling runtime.close() with a
direct await runtime.close(); reference createRuntime and the runtime variable
in the finally block to locate the code to change.
♻️ Duplicate comments (2)
examples/prisma-next-demo/src/entry.ts (2)
17-36: Use canonicalContractIRto avoid drift.
Line 31 defines a local IR type that duplicates the shared surface. Import the canonicalContractIRfrom@prisma-next/contract/irand specialize it with your SQL generics to keep the demo aligned with the shared IR contract. As per coding guidelines, prefer canonical contract types.♻️ Proposed refactor
-import type { ModelDefinition, SqlContract, SqlStorage } from '@prisma-next/sql-contract/types'; +import type { ContractIR as BaseContractIR } from '@prisma-next/contract/ir'; +import type { ModelDefinition, SqlStorage } from '@prisma-next/sql-contract/types'; ... -type ContractIR = SqlContract<SqlStorage, Record<string, ModelDefinition>> & { - target: string; - relations: Record<string, Record<string, Relation>>; - capabilities: Record<string, Record<string, boolean>>; - extensionPacks: Record<string, unknown>; -}; +type ContractIR = BaseContractIR< + SqlStorage, + Record<string, ModelDefinition>, + Record<string, Record<string, Relation>> +>;Run this to confirm the
ContractIRexport path in-repo:#!/bin/bash rg -n "export interface ContractIR" packages/1-framework/1-core/shared/contract/src/ir.ts rg -n "\"\\./ir\"" packages/1-framework/1-core/shared/contract/package.json
157-166: Replace blind casts with a type guard before rendering.
Lines 159 and 165 useas unknown as ContractIR, which bypasses type safety and can mask invalid JSON. Gate rendering behind a small type guard and provide a fallback. As per coding guidelines, avoid blind casts.♻️ Proposed fix
+const isContractIR = (value: unknown): value is ContractIR => { + if (!value || typeof value !== 'object') return false; + const v = value as Record<string, unknown>; + return ( + Object.hasOwn(v, 'target') && + Object.hasOwn(v, 'coreHash') && + Object.hasOwn(v, 'models') && + Object.hasOwn(v, 'storage') && + Object.hasOwn(v, 'relations') && + Object.hasOwn(v, 'capabilities') && + Object.hasOwn(v, 'extensionPacks') + ); +}; ... -if (app) { - app.innerHTML = renderContract(contractJson as unknown as ContractIR); -} +if (app && isContractIR(contractJson)) { + app.innerHTML = renderContract(contractJson); +} else if (app) { + app.textContent = 'Invalid contract JSON'; +} ... - if (app && newContract) { - app.innerHTML = renderContract(newContract as unknown as ContractIR); - } + if (app && isContractIR(newContract)) { + app.innerHTML = renderContract(newContract); + } else if (app) { + app.textContent = 'Invalid contract JSON'; + }Optional verification to locate remaining blind casts:
#!/bin/bash rg -n "as unknown as ContractIR" examples/prisma-next-demo/src/entry.ts
There was a problem hiding this comment.
Actionable comments posted: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (7)
packages/2-sql/4-lanes/orm-lane/README.md (1)
30-43: Document the ExecutionContext/stack-based runtime wiring.The architecture diagram and steps still read as “Plan → Runtime” without acknowledging the new ExecutionStack/ExecutionContext wiring introduced in this PR. This is likely to become stale or misleading for readers trying to map ORM plans to runtime execution.
Consider updating the diagram/text to reflect that runtime construction is now via ExecutionContext (from a stack instance), without implying ORM builds the stack itself.
✏️ Suggested doc tweak
flowchart LR ORM[ORM Builder] --> AST[SqlQueryPlan AST] AST --> Plan[SqlQueryPlan] - Plan --> Runtime[Runtime Lowering + Execute] + Plan --> Runtime[Runtime (from ExecutionContext)] Core[Relational Core] --> ORM-3. Returns plans that can be executed by the runtime +3. Returns plans that can be executed by a runtime constructed from an ExecutionContext (via an ExecutionStack instance)examples/prisma-next-demo/README.md (1)
48-50: Align no‑emit file paths between “Workflows” and “Key Files”.The Workflows section lists no‑emit files under
src/prisma/, but Key Files listssrc/prisma-no-emit/. One of these is wrong. Please reconcile to avoid broken paths. As per coding guidelines, README accuracy is required.📝 Suggested doc fix (if Workflows section is correct)
-- `src/prisma-no-emit/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow) -- `src/prisma-no-emit/runtime-no-emit.ts` - Runtime factory (no-emit workflow) +- `src/prisma/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow) +- `src/prisma/runtime-no-emit.ts` - Runtime factory (no-emit workflow)Also applies to: 111-115
packages/2-sql/4-lanes/relational-core/test/utils.ts (2)
42-49: Remove legacy_adapterparameter (no BC shims).
_adapteris explicitly retained for backward compatibility but unused. Packages-level guidelines disallow backward-compat shims; update call sites and drop the param/docs.♻️ Proposed cleanup
- * `@param` adapter - Optional adapter (for backward compatibility with old test code, but not used) - * `@param` options - Optional extensions to register operations and codecs + * `@param` options - Optional extensions to register operations and codecs @@ export function createTestContext<TContract extends SqlContract<SqlStorage>>( contract: TContract, - _adapter?: Adapter<SelectAst, SqlContract<SqlStorage>, LoweredStatement>, options?: { extensions?: ReadonlyArray<Extension>; }, ): ExecutionContext<TContract> {
73-78: Populatetypesregistry instead of{}.ExecutionContext expects a types helper registry derived from
contract.storage.types+ initialized codecs. Returning{}weakens test fidelity and risks masking runtime issues with type helpers.Build it using the same pattern as production: iterate
contract.storage.typesentries, look up each codec descriptor, and apply init hooks where available (seepackages/2-sql/5-runtime/src/sql-context.ts:257-260for reference).examples/prisma-next-demo/src/entry.ts (1)
44-50: Remove unnecessary optional chaining sincecolumnis guaranteed to be present.The
ModelFieldtype definescolumnas a requiredstringproperty, neverundefined. The optional chaining (?.) is unnecessary and should be removed per the guidance to "Remove optional chaining and conditional property spreading for properties that are guaranteed to exist."- <span class="col-type">→ ${field?.column}</span> + <span class="col-type">→ ${field.column}</span>packages/3-extensions/compat-prisma/src/prisma-client.ts (1)
375-407: Fix invalid driverOptions format for postgres driver.The
driverOptionspassed tocreateRuntimemust conform toPostgresDriverOptions, which requires{ connect: { client: Client } | { pool: Pool }, cursor?: ... }. The current code passes{ connectionString }, which is incompatible with the driver's expected options format and will cause a runtime error.Either construct a proper connection pool and pass
{ connect: { pool }, cursor: { disabled: true } }(matching test usage), or create the driver first usingcreatePostgresDriver(connectionString)before passing to runtime.packages/2-sql/5-runtime/test/sql-runtime.test.ts (1)
169-174: Prefer an object matcher for related runtime shape checks.
Multiple relatedtoBeDefined()checks can be expressed more concisely with a single matcher.♻️ Suggested refactor
- expect(runtime).toBeDefined(); - expect(runtime.execute).toBeDefined(); - expect(runtime.telemetry).toBeDefined(); - expect(runtime.operations).toBeDefined(); - expect(runtime.close).toBeDefined(); + expect(runtime).toMatchObject({ + execute: expect.any(Function), + telemetry: expect.any(Function), + operations: expect.any(Function), + close: expect.any(Function), + });As per coding guidelines, prefer object matchers for multiple related assertions in tests.
🤖 Fix all issues with AI agents
In `@docs/architecture` docs/subsystems/4. Runtime & Plugin Framework.md:
- Around line 46-56: The example passed to createRuntime uses the wrong
driverOptions shape; update the driverOptions in the createRuntime call to the
documented nested pattern so it uses connect: e.g. replace driverOptions: {
connectionString: process.env.DATABASE_URL } with driverOptions: { connect: {
connectionString: process.env.DATABASE_URL } } (or driverOptions: { connect: {
pool } } for pool-based configs) so it matches the runtime/driver API.
In `@examples/prisma-next-demo/README.md`:
- Around line 66-72: The diagram incorrectly wires Runtime from ExecutionStack;
update the graph so Runtime is created from the ExecutionStackInstance and
context instead: remove the edge "Stack --> Runtime" and add (or ensure) the
edge "StackI --> Runtime" while keeping "Context --> Runtime" so Runtime is
produced from ExecutionStackInstance (stackInstance) + ExecutionContext
(context). Reference nodes: ExecutionStack (Stack), ExecutionStackInstance
(StackI / stackInstance), ExecutionContext (Context), and Runtime.
In `@examples/prisma-next-demo/scripts/seed.ts`:
- Around line 45-46: The seed script currently uses hard-coded IDs (e.g., "id:
1", "id: 2") which will break when re-running the seeder; update the seeding
logic in examples/prisma-next-demo/scripts/seed.ts to either remove explicit id
properties so the DB auto-generates them, or convert the inserts into idempotent
operations (use prisma.createMany({ data: [...], skipDuplicates: true }) or
prisma.<Model>.upsert({ where: { email }, update: {}, create: {...} }) for each
record). Locate the blocks that include "id: 1" / "id: 2" and apply one of these
two fixes so the seed becomes re-runnable without conflicts.
In `@examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts`:
- Around line 1-37: The imported `contract` is unvalidated; import the
`Contract` type from `../../prisma/contract.d.ts` and run
`validateContract<Contract>(contract)` (from your validation utility) before
calling `createExecutionContext`; replace the raw `contract` passed into
`createExecutionContext` with the validated result so `createExecutionContext({
contract: validatedContract, stackInstance: executionStackInstance })` uses the
validated contract.
In `@examples/prisma-next-demo/src/prisma/runtime.ts`:
- Around line 5-28: getRuntime creates a new Pool and passes it into
createRuntime but never exposes or tracks the Pool for shutdown, risking leaked
DB connections; modify getRuntime (and its return) to either (a) return a
cleanup handle alongside the Runtime (e.g., return { runtime, close: async () =>
pool.end() }) or (b) register the pool with the runtime shutdown path (similar
to closePrismaNextRuntime) so that calling runtime.close() also calls
pool.end(), or (c) document that runtime.close() must close the pool and ensure
createRuntime is wired to call pool.end(); update references to Pool,
getRuntime, createRuntime, and any closePrismaNextRuntime-style shutdown helper
to implement the chosen cleanup approach.
In `@examples/prisma-next-demo/src/queries/similarity-search.ts`:
- Around line 3-11: The parameter order for similaritySearch is inconsistent
with other runtime-based helpers (it currently is similaritySearch(queryVector,
runtime, limit)); change its signature to similaritySearch(runtime: Runtime,
queryVector: number[], limit = 10) and update every call site to pass the
Runtime first (matching helpers like getUsers), as well as adjust any internal
references to the parameter names to the new order so runtime is used where
expected.
In `@packages/1-framework/1-core/runtime/execution-plane/src/stack.ts`:
- Around line 12-36: Add a brief inline comment above the ExecutionStack
interface explaining that the generic defaults
(RuntimeAdapterInstance<TFamilyId, TTargetId>, RuntimeDriverInstance<TFamilyId,
TTargetId>, RuntimeExtensionInstance<TFamilyId, TTargetId>) are provided because
the interface is meaningfully usable with those common instance shapes (allowing
shorthand like ExecutionStack<'sql','postgres'>), and note when consumers should
supply explicit type arguments (e.g., when using custom adapter/driver/extension
instance shapes or stricter typing is required); reference the interface name
ExecutionStack and the default types RuntimeAdapterInstance,
RuntimeDriverInstance, and RuntimeExtensionInstance in the comment.
In `@packages/2-sql/3-tooling/family/src/core/runtime-instance.ts`:
- Around line 3-4: Remove the redundant inline comment above the re-export; keep
only the export statement "export type { SqlRuntimeAdapterInstance,
SqlRuntimeDriverInstance } from '@prisma-next/sql-runtime';" and delete the
comment line so the file contains just the self-explanatory type re-export.
In `@packages/2-sql/5-runtime/src/sql-runtime.ts`:
- Around line 233-245: The code validates the stack against the standalone
`contract` but then uses `context.contract`, which can mismatch; in
`createRuntime` derive an `effectiveContract` (e.g., const effectiveContract =
context?.contract ?? contract) and use that for both
`assertExecutionStackContractRequirements` and when creating or accepting
`resolvedContext` so validation and runtime use the same contract; apply the
same pattern to the other block referenced around `resolvedContext`/context
handling (lines ~276-285) to ensure consistent contract usage across
`createRuntime`, `assertExecutionStackContractRequirements`, and
`createExecutionContext`.
In `@packages/2-sql/5-runtime/test/sql-runtime.test.ts`:
- Around line 112-116: The test is using a direct cast to
SqlRuntimeAdapterInstance<'postgres'>; change the unsafe cast to the explicit
double-cast pattern by first casting the composed object to unknown and then to
SqlRuntimeAdapterInstance<'postgres'> (i.e., use "as unknown as
SqlRuntimeAdapterInstance<'postgres'>") so the mock boundary is explicit; apply
this to the return expression that merges { familyId: 'sql', targetId:
'postgres' } with the adapter variable and any similar adapter/driver instance
mocks in this file.
♻️ Duplicate comments (4)
packages/2-sql/3-tooling/family/README.md (1)
123-130: Add@prisma-next/sql-runtimeto the Dependencies list.The README now references runtime factory helpers from
@prisma-next/sql-runtime, but the Dependencies section does not list it. Keep the dependency list aligned with referenced packages. As per coding guidelines.examples/prisma-next-demo/src/entry.ts (2)
17-38: Prefer the canonicalContractIRtype instead of a local shim.Reusing the shared IR type keeps the demo aligned with the core contract shape and avoids maintaining a bespoke intersection.
♻️ Suggested refactor
-import type { ModelDefinition, SqlContract, SqlStorage } from '@prisma-next/sql-contract/types'; +import type { ModelDefinition, SqlStorage } from '@prisma-next/sql-contract/types'; +import type { ContractIR as ContractIRBase } from '@prisma-next/contract/ir'; -type ContractIR = SqlContract<SqlStorage, Record<string, ModelDefinition>> & { - target: string; - relations: Record<string, Record<string, Relation>>; - capabilities: Record<string, Record<string, boolean>>; - extensionPacks: Record<string, unknown>; -}; +type ContractIR = ContractIRBase< + SqlStorage, + Record<string, ModelDefinition>, + Record<string, Record<string, Relation>> +>;Please verify that
@prisma-next/contract/iris the intended canonical source forContractIRin this repo.
157-165: Replaceas unknown as ContractIRwith a lightweight guard before rendering.Double casting bypasses type safety and can mask shape mismatches; a small
isContractIRguard keeps the initial render and HMR safe.🛡️ Suggested guard + usage
+function isContractIR(value: unknown): value is ContractIR { + return ( + typeof value === 'object' && + value !== null && + Object.hasOwn(value, 'models') && + Object.hasOwn(value, 'storage') && + Object.hasOwn(value, 'relations') && + Object.hasOwn(value, 'capabilities') && + Object.hasOwn(value, 'extensionPacks') + ); +} -if (app) { - app.innerHTML = renderContract(contractJson as unknown as ContractIR); -} +if (app && isContractIR(contractJson)) { + app.innerHTML = renderContract(contractJson); +} - if (app && newContract) { - app.innerHTML = renderContract(newContract as unknown as ContractIR); - } + if (app && newContract && isContractIR(newContract)) { + app.innerHTML = renderContract(newContract); + }Please verify the guard covers the fields
renderContractreads. As per coding guidelines, avoid blind casts and prefer type guards.packages/2-sql/5-runtime/test/execution-stack.test.ts (1)
116-124: Use double-cast for mock driver instance.The mock driver is directly cast to
SqlRuntimeDriverInstance<'postgres'>. Per coding guidelines, mocks in tests should useas unknown as ...to avoid unsafe direct casting.♻️ Suggested fix
create() { return Object.assign( { familyId: 'sql' as const, targetId: 'postgres' as const, }, driver, - ) as SqlRuntimeDriverInstance<'postgres'>; + ) as unknown as SqlRuntimeDriverInstance<'postgres'>; },
| import postgresAdapter from '@prisma-next/adapter-postgres/runtime'; | ||
| import { | ||
| createExecutionStack, | ||
| instantiateExecutionStack, | ||
| } from '@prisma-next/core-execution-plane/stack'; | ||
| import postgresDriver from '@prisma-next/driver-postgres/runtime'; | ||
| import { sql as sqlBuilder } from '@prisma-next/sql-lane'; | ||
| import { orm as ormBuilder } from '@prisma-next/sql-orm-lane'; | ||
| import { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema'; | ||
| import { createExecutionContext } from '@prisma-next/sql-runtime'; | ||
| import postgresTarget from '@prisma-next/target-postgres/runtime'; | ||
| // Use contract directly from TypeScript - no emit needed! | ||
| import { contract } from '../../prisma/contract'; | ||
|
|
||
| export const executionStack = createExecutionStack({ | ||
| target: postgresTarget, | ||
| adapter: postgresAdapter, | ||
| driver: postgresDriver, | ||
| extensionPacks: [], | ||
| }); | ||
|
|
||
| export const executionStackInstance = instantiateExecutionStack(executionStack); | ||
| export const executionContext = createExecutionContext({ | ||
| contract, | ||
| stackInstance: executionStackInstance, | ||
| }); | ||
|
|
||
| export const sql = sqlBuilder<typeof contract>({ | ||
| context: executionContext, | ||
| }); | ||
|
|
||
| export const schema = schemaBuilder<typeof contract>(executionContext); | ||
| export const tables = schema.tables; | ||
|
|
||
| export const orm = ormBuilder<typeof contract>({ | ||
| context: executionContext, | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check the contract module for validation and Contract type exports
rg -n "validateContract|export type Contract|export.*contract" examples/prisma-next-demo/src/prisma -g '*.ts' --max-count=50Repository: prisma/prisma-next
Length of output: 405
🏁 Script executed:
#!/bin/bash
# Check if contract.d.ts exists in the prisma directory
find examples/prisma-next-demo -name "contract.d.ts" -o -name "contract.ts" | head -20Repository: prisma/prisma-next
Length of output: 157
🏁 Script executed:
#!/bin/bash
# Look at the actual contract import to understand its structure
cat -n examples/prisma-next-demo/src/prisma/contract.ts 2>/dev/null | head -50Repository: prisma/prisma-next
Length of output: 44
🏁 Script executed:
#!/bin/bash
# Search for validateContract across the codebase to understand correct import
rg -n "export.*validateContract|from.*validateContract" --type ts -g '*.ts' | head -20Repository: prisma/prisma-next
Length of output: 674
🏁 Script executed:
#!/bin/bash
# Check execution-context.ts to see the correct pattern
cat -n examples/prisma-next-demo/src/prisma/execution-context.tsRepository: prisma/prisma-next
Length of output: 1326
🏁 Script executed:
#!/bin/bash
# Check query-no-emit.ts to confirm it doesn't validate
cat -n examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.tsRepository: prisma/prisma-next
Length of output: 1648
🏁 Script executed:
#!/bin/bash
# Check what's exported from ../../prisma/contract (relative to query-no-emit.ts)
cat -n examples/prisma-next-demo/src/prisma/contract.ts 2>/dev/null || echo "contract.ts not found"Repository: prisma/prisma-next
Length of output: 83
🏁 Script executed:
#!/bin/bash
# Also check contract.d.ts
cat -n examples/prisma-next-demo/src/prisma/contract.d.tsRepository: prisma/prisma-next
Length of output: 6894
🏁 Script executed:
#!/bin/bash
# Check what files exist in the prisma directory
ls -la examples/prisma-next-demo/src/prisma/Repository: prisma/prisma-next
Length of output: 487
🏁 Script executed:
#!/bin/bash
# Search for where contract is exported as a value
rg -n "export.*contract" examples/prisma-next-demo/src/prisma/ --type ts --type jsRepository: prisma/prisma-next
Length of output: 44
🏁 Script executed:
#!/bin/bash
# Check if there's a JSON contract file
find examples/prisma-next-demo -name "contract.json" | head -5Repository: prisma/prisma-next
Length of output: 112
🏁 Script executed:
#!/bin/bash
# Check if there are any contract files in prisma directory (all types)
find examples/prisma-next-demo/src/prisma -name "contract*" -type fRepository: prisma/prisma-next
Length of output: 163
🏁 Script executed:
#!/bin/bash
# Try to understand what query-no-emit.ts is actually trying to do
# by checking if the import resolves and what it might be importing
rg -n "export.*contract" examples/prisma-next-demo/prisma -A 2 -B 2 --type ts --type js 2>/dev/null || echo "No matches in prisma dir"Repository: prisma/prisma-next
Length of output: 460
🏁 Script executed:
#!/bin/bash
# Check if there's a re-export somewhere (like in index.ts)
find examples/prisma-next-demo/src/prisma -name "*.ts" -o -name "*.js" | xargs grep -l "export.*contract" 2>/dev/null || echo "No files found"Repository: prisma/prisma-next
Length of output: 76
🏁 Script executed:
#!/bin/bash
# Check what's in the prisma directory (authoring directory)
ls -la examples/prisma-next-demo/prisma/Repository: prisma/prisma-next
Length of output: 296
🏁 Script executed:
#!/bin/bash
# Check the actual content of prisma/contract.ts to see what it exports
head -30 examples/prisma-next-demo/prisma/contract.tsRepository: prisma/prisma-next
Length of output: 1375
🏁 Script executed:
#!/bin/bash
# Check if query-no-emit.ts is trying to import from a non-existent location
# by checking the actual path resolution
file examples/prisma-next-demo/src/prisma-no-emit/../../prisma/contract.ts 2>&1 || echo "File does not exist"Repository: prisma/prisma-next
Length of output: 124
🏁 Script executed:
#!/bin/bash
# Verify the exact path resolution: from prisma-no-emit, going up 2 levels should reach examples/prisma-next-demo level
# Then /prisma/contract should resolve correctly
cd examples/prisma-next-demo/src/prisma-no-emit && pwd && ls -la ../../prisma/contract.*Repository: prisma/prisma-next
Length of output: 199
🏁 Script executed:
#!/bin/bash
# Check what defineContract returns - is it a validated contract or a builder?
rg -n "defineContract|export const contract" examples/prisma-next-demo/prisma/contract.ts -A 5 -B 2Repository: prisma/prisma-next
Length of output: 665
🏁 Script executed:
#!/bin/bash
# Check the type of the contract exported from prisma/contract.ts
rg -n "class|interface|type.*Contract|return.*" examples/prisma-next-demo/prisma/contract.ts | head -20Repository: prisma/prisma-next
Length of output: 87
🏁 Script executed:
#!/bin/bash
# Look at the full prisma/contract.ts file to understand what's being exported
cat examples/prisma-next-demo/prisma/contract.tsRepository: prisma/prisma-next
Length of output: 2563
🏁 Script executed:
#!/bin/bash
# Check if there's an index.ts or any file that re-exports contract
find examples/prisma-next-demo/src/prisma -name "*.ts" -type f | xargs catRepository: prisma/prisma-next
Length of output: 8022
🏁 Script executed:
#!/bin/bash
# Check if the import might be resolving to contract.json through a package.json or tsconfig
cat examples/prisma-next-demo/tsconfig.json | head -50Repository: prisma/prisma-next
Length of output: 373
🏁 Script executed:
#!/bin/bash
# Verify: does query-no-emit.ts actually exist and is it being used?
ls -la examples/prisma-next-demo/src/prisma-no-emit/Repository: prisma/prisma-next
Length of output: 306
🏁 Script executed:
#!/bin/bash
# Check what query.ts does (in the same src/prisma directory)
cat -n examples/prisma-next-demo/src/prisma/query.tsRepository: prisma/prisma-next
Length of output: 602
🏁 Script executed:
#!/bin/bash
# Let's understand the architecture: why does query-no-emit.ts exist separately
# and what is it trying to accomplish?
head -20 examples/prisma-next-demo/src/prisma-no-emit/runtime-no-emit.tsRepository: prisma/prisma-next
Length of output: 683
🏁 Script executed:
#!/bin/bash
# Look for defineContract and its build() method to understand what gets returned
rg -n "\.build()|interface.*Builder|class.*Builder" packages/2-sql/2-authoring/contract-ts/src -A 3 -B 1 --type ts | head -50Repository: prisma/prisma-next
Length of output: 2771
🏁 Script executed:
#!/bin/bash
# Check what the builder's build() method returns
rg -n "build\(\)|return" packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts -A 2 -B 1 | head -60Repository: prisma/prisma-next
Length of output: 1953
🏁 Script executed:
#!/bin/bash
# Verify: is the no-emit pattern supposed to use unvalidated builder output or should it still validate?
rg -n "no-emit|no emit|noEmit|query-no-emit" examples/prisma-next-demo -i --type ts | head -20Repository: prisma/prisma-next
Length of output: 2485
Validate the contract before creating the ExecutionContext.
The contract imported from ../../prisma/contract is the unvalidated builder output. Import the Contract type from ../../prisma/contract.d.ts (not from contract.ts), then validate using validateContract<Contract>(contract) before passing to createExecutionContext().
🛠️ Suggested fix
import postgresAdapter from '@prisma-next/adapter-postgres/runtime';
import {
createExecutionStack,
instantiateExecutionStack,
} from '@prisma-next/core-execution-plane/stack';
import postgresDriver from '@prisma-next/driver-postgres/runtime';
+import { validateContract } from '@prisma-next/sql-contract-ts/contract';
import { sql as sqlBuilder } from '@prisma-next/sql-lane';
import { orm as ormBuilder } from '@prisma-next/sql-orm-lane';
import { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';
import { createExecutionContext } from '@prisma-next/sql-runtime';
import postgresTarget from '@prisma-next/target-postgres/runtime';
+import type { Contract } from '../../prisma/contract.d';
// Use contract directly from TypeScript - no emit needed!
import { contract } from '../../prisma/contract';
export const executionStack = createExecutionStack({
target: postgresTarget,
adapter: postgresAdapter,
driver: postgresDriver,
extensionPacks: [],
});
export const executionStackInstance = instantiateExecutionStack(executionStack);
+const validatedContract = validateContract<Contract>(contract);
export const executionContext = createExecutionContext({
- contract,
+ contract: validatedContract,
stackInstance: executionStackInstance,
});
-export const sql = sqlBuilder<typeof contract>({
+export const sql = sqlBuilder<typeof validatedContract>({
context: executionContext,
});
-export const schema = schemaBuilder<typeof contract>(executionContext);
+export const schema = schemaBuilder<typeof validatedContract>(executionContext);
export const tables = schema.tables;
-export const orm = ormBuilder<typeof contract>({
+export const orm = ormBuilder<typeof validatedContract>({
context: executionContext,
});🤖 Prompt for AI Agents
In `@examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts` around lines 1
- 37, The imported `contract` is unvalidated; import the `Contract` type from
`../../prisma/contract.d.ts` and run `validateContract<Contract>(contract)`
(from your validation utility) before calling `createExecutionContext`; replace
the raw `contract` passed into `createExecutionContext` with the validated
result so `createExecutionContext({ contract: validatedContract, stackInstance:
executionStackInstance })` uses the validated contract.
There was a problem hiding this comment.
We trust builder output, don't we? validateContract() is intended to validate imported JSON contracts, I thought. @coderabbitai
There was a problem hiding this comment.
@wmadden, you're absolutely right—I apologize for the confusion.
Builder output from defineContract({...}).build() is type-safe and trusted; you don't need runtime validation for it. The validateContract() function is indeed intended for JSON contracts (loaded from disk or external sources) where the shape isn't guaranteed at compile time.
In this file (query-no-emit.ts), you're importing the contract directly from the TypeScript builder, so no validation is needed. The parallel emit-based workflow in execution-context.ts validates because it loads contractJson from a file.
My original comment was incorrect. The code is fine as-is.
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
packages/2-sql/5-runtime/tsup.config.ts (1)
4-13: Align tsup entrypoints/outDir with the standard exports layoutThe config still omits the required
adapter,types,codec-types,control, andruntimeentries and outputs todistinstead ofdist/exports. This will leave expected export entrypoints missing. Please align the entry map and output directory with the standard layout.🔧 Suggested shape (adjust paths to match actual files)
export default defineConfig({ entry: { - index: 'src/exports/index.ts', - 'test/utils': 'test/utils.ts', + adapter: 'src/exports/adapter.ts', + types: 'src/exports/types.ts', + 'codec-types': 'src/exports/codec-types.ts', + control: 'src/exports/control.ts', + runtime: 'src/exports/runtime.ts', + index: 'src/exports/index.ts', + 'test/utils': 'test/utils.ts', }, - outDir: 'dist', + outDir: 'dist/exports', format: ['esm'], sourcemap: true, dts: false, clean: true, target: 'es2022', minify: false, });As per coding guidelines, the tsup config should use a single block with adapter/types/codec-types/control/runtime entries outputting to
dist/exports.examples/prisma-orm-demo/src/prisma-next/runtime.ts (1)
29-54: Callawait client.connect()before passing tocreateRuntime.The
pg.Clientinstance is created on line 29 butclient.connect()is never called before passing it todriverOptions. The postgres driver explicitly does not handle connection (see postgres-driver.ts line 52-54:async connect(): Promise<void> { // No-op: caller controls connecting the underlying client or pool }). The client must be connected by the caller before use.Add
await client.connect();after line 29 to establish the connection.examples/prisma-next-demo/src/entry.ts (1)
44-50: Avoid rendering"undefined"for fields without a column.Provide a fallback when
columnis absent.🐛 Suggested fix
- <span class="col-type">→ ${field?.column}</span> + <span class="col-type">→ ${field.column ?? '—'}</span>docs/reference/query-patterns.md (2)
1-7: Consider adding a note about runtime creation and offline behavior.This document comprehensively covers query patterns. Since the PR introduces offline-by-default runtime behavior (when
driverOptionsis omitted), consider adding a brief note or link in the introduction pointing to documentation about runtime creation and connection management. This would help readers understand the full context of the execution stack.📝 Suggested addition to introduction
# Query Patterns -This document covers standard patterns for working with Prisma Next queries, including table access, type inference, and common usage patterns. +This document covers standard patterns for working with Prisma Next queries, including table access, type inference, and common usage patterns. + +> **Note**: For information about runtime creation, connection management, and offline execution, see [Runtime Patterns](./runtime-patterns.md) or the [SQL Runtime README](../../packages/sql-runtime/README.md).
86-86: Update import paths to use@prisma-next/sql-relational-coreinstead of deprecated@prisma-next/sql-query.The package
@prisma-next/sql-queryno longer exists in the modularized structure. BothResultTypeandparamare now exported from@prisma-next/sql-relational-core:
import type { ResultType } from '@prisma-next/sql-relational-core/types';import { param } from '@prisma-next/sql-relational-core/param';Affected lines
Lines 86, 121, 141, 164 (ResultType imports)
Lines 120, 140 (param imports)Also update:
docs/reference/typescript-patterns.mdline 413, 870, 890examples/prisma-next-demo/test/runtime.integration.test.ts (1)
468-486: Consider using object matchers for related assertions.Per coding guidelines, prefer
toMatchObjectover multiple individualexpect().toHaveProperty()calls when checking related values. Lines 469-481 could be consolidated.♻️ Suggested consolidation
- expect(rows[0]).toHaveProperty('id'); - expect(rows[0]).toHaveProperty('email'); - expect(rows[0]).toHaveProperty('posts'); - expect(Array.isArray(rows[0]!.posts)).toBe(true); - - const alice = rows.find((r) => r.email === '[email protected]'); - expect(alice).toBeDefined(); - expect(alice!.posts).toHaveLength(2); - expect(alice!.posts[0]).toHaveProperty('id'); - expect(alice!.posts[0]).toHaveProperty('title'); - expect(alice!.posts[0]).toHaveProperty('createdAt'); - expect(typeof alice!.posts[0]!.id).toBe('number'); - expect(typeof alice!.posts[0]!.title).toBe('string'); + expect(rows[0]).toMatchObject({ + id: expect.any(Number), + email: expect.any(String), + posts: expect.any(Array), + }); + + const alice = rows.find((r) => r.email === '[email protected]'); + expect(alice).toBeDefined(); + expect(alice!.posts).toHaveLength(2); + expect(alice!.posts[0]).toMatchObject({ + id: expect.any(Number), + title: expect.any(String), + createdAt: expect.anything(), + });
🤖 Fix all issues with AI agents
In `@docs/reference/typescript-patterns.md`:
- Around line 1391-1399: Update the guidance to consistently demonstrate passing
context into the schema function: replace the incorrect sentence "Use
`schema().tables` instead" with "Use `schema(context).tables` instead", and
ensure the example and explanation reference `schema(context)` (and not
`schema()`); also remove or rephrase the note about `makeT()` so it clarifies
that `makeT()` was removed in favor of calling `schema(context)` and that
`tables` should be accessed via `schema(context).tables`.
In `@examples/prisma-next-demo/scripts/seed.ts`:
- Around line 82-88: Extract the magic number 1536 into a named constant (e.g.,
EMBEDDING_DIM or EMBEDDING_DIMENSION) and use that constant inside the
generateEmbedding function instead of the literal; update the for-loop to
iterate to EMBEDDING_DIM and any related code that assumes 1536 to reference the
new constant so the dimension is easy to update and clearer to readers.
In `@examples/prisma-next-demo/src/main-no-emit.ts`:
- Around line 33-47: Extract the duplicated app config schema and loader into a
shared module: move the appConfigSchema and loadAppConfig implementation into a
new module and export loadAppConfig; then replace the duplicated definitions in
main-no-emit.ts and main.ts with an import of loadAppConfig. Ensure the exported
symbols match (appConfigSchema stays internal to the module, export function
loadAppConfig) and that callers use the returned { databaseUrl } shape
unchanged.
In `@examples/prisma-next-demo/test/utils/control-client.ts`:
- Around line 14-15: This file re-exports getRuntime which per guidelines should
not live outside an exports/ facade; remove the re-export from control-client.ts
and update consuming test files to import getRuntime directly from
'../../src/prisma/runtime' (or alternatively move this re-export into an
exports/ test-facade if you intentionally want a single import point); ensure
all references to getRuntime in tests are updated to the new module path.
In `@examples/prisma-orm-demo/test/utils/control-client.ts`:
- Around line 85-96: The Pool created via "new Pool({ connectionString })" must
be closed if createRuntime(...) throws: wrap the call to createRuntime (which
sets the runtime variable) in a try/catch, and in the catch call pool.end()
before rethrowing the error; ensure any early return paths also close the pool
so tests won't hang. Target the block where Pool, createRuntime, runtime, and
pool.end() are used and add the cleanup in the error path.
In `@packages/2-sql/3-tooling/family/src/core/runtime-instance.ts`:
- Around line 3-4: Remove the runtime-plane re-export from the core layer:
delete the export of SqlRuntimeAdapterInstance and SqlRuntimeDriverInstance that
imports from '@prisma-next/sql-runtime' in the core module, and instead add that
exact re-export into the runtime-plane exports module (the runtime entrypoint)
so the core stays free of runtime dependencies; ensure the symbols
SqlRuntimeAdapterInstance and SqlRuntimeDriverInstance are re-exported from the
runtime entrypoint and no imports from '@prisma-next/sql-runtime' remain in
src/core.
In `@packages/2-sql/4-lanes/orm-lane/README.md`:
- Around line 93-96: The README links to "Query Lanes" and "Runtime & Plugin
Framework" use URL-encoded spaces (%20) in their relative paths; update the
documentation and target filenames to remove spaces (prefer hyphenated
filenames) and then change the link targets in README.md to use the new
hyphenated paths (e.g., replace "architecture docs/subsystems/3. Query Lanes.md"
and "architecture docs/subsystems/4. Runtime & Plugin Framework.md" with their
hyphenated equivalents), ensuring the link text ("Query Lanes" and "Runtime &
Plugin Framework") remains unchanged and that the referenced files are
renamed/moved to match.
In `@packages/2-sql/5-runtime/README.md`:
- Around line 58-65: Add a short note to the createRuntime example explaining
that omitting driverOptions (or a connect.connectionString) results in an
offline-only runtime; mention the specific option name driverOptions and the
connect.connectionString field and that consumers must pass driverOptions: {
connect: { connectionString: ... } } to enable a live DB connection when calling
createRuntime.
In `@packages/2-sql/5-runtime/test/sql-runtime.test.ts`:
- Around line 239-249: The test title is ambiguous; rename the it() description
in the test block that calls createTestStackInstance() and createRuntime(...)
from "uses offline driver when stack has driver but driverOptions is undefined"
to "creates runtime in offline mode when driverOptions is undefined" so the name
reflects that the test only verifies runtime creation (offline mode) rather than
asserting driver behavior; update the string passed to the it(...) for that test
case referencing the same block that instantiates stackInstance and calls
createRuntime.
♻️ Duplicate comments (4)
packages/2-sql/3-tooling/family/README.md (1)
120-130: Document runtime wiring dependencies explicitly.The entrypoint now directs users to
@prisma-next/core-execution-plane/stackand@prisma-next/sql-runtime, but the Dependencies section doesn’t list them. Please add both to keep README dependency docs accurate.📝 Proposed doc update
## Dependencies - **`@prisma-next/core-control-plane`**: Control plane types (`ControlFamilyDescriptor`, `ControlTargetDescriptor`, `ControlAdapterDescriptor`, `ControlDriverDescriptor`, `ControlExtensionDescriptor`, `ControlDriverInstance`, etc.) +- **`@prisma-next/core-execution-plane`**: Execution stack descriptor/instance factories (`createExecutionStack`, `instantiateExecutionStack`) - **`@prisma-next/sql-contract-emitter`**: SQL target family hook (`sqlTargetFamilyHook`) - **`@prisma-next/sql-contract-ts`**: Contract validation (`validateContract`) - **`@prisma-next/sql-contract`**: SQL contract types (`SqlContract`, `SqlStorage`) - **`@prisma-next/sql-operations`**: SQL operation signature types (`SqlOperationSignature`) +- **`@prisma-next/sql-runtime`**: Runtime/context factories (`createExecutionContext`, `createRuntime`)examples/prisma-next-demo/src/entry.ts (2)
20-38: Use the canonicalContractIRimport to avoid type drift.Consider replacing the local alias with the canonical type from
@prisma-next/contract/irand keep a demo-specific alias if needed.♻️ Proposed refactor
-import type { ModelDefinition, SqlContract, SqlStorage } from '@prisma-next/sql-contract/types'; +import type { ModelDefinition, SqlStorage } from '@prisma-next/sql-contract/types'; +import type { ContractIR } from '@prisma-next/contract/ir'; -// Temporary demo-only shim... -type ContractIR = SqlContract<SqlStorage, Record<string, ModelDefinition>> & { - target: string; - relations: Record<string, Record<string, Relation>>; - capabilities: Record<string, Record<string, boolean>>; - extensionPacks: Record<string, unknown>; -}; +type ContractIRDemo = ContractIR< + SqlStorage, + Record<string, ModelDefinition>, + Record<string, Record<string, Relation>> +>;
157-166: Avoid the blindas unknown as ContractIRcasts.Prefer a lightweight type guard or validator before calling
renderContract, and render an error state if validation fails.packages/2-sql/5-runtime/test/execution-stack.test.ts (1)
110-124: Use double-cast for the mock driver instance.
Direct casting of mocks should go throughunknownin tests. As per coding guidelines, prefer double-casts for mocks.♻️ Suggested change
- return Object.assign( - { - familyId: 'sql' as const, - targetId: 'postgres' as const, - }, - driver, - ) as SqlRuntimeDriverInstance<'postgres'>; + return Object.assign( + { + familyId: 'sql' as const, + targetId: 'postgres' as const, + }, + driver, + ) as unknown as SqlRuntimeDriverInstance<'postgres'>;
| **✅ CORRECT: Pass context to schema** | ||
|
|
||
| ```typescript | ||
| // Don't do this - codecTypes is not a runtime parameter | ||
| const tables = schema(contract, codecTypes, context).tables; | ||
| const tables = schema(context).tables; | ||
| ``` | ||
|
|
||
| **Removed `makeT()`**: Use `schema().tables` instead. The `makeT()` function was redundant. | ||
|
|
||
| ### Key Points |
There was a problem hiding this comment.
Fix schema invocation guidance to match context-based pattern.
The section says “Use schema().tables,” but the examples and new pattern require schema(context).tables. This is a doc correctness issue and could mislead users into omitting the context.
💡 Suggested edit
-**Removed `makeT()`**: Use `schema().tables` instead. The `makeT()` function was redundant.
+**Removed `makeT()`**: Use `schema(context).tables` instead. The `makeT()` function was redundant.🤖 Prompt for AI Agents
In `@docs/reference/typescript-patterns.md` around lines 1391 - 1399, Update the
guidance to consistently demonstrate passing context into the schema function:
replace the incorrect sentence "Use `schema().tables` instead" with "Use
`schema(context).tables` instead", and ensure the example and explanation
reference `schema(context)` (and not `schema()`); also remove or rephrase the
note about `makeT()` so it clarifies that `makeT()` was removed in favor of
calling `schema(context)` and that `tables` should be accessed via
`schema(context).tables`.
| // Re-export SQL runtime instance types from canonical source | ||
| export type { SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance } from '@prisma-next/sql-runtime'; |
There was a problem hiding this comment.
Layering violation: runtime import in src/core
src/core/** must stay free of runtime-plane dependencies; re-exporting from @prisma-next/sql-runtime breaks the layering rule. Move this re-export to the runtime entrypoint (src/exports/runtime.ts) or another runtime-plane module.
🐛 Proposed fix (remove runtime re-export from core)
-// Re-export SQL runtime instance types from canonical source
-export type { SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance } from '@prisma-next/sql-runtime';As per coding guidelines, keep src/core/** free of runtime-plane imports.
🤖 Prompt for AI Agents
In `@packages/2-sql/3-tooling/family/src/core/runtime-instance.ts` around lines 3
- 4, Remove the runtime-plane re-export from the core layer: delete the export
of SqlRuntimeAdapterInstance and SqlRuntimeDriverInstance that imports from
'@prisma-next/sql-runtime' in the core module, and instead add that exact
re-export into the runtime-plane exports module (the runtime entrypoint) so the
core stays free of runtime dependencies; ensure the symbols
SqlRuntimeAdapterInstance and SqlRuntimeDriverInstance are re-exported from the
runtime entrypoint and no imports from '@prisma-next/sql-runtime' remain in
src/core.
Rename control-plane core files to `control-*` and add execution-plane naming notes referencing TML-1842.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/reference/typescript-patterns.md (1)
424-424: Update example to match currentcreateRuntimeAPI signature.Line 424 shows the outdated API with
adapterparameter. The current signature usesstackInstanceinstead:createRuntime({ stackInstance, contract, context, driverOptions, verify }). Update this example to reflect the correct pattern.
- Rename test to reflect offline mode creation rather than driver behavior - Fix driverOptions shape to use nested connect pattern in docs - Fix architecture diagram to show Runtime from StackInstance not Stack
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@examples/prisma-next-demo/README.md`:
- Around line 111-116: Update the “Key Files” list so the listed no-emit file
paths match the actual directory structure used in the “Workflows” section:
replace entries referencing src/prisma-no-emit/* (specifically
src/prisma-no-emit/query-no-emit.ts and src/prisma-no-emit/runtime-no-emit.ts)
with the corresponding src/prisma/* no-emit paths (matching
src/prisma/execution-context.ts, src/prisma/query.ts, src/prisma/runtime.ts) or
vice versa so both sections use the same directory layout; edit the README.md
lines that enumerate those filenames to ensure consistency and accurate
filenames.
In `@packages/2-sql/5-runtime/test/sql-runtime.test.ts`:
- Around line 134-139: The test mock in the create() method currently casts the
merged object directly to SqlRuntimeDriverInstance<'postgres'>; change this to
the double-cast pattern used elsewhere (cast to unknown first, then to
SqlRuntimeDriverInstance<'postgres'>) to satisfy type-checking for the driver
mock. Update the return in the create() function that merges { familyId: 'sql',
targetId: 'postgres' } with driver to use "as unknown as
SqlRuntimeDriverInstance<'postgres'>" so the driver mock is treated consistently
with createTestAdapterDescriptor.
♻️ Duplicate comments (2)
packages/2-sql/5-runtime/test/sql-runtime.test.ts (2)
111-116: Use double-cast pattern for test mocks.Per coding guidelines, test mocks should use
as unknown as Xto keep the unsafe boundary explicit. Line 305 in this file correctly uses this pattern, but lines 115 and 138 use direct casts.♻️ Proposed fix
create() { return Object.assign( { familyId: 'sql' as const, targetId: 'postgres' as const }, adapter, - ) as SqlRuntimeAdapterInstance<'postgres'>; + ) as unknown as SqlRuntimeAdapterInstance<'postgres'>; },
264-269: Apply double-cast pattern.The invalid driver mock should use
as unknown asfor consistency with the pattern used at line 305.♻️ Proposed fix
create() { return { familyId: 'sql' as const, targetId: 'postgres' as const, - } as SqlRuntimeDriverInstance<'postgres'>; + } as unknown as SqlRuntimeDriverInstance<'postgres'>; },
| - `src/prisma/execution-context.ts` - Env-free execution stack/context (emit workflow) | ||
| - `src/prisma/query.ts` - Env-free query roots (emit workflow) | ||
| - `src/prisma-no-emit/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow) | ||
| - `src/prisma/runtime.ts` - Runtime factory (emit workflow) | ||
| - `src/prisma-no-emit/runtime-no-emit.ts` - Runtime factory (no-emit workflow) | ||
| - `src/main.ts` - App entrypoint with arktype config validation (emit workflow) |
There was a problem hiding this comment.
Fix inconsistent no-emit file paths in “Key Files”.
“Workflows” lists no-emit files under src/prisma/*, but “Key Files” lists src/prisma-no-emit/*. This inconsistency will mislead readers and should be aligned with the actual directory structure.
📝 Suggested fix
-- `src/prisma-no-emit/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow)
-- `src/prisma-no-emit/runtime-no-emit.ts` - Runtime factory (no-emit workflow)
+- `src/prisma/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow)
+- `src/prisma/runtime-no-emit.ts` - Runtime factory (no-emit workflow)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| - `src/prisma/execution-context.ts` - Env-free execution stack/context (emit workflow) | |
| - `src/prisma/query.ts` - Env-free query roots (emit workflow) | |
| - `src/prisma-no-emit/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow) | |
| - `src/prisma/runtime.ts` - Runtime factory (emit workflow) | |
| - `src/prisma-no-emit/runtime-no-emit.ts` - Runtime factory (no-emit workflow) | |
| - `src/main.ts` - App entrypoint with arktype config validation (emit workflow) | |
| - `src/prisma/execution-context.ts` - Env-free execution stack/context (emit workflow) | |
| - `src/prisma/query.ts` - Env-free query roots (emit workflow) | |
| - `src/prisma/query-no-emit.ts` - Env-free execution stack/context + query roots (no-emit workflow) | |
| - `src/prisma/runtime.ts` - Runtime factory (emit workflow) | |
| - `src/prisma/runtime-no-emit.ts` - Runtime factory (no-emit workflow) | |
| - `src/main.ts` - App entrypoint with arktype config validation (emit workflow) |
🤖 Prompt for AI Agents
In `@examples/prisma-next-demo/README.md` around lines 111 - 116, Update the “Key
Files” list so the listed no-emit file paths match the actual directory
structure used in the “Workflows” section: replace entries referencing
src/prisma-no-emit/* (specifically src/prisma-no-emit/query-no-emit.ts and
src/prisma-no-emit/runtime-no-emit.ts) with the corresponding src/prisma/*
no-emit paths (matching src/prisma/execution-context.ts, src/prisma/query.ts,
src/prisma/runtime.ts) or vice versa so both sections use the same directory
layout; edit the README.md lines that enumerate those filenames to ensure
consistency and accurate filenames.
| }, | ||
| }); | ||
|
|
||
| const bob = (await runtime.execute(bobPlan).toArray())[0]; |
There was a problem hiding this comment.
In terms of DX, have we already considered something like
const bob = await sql
.whatever()
.build({ params: { ... }})
/* the plan is built and ready to be executed */
.run(runtime)
/* the plan has been run against the database */
.toArray()
/* the stream-first result has been collected into an array */Basically, this chainability would swap out runtime.execute(bobPlan) with bobPlan.run(runtime).
Why do I propose this? Because bobPlan.run(runtime) is easier to discover via Intellisense autocompletion than runtime.execute(bobPlan)
There was a problem hiding this comment.
I think it's a cool idea - it's much more ergonomic to chain run() on the end of the query than runtime.execute(query.build()) - but I don't feel confident enough to commit to (or against) this decision yet
I'd like to leave these details of the DX to you and the team, I'm trying to focus my attention on the framework structures instead
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
examples/prisma-next-demo/test/runtime.integration.test.ts (2)
28-48: Prefer dot-access for tables/columns and extract locals.Bracket access makes column usage noisier and conflicts with the preferred
tables.user.columns.emailpattern. Apply the same pattern across this file. As per coding guidelines, ...♻️ Suggested refactor
- const tables = schema(executionContext).tables; - const userTable = tables['user']!; - const postTable = tables['post']!; + const tables = schema(executionContext).tables; + const userTable = tables.user!; + const postTable = tables.post!; ... - .returning(userTable.columns['id']!) + .returning(userTable.columns.id!)
469-487: Use object matchers for related assertions.Multiple property/type checks can be collapsed into a single
toMatchObjectfor clarity and guideline compliance. As per coding guidelines, ...♻️ Suggested refactor
- expect(rows[0]).toHaveProperty('id'); - expect(rows[0]).toHaveProperty('email'); - expect(rows[0]).toHaveProperty('posts'); - expect(Array.isArray(rows[0]!.posts)).toBe(true); + expect(rows[0]).toMatchObject({ + id: expect.any(Number), + email: expect.any(String), + posts: expect.any(Array), + }); ... - expect(alice!.posts[0]).toHaveProperty('id'); - expect(alice!.posts[0]).toHaveProperty('title'); - expect(alice!.posts[0]).toHaveProperty('createdAt'); - expect(typeof alice!.posts[0]!.id).toBe('number'); - expect(typeof alice!.posts[0]!.title).toBe('string'); + expect(alice!.posts[0]).toMatchObject({ + id: expect.any(Number), + title: expect.any(String), + createdAt: expect.anything(), + });
…context-foundation

Goal / purpose
Introduce the runtime-plane ExecutionStack composition pattern and make ExecutionContext an explicit, lane-friendly “wiring object” built from a stack instance.
This standardizes runtime wiring to:
descriptors → stack → stackInstance → executionContext → runtime
and makes it possible to import/build plans without a DB connection (runtime execution remains optional / configured later).
Linear
Where to start (review order)
Execution stack primitives
packages/1-framework/1-core/runtime/execution-plane/src/stack.tsSQL ExecutionContext construction + contract/stack validation
packages/2-sql/5-runtime/src/sql-context.tsSQL runtime creation and offline behavior
packages/2-sql/5-runtime/src/sql-runtime.tsDemo wiring (concrete usage)
examples/prisma-next-demo/src/prisma/execution-context.tsexamples/prisma-next-demo/src/prisma/runtime.tsWhat changed (high level)
Core execution-plane (
@prisma-next/core-execution-plane)ExecutionStack(descriptors-only) andExecutionStackInstance(instantiated target/adapter/extensions).createExecutionStack()+instantiateExecutionStack()helpers (driver remains a descriptor on the stack).SQL runtime (
@prisma-next/sql-runtime)createExecutionContext({ contract, stackInstance })to build the lane-facing context:contractoperationsregistry (adapter + extensions)codecsregistry (adapter + extensions)typeshelper registry (fromstorage.types+ parameterized codecs)createRuntime()to takeCreateRuntimeOptions:{ stackInstance, contract, context?, driverOptions?, verify, plugins?, ... }driverOptionsisn’t provided, the runtime is still constructible (execution calls error with stable codes).packages/2-sql/5-runtime/README.md).Demo update (prisma-next-demo)
src/prisma/execution-context.ts.src/prisma/runtime.tsprovides driver options (pool/client) only when actually creating the runtime.Notes / follow-ups
createRuntime()today because runtime drivers currently receive connection info at construction time (driverOptions). This is tracked as a follow-up inTML-1837(decouple driver instantiation from connection binding).How to verify
Expected:
Summary by CodeRabbit
New Features
Architecture Updates
Refactor
Documentation
Tests
Chores
✏️ Tip: You can customize this high-level summary in your review settings.