Repository navigation
feat(sql-runtime): derive static ExecutionContext from descriptors only (TML-1827) - #133
Conversation
TML-1827 Runtime DX: derive static SQL ExecutionContext from descriptors
SummaryRefactor SQL runtime-plane composition so a static SQL ExecutionContext (contract + codec registry + operation registry + type helpers) can be created from descriptors only (no adapter/extension instantiation). This unblocks clean demo/app DX: a Links
Scope
Acceptance criteria
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughRefactors the SQL execution plane to derive a static ExecutionContext from descriptor-level static contributions (codecs, operationSignatures, parameterizedCodecs) without instantiating runtime components. Runtime creation now requires an explicit driver and precomputed context; manifest-based operation types and related exports are removed or migrated to descriptor surfaces. Changes
Comment |
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 (3)
packages/2-sql/5-runtime/test/async-iterable-result.test.ts (1)
160-164: 🧹 Nitpick | 🔵 TrivialPrefer assertion over defensive check.
After asserting
rows.lengthis 1,rows[0]is guaranteed to exist. Theif (rows[0])check is unnecessary defensive coding.As per coding guidelines: "Prefer assertions over defensive checks when data is guaranteed to be valid."
♻️ 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(typeof rows[0]!.id).toBe('number'); + expect(typeof rows[0]!.email).toBe('string');examples/prisma-next-demo/test/runtime.integration.test.ts (1)
268-284: 🧹 Nitpick | 🔵 TrivialConsider extracting repeated driver creation pattern.
The driver creation pattern
executionStack.driver!.create({ connect: { pool }, cursor: { disabled: true } })is repeated across multiple test cases. Consider extracting a helper function for readability.♻️ Optional helper extraction
function createTestDriver(pool: Pool) { return executionStack.driver!.create({ connect: { pool }, cursor: { disabled: true }, }); }packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts (1)
503-504: 🛠️ Refactor suggestion | 🟠 MajorSplit this test file; it now exceeds the 500‑line limit.
The file is at ~504 lines; split by concern (e.g., move the vector operation or returning() capability tests into separate
sql-dml.*.test.tsfiles).As per coding guidelines: "**/*.test.ts: Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."
| 4. **Operations representation (remove manifest hangover; keep framework clean)** | ||
| - Remove the obsolete “manifest” representation for operations: | ||
| - strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*` | ||
| - remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components` | ||
| - Keep the framework operation building blocks: | ||
| - `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering). | ||
| - Make family-owned operation definitions the source of truth: | ||
| - SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`. | ||
| - SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`. | ||
| - Contract emission/type generation must continue to work: | ||
| - keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation | ||
| - if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata). | ||
|
|
||
| 4. **Demo refactor** | ||
| - Add `examples/prisma-next-demo/src/prisma/context.ts`: | ||
| - validates/loads contract | ||
| - defines configuration for static context | ||
| - exports query roots (`sql`, `orm`, `schema`, `tables`) | ||
| - exports any helper needed by runtime constructor (e.g., contract, stack descriptors) | ||
| - Update `examples/prisma-next-demo/src/prisma/runtime.ts`: | ||
| - imports from `context.ts` | ||
| - constructs runtime (instantiates adapter/driver as needed) | ||
| - `examples/prisma-next-demo/src/main.ts` continues to: | ||
| - validate env/config (arktype) | ||
| - call runtime constructor | ||
| - close runtime |
There was a problem hiding this comment.
Minor numbering inconsistency.
Section numbering has a duplicate: there are two sections numbered "4" (Operations representation and Demo refactor). The Demo refactor section should be numbered "5".
📝 Suggested fix
-4. **Demo refactor**
+5. **Demo refactor**📝 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.
| 4. **Operations representation (remove manifest hangover; keep framework clean)** | |
| - Remove the obsolete “manifest” representation for operations: | |
| - strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*` | |
| - remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components` | |
| - Keep the framework operation building blocks: | |
| - `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering). | |
| - Make family-owned operation definitions the source of truth: | |
| - SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`. | |
| - SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`. | |
| - Contract emission/type generation must continue to work: | |
| - keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation | |
| - if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata). | |
| 4. **Demo refactor** | |
| - Add `examples/prisma-next-demo/src/prisma/context.ts`: | |
| - validates/loads contract | |
| - defines configuration for static context | |
| - exports query roots (`sql`, `orm`, `schema`, `tables`) | |
| - exports any helper needed by runtime constructor (e.g., contract, stack descriptors) | |
| - Update `examples/prisma-next-demo/src/prisma/runtime.ts`: | |
| - imports from `context.ts` | |
| - constructs runtime (instantiates adapter/driver as needed) | |
| - `examples/prisma-next-demo/src/main.ts` continues to: | |
| - validate env/config (arktype) | |
| - call runtime constructor | |
| - close runtime | |
| 4. **Operations representation (remove manifest hangover; keep framework clean)** | |
| - Remove the obsolete "manifest" representation for operations: | |
| - strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*` | |
| - remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components` | |
| - Keep the framework operation building blocks: | |
| - `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering). | |
| - Make family-owned operation definitions the source of truth: | |
| - SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`. | |
| - SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`. | |
| - Contract emission/type generation must continue to work: | |
| - keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation | |
| - if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata). | |
| 5. **Demo refactor** | |
| - Add `examples/prisma-next-demo/src/prisma/context.ts`: | |
| - validates/loads contract | |
| - defines configuration for static context | |
| - exports query roots (`sql`, `orm`, `schema`, `tables`) | |
| - exports any helper needed by runtime constructor (e.g., contract, stack descriptors) | |
| - Update `examples/prisma-next-demo/src/prisma/runtime.ts`: | |
| - imports from `context.ts` | |
| - constructs runtime (instantiates adapter/driver as needed) | |
| - `examples/prisma-next-demo/src/main.ts` continues to: | |
| - validate env/config (arktype) | |
| - call runtime constructor | |
| - close runtime |
| // | ||
| // Assert that the stack's descriptors implement SqlControlStaticContributions. | ||
| // This is a runtime contract: SQL descriptors must provide operationSignatures(). | ||
| const target = stack.target as unknown as SqlControlDescriptorWithContributions; | ||
| const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>; | ||
| const extensionPacks = | ||
| stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[]; | ||
| return createSqlFamilyInstance({ | ||
| target: stack.target, | ||
| adapter: stack.adapter, | ||
| extensionPacks: stack.extensionPacks, | ||
| target, | ||
| adapter, | ||
| extensionPacks, | ||
| }); |
There was a problem hiding this comment.
Replace blind casts with runtime validation.
The as unknown as casts at lines 39-42 violate coding guidelines for production code. Since this is a "runtime contract" as the comment states, add runtime validation to ensure descriptors implement the required interface before use.
Consider adding a type guard or validation function:
🛡️ Proposed fix with runtime validation
+function assertSqlStaticContributions(
+ descriptor: unknown,
+ name: string,
+): asserts descriptor is SqlControlDescriptorWithContributions {
+ if (
+ typeof descriptor !== 'object' ||
+ descriptor === null ||
+ typeof (descriptor as SqlControlDescriptorWithContributions).operationSignatures !== 'function'
+ ) {
+ throw new Error(
+ `${name} descriptor must implement SqlControlStaticContributions (missing operationSignatures())`,
+ );
+ }
+}
create<TTargetId extends string>(
stack: ControlPlaneStack<'sql', TTargetId>,
): SqlControlFamilyInstance {
- //
- // Assert that the stack's descriptors implement SqlControlStaticContributions.
- // This is a runtime contract: SQL descriptors must provide operationSignatures().
- const target = stack.target as unknown as SqlControlDescriptorWithContributions;
- const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>;
- const extensionPacks =
- stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[];
+ // Validate that the stack's descriptors implement SqlControlStaticContributions.
+ assertSqlStaticContributions(stack.target, 'target');
+ assertSqlStaticContributions(stack.adapter, 'adapter');
+ for (const ext of stack.extensionPacks) {
+ assertSqlStaticContributions(ext, `extension ${ext.id}`);
+ }
+ const target = stack.target as SqlControlDescriptorWithContributions;
+ const adapter = stack.adapter as SqlControlAdapterDescriptor<TTargetId>;
+ const extensionPacks = stack.extensionPacks as readonly SqlControlExtensionDescriptor<TTargetId>[];
return createSqlFamilyInstance({
target,
adapter,
extensionPacks,
});
}As per coding guidelines: "Avoid blind casts like as unknown as X in production TypeScript code. Use type predicates (value is X) or type guards instead to let the compiler narrow types safely."
📝 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.
| // | |
| // Assert that the stack's descriptors implement SqlControlStaticContributions. | |
| // This is a runtime contract: SQL descriptors must provide operationSignatures(). | |
| const target = stack.target as unknown as SqlControlDescriptorWithContributions; | |
| const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>; | |
| const extensionPacks = | |
| stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[]; | |
| return createSqlFamilyInstance({ | |
| target: stack.target, | |
| adapter: stack.adapter, | |
| extensionPacks: stack.extensionPacks, | |
| target, | |
| adapter, | |
| extensionPacks, | |
| }); | |
| function assertSqlStaticContributions( | |
| descriptor: unknown, | |
| name: string, | |
| ): asserts descriptor is SqlControlDescriptorWithContributions { | |
| if ( | |
| typeof descriptor !== 'object' || | |
| descriptor === null || | |
| typeof (descriptor as SqlControlDescriptorWithContributions).operationSignatures !== 'function' | |
| ) { | |
| throw new Error( | |
| `${name} descriptor must implement SqlControlStaticContributions (missing operationSignatures())`, | |
| ); | |
| } | |
| } | |
| create<TTargetId extends string>( | |
| stack: ControlPlaneStack<'sql', TTargetId>, | |
| ): SqlControlFamilyInstance { | |
| // Validate that the stack's descriptors implement SqlControlStaticContributions. | |
| assertSqlStaticContributions(stack.target, 'target'); | |
| assertSqlStaticContributions(stack.adapter, 'adapter'); | |
| for (const ext of stack.extensionPacks) { | |
| assertSqlStaticContributions(ext, `extension ${ext.id}`); | |
| } | |
| const target = stack.target as SqlControlDescriptorWithContributions; | |
| const adapter = stack.adapter as SqlControlAdapterDescriptor<TTargetId>; | |
| const extensionPacks = stack.extensionPacks as readonly SqlControlExtensionDescriptor<TTargetId>[]; | |
| return createSqlFamilyInstance({ | |
| target, | |
| adapter, | |
| extensionPacks, | |
| }); | |
| } |
| template: '${self} <=> ${arg0}', | ||
| }, | ||
| }; | ||
| const mockVectorExtensionDescriptor: import('@prisma-next/sql-runtime').SqlRuntimeExtensionDescriptor<'postgres'> = |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, check if the file exists and read around line 327
wc -l packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.tsRepository: prisma/prisma-next
Length of output: 118
🏁 Script executed:
# Read the specific area around line 327
sed -n '320,335p' packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts | cat -nRepository: prisma/prisma-next
Length of output: 812
🏁 Script executed:
# Check the top-level imports in the file
head -50 packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts | cat -nRepository: prisma/prisma-next
Length of output: 2204
Replace the inline type import with a top-level import type statement.
Inline type imports are disallowed; move SqlRuntimeExtensionDescriptor to a named type import at the top of the file alongside other imports from @prisma-next/sql-runtime.
🔧 Proposed change
import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
+import type { SqlRuntimeExtensionDescriptor } from '@prisma-next/sql-runtime';
import { validateContract } from '@prisma-next/sql-contract-ts/contract';
@@
- const mockVectorExtensionDescriptor: import('@prisma-next/sql-runtime').SqlRuntimeExtensionDescriptor<'postgres'> =
+ const mockVectorExtensionDescriptor: SqlRuntimeExtensionDescriptor<'postgres'> =There was a problem hiding this comment.
See if there's a mermaid skill available we can use!
| target: { | ||
| kind: 'target', | ||
| id: 'postgres', | ||
| version: '0.0.1', | ||
| familyId: 'sql' as const, | ||
| targetId: 'postgres' as const, | ||
| codecs: () => createCodecRegistry(), | ||
| operationSignatures: () => [], | ||
| parameterizedCodecs: () => [], | ||
| create() { | ||
| return { familyId: 'sql' as const, targetId: 'postgres' as const }; | ||
| }, |
There was a problem hiding this comment.
We can probably DRY up these mock framework component structures, perhaps in test/utils
44113e0 to
cabf9e5
Compare
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 (5)
packages/3-extensions/pgvector/test/manifest.test.ts (1)
32-47:⚠️ Potential issue | 🟡 MinorConsolidate related assertions with an object matcher.
Use a singletoMatchObjectfor the cosineDistance operation instead of multiple property assertions.As per coding guidelines, "Prefer object comparison using `toEqual` or `toMatchObject` for assertions on objects, rather than property-by-property checks with `toHaveProperty` or individual property assertions."♻️ Suggested refactor
- expect(cosineDistanceOp).toBeDefined(); - expect(cosineDistanceOp?.args).toEqual([{ kind: 'param' }]); - expect(cosineDistanceOp?.returns).toEqual({ kind: 'builtin', type: 'number' }); - expect(cosineDistanceOp?.lowering).toEqual({ - targetFamily: 'sql', - strategy: 'function', - template: '1 - ({{self}} <=> {{arg0}})', - }); + expect(cosineDistanceOp).toMatchObject({ + args: [{ kind: 'param' }], + returns: { kind: 'builtin', type: 'number' }, + lowering: { + targetFamily: 'sql', + strategy: 'function', + template: '1 - ({{self}} <=> {{arg0}})', + }, + });packages/2-sql/3-tooling/family/test/emit-parameterized.test.ts (2)
70-77: 🛠️ Refactor suggestion | 🟠 MajorUse
ifDefined()for conditional spreads.Inline conditional spread for
typesImportshould use the shared helper for consistency.As per coding guidelines, Use `ifDefined()` from `@prisma-next/utils/defined` for conditional object spreads instead of inline conditional spread patterns.♻️ Suggested change
+import { ifDefined } from '@prisma-next/utils/defined'; ... - ...(config.typesImport ? { typeImports: [config.typesImport] } : {}), + ...ifDefined(config.typesImport, (typesImport) => ({ + typeImports: [typesImport], + })),
116-133: 🛠️ Refactor suggestion | 🟠 MajorPrefer
createContractIR()factory for ContractIR test data.Manual ContractIR construction is discouraged; using the factory avoids drift and keeps defaults consistent. As per coding guidelines, Use factory functions like
createContractIR()instead of manual object creation for ContractIR objects in tests to avoid duplication, ensure all required fields are present with proper defaults, and simplify refactoring.packages/2-sql/5-runtime/test/parameterized-types.test.ts (1)
16-51: 🛠️ Refactor suggestion | 🟠 MajorReplace conditional spreads with
ifDefined()in test helpers.Use the shared helper for the optional
typesandinitspreads to match repo conventions.As per coding guidelines, Use `ifDefined()` from `@prisma-next/utils/defined` for conditional object spreads instead of inline conditional spread patterns.♻️ Suggested change
+import { ifDefined } from '@prisma-next/utils/defined'; ... - ...(options?.types ? { types: options.types } : {}), + ...ifDefined(options?.types, (types) => ({ types })), ... - ...(options?.init ? { init: options.init } : {}), + ...ifDefined(options?.init, (init) => ({ init })),Also applies to: 106-116
packages/2-sql/5-runtime/test/sql-runtime.test.ts (1)
160-190: 🧹 Nitpick | 🔵 TrivialPrefer object matchers for related assertions in these tests.
Multiple related
toBeDefined()checks can be collapsed into a singletoMatchObjectfor clarity.✅ 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), + }); - const ops = runtime.operations(); - expect(ops).toBeDefined(); - expect(ops.byType).toBeDefined(); + const ops = runtime.operations(); + expect(ops).toMatchObject({ + byType: expect.any(Function), + });As per coding guidelines: “Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests.”
…r-level static contributions Introduce SqlStaticContributions interface that defines required methods for SQL runtime-plane descriptors to contribute codecs, operations, and parameterized codec descriptors to ExecutionContext. Add SQL-specific descriptor types that extend core execution-plane types: - SqlRuntimeTargetDescriptor - SqlRuntimeAdapterDescriptor - SqlRuntimeExtensionDescriptor These types require descriptors to implement static contribution methods: - codecs(): returns CodecRegistry - operationSignatures(): returns SqlOperationSignature[] (renamed from operations() to avoid conflict with ComponentMetadata.operations) - parameterizedCodecs(): returns RuntimeParameterizedCodecDescriptor[] This enables static context creation without instantiating runtime components.
…y static contributions Update postgres runtime target descriptor to implement the new SqlRuntimeTargetDescriptor interface with required static contribution methods. The target provides empty contributions since codecs and operations are contributed by the adapter and extensions: - codecs(): returns empty CodecRegistry - operationSignatures(): returns empty array - parameterizedCodecs(): returns empty array Add sql-relational-core and sql-runtime dependencies to package.json.
…atic codec contributions Update postgres runtime adapter descriptor to implement the new SqlRuntimeAdapterDescriptor interface with required static contribution methods. The adapter contributes codecs for all native postgres types: - codecs(): creates registry from codecDefinitions (pg/text@1, pg/int4@1, etc.) - operationSignatures(): returns empty array (adapter has no operations) - parameterizedCodecs(): returns empty array (adapter has no parameterized codecs) Extract createPostgresCodecRegistry helper to share codec registry creation logic between static contributions and adapter instance. Add sql-runtime dependency to package.json.
…descriptor Update pgvector runtime extension descriptor to implement SqlRuntimeExtensionDescriptor with static contributions on the descriptor rather than instance methods. The descriptor now provides: - codecs(): pg/vector@1 codec for vector type - operationSignatures(): cosineDistance operation for similarity search - parameterizedCodecs(): vector params schema with length validation The instance is now minimal (identity properties only) since no runtime hooks require instance-level behavior. Update tests to verify descriptor static contributions instead of instance methods.
The framework contract should not define operation manifest types. Operations are family-owned concerns (e.g. SQL family defines SqlOperationSignature). - Remove ArgSpecManifest, ReturnSpecManifest, LoweringSpecManifest, OperationManifest - Remove ComponentMetadata.operations property - Delete pack-manifest-types.ts export entrypoint This is the first step of operations layering - moving operation definitions from framework to family-specific descriptor surfaces.
Define operationSignatures() method on SQL control plane descriptors. This is the family-owned API for declaring operation signatures at control plane initialization, replacing the generic OperationManifest. - Add SqlControlStaticContributions interface with operationSignatures() - Update SqlControlTargetDescriptor to extend SqlControlStaticContributions - Update SqlControlAdapterDescriptor to extend SqlControlStaticContributions - Update SqlControlExtensionDescriptor to extend SqlControlStaticContributions - Export SqlControlDescriptorWithContributions from control.ts
The operation registry is now assembled by calling operationSignatures() on each SQL descriptor, rather than converting OperationManifest. - Remove convertOperationManifest from assembly and test-utils exports - Update assembleOperationRegistry to take SqlControlDescriptorWithContributions - Call descriptor.operationSignatures() and register each signature - Cast generic ControlPlaneStack types to SQL-specific types at family boundary - Simplify collectSupportedCodecTypeIds to accept minimal descriptor shape
Move operation definition from pack metadata to descriptor method. The operation signature is now returned by operationSignatures() on both control and runtime descriptors. - Remove operations array from pgvectorPackMeta - Add pgvectorOperationSignature as canonical SqlOperationSignature - Implement operationSignatures() on control descriptor - Update runtime descriptor to use pgvectorOperationSignature
Postgres target and adapter now implement SqlControlStaticContributions. They return empty arrays since they do not contribute operations. - Update postgres target descriptor with operationSignatures: () => [] - Update postgres adapter descriptor with operationSignatures: () => [] - Use SQL-specific descriptor types for better type safety
Test mocks and fixtures now implement SqlControlStaticContributions. Remove convertOperationManifest usage from all integration tests. - Add operationSignatures() to mock descriptors in family-sql tests - Update sql-lane mock extension descriptor with codecs() and operationSignatures() - Provide operations() on mock instance (required by createExecutionContext) - Update pgvector manifest test to use operationSignatures() - Update postgres planner tests with operationSignatures() - Remove convertOperationManifest from integration test imports - Update integration utils to use SQL-specific descriptor types
Change the signature from { contract, stackInstance } to
{ contract, stack } where stack is a SqlExecutionStack containing
SQL descriptors with required static contributions (codecs,
operationSignatures, parameterizedCodecs).
This enables static ExecutionContext creation without instantiating
adapter/extension instances, since all contributions are read
directly from descriptor methods.
Merge order is deterministic: target -> adapter -> extensionPacks.
Parameterized codec collection also follows this order across all
contributors, not just extensions.
Replace { contract, stackInstance } with { contract, stack } at every
createExecutionContext call site. Context is now derived from
descriptor static contributions, removing the need to instantiate
the execution stack just to build query roots.
Remove all internal plumbing from createRuntime: - context is now required (no fallback derivation) - driver is an explicit SqlDriver (no driverOptions/descriptor instantiation) - Remove offline driver defaulting - Remove driver type validation (isSqlDriver) - Remove contract/stack assertion (already done in createExecutionContext) Callers are now responsible for constructing the ExecutionContext (via createExecutionContext) and the SqlDriver before calling createRuntime. This eliminates the unsafe SqlExecutionStack cast and clarifies the boundary between static setup and runtime wiring.
- Add missing RuntimeDriverInstance import in sql-context.ts - Update schema-view test mocks to implement SqlControlStaticContributions Both issues existed before Section 4 changes and were exposed by the full build and test suite.
…ntime Callers now construct drivers explicitly via descriptor.create() instead of passing driverOptions. The contract parameter is removed since it lives in context. The offline integration test is simplified to test query plan building without a runtime, since static query building no longer requires runtime construction.
…onStack directly createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor (et al.) to RuntimeTargetDescriptor, losing SqlStaticContributions. Instead of casting the result, construct SqlExecutionStack inline from the concrete descriptor imports which preserve their SQL-specific types.
The casts work around createExecutionStack broadening SQL-specific descriptor types to their generic base types. Comments explain this is a type inference limitation, not a missing property (driver is not the issue).
parsePostgresArray previously split naively on commas, which would misparse enum labels containing commas, double quotes, or backslashes. Implement proper PostgreSQL array quoting rules where quoted elements use \" and \\ escape sequences. Add test coverage for these edge cases.
6ec9f81 to
7c99a81
Compare
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/3-extensions/pgvector/test/operations.test.ts (1)
24-39: 🧹 Nitpick | 🔵 TrivialPrefer object matchers for related field checks.
Consolidate property assertions intotoMatchObjectto align with test conventions.♻️ Suggested refactor
- const cosineDistanceOp = operations[0]; - expect(cosineDistanceOp).toBeDefined(); - expect(cosineDistanceOp?.forTypeId).toBe('pg/vector@1'); - expect(cosineDistanceOp?.method).toBe('cosineDistance'); - expect(cosineDistanceOp?.args).toEqual([{ kind: 'param' }]); - expect(cosineDistanceOp?.returns).toEqual({ kind: 'builtin', type: 'number' }); - expect(cosineDistanceOp?.lowering).toEqual({ - targetFamily: 'sql', - strategy: 'function', - template: '1 - ({{self}} <=> {{arg0}})', - }); + const cosineDistanceOp = operations[0]; + expect(cosineDistanceOp).toMatchObject({ + forTypeId: 'pg/vector@1', + method: 'cosineDistance', + args: [{ kind: 'param' }], + returns: { kind: 'builtin', type: 'number' }, + lowering: { + targetFamily: 'sql', + strategy: 'function', + template: '1 - ({{self}} <=> {{arg0}})', + }, + }); @@ - const instance = pgvectorDescriptor.create(); - expect(instance.familyId).toBe('sql'); - expect(instance.targetId).toBe('postgres'); + const instance = pgvectorDescriptor.create(); + expect(instance).toMatchObject({ familyId: 'sql', targetId: 'postgres' });As per coding guidelines,
**/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests.Also applies to: 70-74
packages/2-sql/5-runtime/src/sql-context.ts (1)
231-237: 🧹 Nitpick | 🔵 TrivialConsider removing the generic default for
TContract.The default
TContract extends SqlContract<SqlStorage> = SqlContract<SqlStorage>may cause type inference issues downstream. As per coding guidelines: "Using a generic type causes all subsequent type inference to fail, resulting inunknowntypes throughout the code."Callers should always provide a fully-typed contract type for proper type inference in the returned
ExecutionContext<TContract>.♻️ Suggested change
export function createExecutionContext< - TContract extends SqlContract<SqlStorage> = SqlContract<SqlStorage>, + TContract extends SqlContract<SqlStorage>, TTargetId extends string = string, >(options: {
| export const executionStackInstance = instantiateExecutionStack(executionStack); | ||
| export const executionContext = createExecutionContext({ | ||
| contract, | ||
| stackInstance: executionStackInstance, | ||
| stack: executionStack as never, | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.tsRepository: prisma/prisma-next
Length of output: 1641
🏁 Script executed:
rg -n -B5 -A10 'createExecutionContext' examples/prisma-next-demo/src/prisma-no-emit/ --type tsRepository: prisma/prisma-next
Length of output: 3048
🏁 Script executed:
rg -n -A5 'createExecutionContext\(' --type=tsRepository: prisma/prisma-next
Length of output: 9880
🏁 Script executed:
cat -n examples/prisma-next-demo/src/prisma/context.ts | head -35Repository: prisma/prisma-next
Length of output: 1956
🏁 Script executed:
rg -B3 -A3 'as never' examples/prisma-next-demo/src/prisma examples/prisma-orm-demo/src --type ts | head -40Repository: prisma/prisma-next
Length of output: 1267
Add explanatory comment for the as never cast and remove unused executionStackInstance.
The as never cast on line 25 is necessary due to generic type inference, not a blind cast. Add the explanatory comment from context.ts to document why the cast is needed. Additionally, executionStackInstance (line 22) is exported but never used and should be removed.
| import { executionContext, executionStack, executionStackInstance } from './query-no-emit'; | ||
|
|
||
| export function getRuntime(databaseUrl: string): Runtime { | ||
| const pool = new Pool({ connectionString: databaseUrl }); | ||
|
|
||
| const driverDescriptor = executionStack.driver; | ||
| if (!driverDescriptor) { | ||
| throw new Error('Driver descriptor missing from execution stack'); | ||
| } | ||
|
|
||
| return createRuntime({ | ||
| stackInstance: executionStackInstance, | ||
| contract: executionContext.contract, | ||
| context: executionContext, | ||
| driverOptions: { | ||
| driver: driverDescriptor.create({ | ||
| connect: { pool }, | ||
| cursor: { disabled: true }, | ||
| }, | ||
| }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -type f -name "query-no-emit.ts" | head -5Repository: prisma/prisma-next
Length of output: 125
🏁 Script executed:
fd "runtime-no-emit" -t fRepository: prisma/prisma-next
Length of output: 125
🏁 Script executed:
fd "query-no-emit" -t fRepository: prisma/prisma-next
Length of output: 123
🏁 Script executed:
cat -n examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.tsRepository: prisma/prisma-next
Length of output: 1641
🏁 Script executed:
cat -n examples/prisma-next-demo/src/prisma-no-emit/runtime-no-emit.tsRepository: prisma/prisma-next
Length of output: 1240
🏁 Script executed:
rg "instantiateExecutionStack" --type ts -B 2 -A 2 | head -30Repository: prisma/prisma-next
Length of output: 1772
🏁 Script executed:
sed -n '1,50p' packages/2-sql/5-runtime/test/utils.tsRepository: prisma/prisma-next
Length of output: 2041
Avoid import-time stack instantiation in the no-emit runtime.
executionStackInstance is instantiated at module load in examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts, so importing it here reintroduces side effects that the descriptor-based approach is trying to avoid. Instantiate the stack inside getRuntime and pass that instance to createRuntime instead.
Suggested change
-import { executionContext, executionStack, executionStackInstance } from './query-no-emit';
+import { instantiateExecutionStack } from '@prisma-next/core-execution-plane/stack';
+import { executionContext, executionStack } from './query-no-emit';
export function getRuntime(databaseUrl: string): Runtime {
const pool = new Pool({ connectionString: databaseUrl });
+ const stackInstance = instantiateExecutionStack(executionStack);
const driverDescriptor = executionStack.driver;
if (!driverDescriptor) {
throw new Error('Driver descriptor missing from execution stack');
}
return createRuntime({
- stackInstance: executionStackInstance,
+ stackInstance,
context: executionContext,
driver: driverDescriptor.create({
connect: { pool },
cursor: { disabled: true },
}),| // Cast needed: createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor | ||
| // (et al.) to RuntimeTargetDescriptor, losing the SqlStaticContributions interface that | ||
| // createExecutionContext requires. The concrete descriptors above do satisfy SqlExecutionStack. | ||
| export const executionContext = createExecutionContext({ | ||
| contract, | ||
| stackInstance: executionStackInstance, | ||
| stack: executionStack as never, | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -type f -name "context.ts" | grep "prisma-next-demo"Repository: prisma/prisma-next
Length of output: 111
🏁 Script executed:
cat -n examples/prisma-next-demo/src/prisma/context.tsRepository: prisma/prisma-next
Length of output: 1956
🏁 Script executed:
# Find SqlExecutionStack type definition
rg "type SqlExecutionStack|interface SqlExecutionStack" --type tsRepository: prisma/prisma-next
Length of output: 253
🏁 Script executed:
# Check imports in the context.ts file to understand what's available
head -30 examples/prisma-next-demo/src/prisma/context.tsRepository: prisma/prisma-next
Length of output: 1502
🏁 Script executed:
# Check the SqlExecutionStack definition
sed -n '1,50p' packages/2-sql/5-runtime/src/sql-context.tsRepository: prisma/prisma-next
Length of output: 1920
🏁 Script executed:
# Check createExecutionContext signature
rg "export (function|const) createExecutionContext" packages/2-sql/5-runtime/src -A 10Repository: prisma/prisma-next
Length of output: 922
🏁 Script executed:
# Check if SqlExecutionStack is exported from `@prisma-next/sql-runtime`
rg "SqlExecutionStack" packages/2-sql/5-runtime/src/index.ts packages/2-sql/5-runtime/src/exports.ts 2>/dev/null || echo "Checking package exports..."Repository: prisma/prisma-next
Length of output: 89
🏁 Script executed:
# Find the main export file for sql-runtime
find packages/2-sql/5-runtime -name "index.ts" -o -name "exports.ts" -o -name "package.json" | head -5Repository: prisma/prisma-next
Length of output: 145
🏁 Script executed:
# Check the exports file
cat packages/2-sql/5-runtime/src/exports/index.tsRepository: prisma/prisma-next
Length of output: 1223
🏁 Script executed:
# Also check if there's a main index.ts
cat packages/2-sql/5-runtime/src/index.ts 2>/dev/null || echo "No main index.ts"Repository: prisma/prisma-next
Length of output: 78
🏁 Script executed:
# Check the complete SqlExecutionStack definition
sed -n '/^export interface SqlExecutionStack/,/^}/p' packages/2-sql/5-runtime/src/sql-context.tsRepository: prisma/prisma-next
Length of output: 333
🏁 Script executed:
# Check assertExecutionStackContractRequirements to understand what it validates
rg "function assertExecutionStackContractRequirements" packages/2-sql/5-runtime/src -A 15Repository: prisma/prisma-next
Length of output: 1227
Replace the as never cast with explicit SqlExecutionStack typing.
The cast bypasses type checking. Add an explicit type annotation to executionStack using SqlExecutionStack from @prisma-next/sql-runtime. This lets TypeScript validate the return type of createExecutionStack() against the expected interface and eliminates the need for the workaround cast and comment.
♻️ Suggested refactor
import { createExecutionStack } from '@prisma-next/core-execution-plane/stack';
+import type { SqlExecutionStack } from '@prisma-next/sql-runtime';
import postgresDriver from '@prisma-next/driver-postgres/runtime';
import pgvectorDescriptor from '@prisma-next/extension-pgvector/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 './contract.d';
import contractJson from './contract.json' with { type: 'json' };
const contract = validateContract<Contract>(contractJson);
-export const executionStack = createExecutionStack({
+export const executionStack: SqlExecutionStack = createExecutionStack({
target: postgresTarget,
adapter: postgresAdapter,
driver: postgresDriver,
extensionPacks: [pgvectorDescriptor],
});
-
-// Cast needed: createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor
-// (et al.) to RuntimeTargetDescriptor, losing the SqlStaticContributions interface that
-// createExecutionContext requires. The concrete descriptors above do satisfy SqlExecutionStack.
export const executionContext = createExecutionContext({
contract,
- stack: executionStack as never,
+ stack: executionStack,
});| import { describe, expect, it, vi } from 'vitest'; | ||
| import { executionStack, sql, tables } from '../src/prisma/context'; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for mock restoration patterns in the codebase
echo "=== Searching for mock restoration patterns ==="
rg -n "restoreAllMocks|clearAllMocks" -g "*.{ts,js,cts,mts}" --max-count=20
echo -e "\n=== Checking vitest configuration ==="
find . -name "vitest.config.*" -type f 2>/dev/null
echo -e "\n=== Checking test setup files ==="
rg -n "setupFiles|setupFilesAfterEnv|vitest\.setup" -g "vitest.config.*" -A 3Repository: prisma/prisma-next
Length of output: 2215
🏁 Script executed:
#!/bin/bash
# Examine the specific test file to see if it uses spies
echo "=== Examining the test file ==="
cat -n examples/prisma-next-demo/test/runtime.offline.integration.test.ts | head -50Repository: prisma/prisma-next
Length of output: 1614
🏁 Script executed:
#!/bin/bash
# Check if there's a global vitest setup file
echo "=== Looking for vitest setup or config in examples/prisma-next-demo ==="
find examples/prisma-next-demo -name "vitest.config.*" -o -name "*.setup.*" -o -name "vitest.*.ts" 2>/dev/null | head -20Repository: prisma/prisma-next
Length of output: 176
🏁 Script executed:
#!/bin/bash
# Search for any vi.spyOn usage in the specific test file
echo "=== Checking for spy usage in the test file ==="
rg -n "vi\.spy|spyOn" examples/prisma-next-demo/test/runtime.offline.integration.test.tsRepository: prisma/prisma-next
Length of output: 346
🏁 Script executed:
#!/bin/bash
# Examine the vitest config for examples/prisma-next-demo
echo "=== Vitest config for examples/prisma-next-demo ==="
cat -n examples/prisma-next-demo/vitest.config.tsRepository: prisma/prisma-next
Length of output: 507
🏁 Script executed:
#!/bin/bash
# Check if there's a shared vitest config at the root
echo "=== Root vitest.config.ts if it exists ==="
if [ -f ./vitest.config.ts ]; then
cat -n ./vitest.config.ts
fi
echo -e "\n=== Check vitest.workspace.ts ==="
if [ -f ./vitest.workspace.ts ]; then
cat -n ./vitest.workspace.ts | head -50
fiRepository: prisma/prisma-next
Length of output: 139
🏁 Script executed:
#!/bin/bash
# Check the test file for any existing afterEach hooks
echo "=== Full test file to check for afterEach ==="
wc -l examples/prisma-next-demo/test/runtime.offline.integration.test.ts
cat -n examples/prisma-next-demo/test/runtime.offline.integration.test.tsRepository: prisma/prisma-next
Length of output: 1698
Add mock restoration to prevent spy leakage across tests.
The test file creates spies at lines 18-20 but provides no cleanup mechanism. Since the vitest configuration for this example does not include global mock restoration setup, these spies will persist after the test completes and potentially affect other tests if added later.
🧹 Suggested fix (local restore)
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { executionStack, sql, tables } from '../src/prisma/context';
+afterEach(() => {
+ vi.restoreAllMocks();
+});| // context.ts exports a descriptors-only stack — create() is never called. | ||
| // Spy on the descriptor create methods and verify they stay untouched | ||
| // while building query plans from the static context. |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove the inline comments and rely on the test name for intent.
These comments restate the test’s purpose and can be removed to keep the file concise.
✂️ Suggested cleanup
- // context.ts exports a descriptors-only stack — create() is never called.
- // Spy on the descriptor create methods and verify they stay untouched
- // while building query plans from the static context.
const adapterSpy = vi.spyOn(executionStack.adapter, 'create');
const targetSpy = vi.spyOn(executionStack.target, 'create');
const extensionSpies = executionStack.extensionPacks.map((ext) => vi.spyOn(ext, 'create'));
- // Build a query plan — must NOT trigger any descriptor instantiation
sql.from(tables.user).select({ id: tables.user.columns.id }).limit(1).build();As per coding guidelines: “Don’t add comments if avoidable; prefer code which expresses its intent.”
Also applies to: 22-22
| export function createSqlFamilyInstance<TTargetId extends string>( | ||
| options: CreateSqlFamilyInstanceOptions<TTargetId>, | ||
| ): SqlFamilyInstance { | ||
| const { target, adapter, extensionPacks: extensions = [] } = options; | ||
|
|
||
| // Build descriptors array for assembly | ||
| // Assembly functions only use manifest and id, so we can pass Control*Descriptor types directly | ||
| const descriptors = [target, adapter, ...extensions]; | ||
| const descriptors: SqlControlDescriptorWithContributions[] = [target, adapter, ...extensions]; | ||
|
|
||
| // Assemble operation registry, type imports, extension IDs, and parameterized renderers | ||
| const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest); | ||
| const operationRegistry = assembleOperationRegistry(descriptors); | ||
| const codecTypeImports = extractCodecTypeImports(descriptors); | ||
| const operationTypeImports = extractOperationTypeImports(descriptors); | ||
| const extensionIds = extractExtensionIds(adapter, target, extensions); | ||
| const parameterizedRenderers = extractParameterizedRenderers(descriptors); | ||
| const parameterizedTypeImports = extractParameterizedTypeImports(descriptors); | ||
|
|
||
| // Build type metadata registry from manifests | ||
| const typeMetadataRegistry = buildSqlTypeMetadataRegistry({ | ||
| target, | ||
| adapter, | ||
| extensionPacks: extensions, | ||
| target: target as DescriptorWithStorageTypes, | ||
| adapter: adapter as DescriptorWithStorageTypes & { readonly targetId: string }, | ||
| extensionPacks: extensions as readonly DescriptorWithStorageTypes[], | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Type assertions are safe but consider type narrowing.
The assertions at lines 301-303 cast to DescriptorWithStorageTypes to satisfy the structural typing for buildSqlTypeMetadataRegistry. While safe (the source types satisfy the target structure), this could be cleaner with a type predicate or by having CreateSqlFamilyInstanceOptions directly extend DescriptorWithStorageTypes constraints.
♻️ Optional: Consider defining DescriptorWithStorageTypes as a constraint
If DescriptorWithStorageTypes is frequently used for type narrowing, consider making it a type constraint on the options interface directly, which would eliminate the need for assertions:
interface CreateSqlFamilyInstanceOptions<TTargetId extends string> {
readonly target: TargetDescriptor<'sql', TTargetId> & SqlControlDescriptorWithContributions & DescriptorWithStorageTypes;
// ...
}| sql<Contract, CodecTypes>({ context: contextWithoutReturning }) | ||
| .insert(tables.user, { | ||
| email: param('email'), | ||
| }) | ||
| .returning(userColumns.id, userColumns.email); | ||
| }).toThrow('returning() requires returning capability'); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
fd -t f "sql-dml-returning.test.ts" packages/2-sql/Repository: prisma/prisma-next
Length of output: 124
🏁 Script executed:
cat -n packages/2-sql/4-lanes/sql-lane/test/sql-dml-returning.test.ts | head -200Repository: prisma/prisma-next
Length of output: 7032
🏁 Script executed:
rg "sql<Contract,\s*CodecTypes" packages/2-sql/4-lanes/sql-lane/test/sql-dml-returning.test.ts -nRepository: prisma/prisma-next
Length of output: 440
Remove CodecTypes from all sql<...> generic parameters in this file.
The coding guidelines require that sql() infer codec and operation types from the contract. Passing CodecTypes as a separate type parameter violates this pattern.
Required changes (5 occurrences)
- sql<Contract, CodecTypes>
+ sql<Contract>Update lines: 81, 106, 127, 156, 181.
| function createTestSetup() { | ||
| const adapter = createStubAdapter(); | ||
| const driver = createMockDriver(); | ||
|
|
||
| const driverDescriptor: RuntimeDriverDescriptor< | ||
| 'sql', | ||
| 'postgres', | ||
| SqlRuntimeDriverInstance<'postgres'> | ||
| > = { | ||
| kind: 'driver', | ||
| id: 'test-driver', | ||
| version: '0.0.1', | ||
| familyId: 'sql' as const, | ||
| targetId: 'postgres' as const, | ||
| create() { | ||
| return Object.assign( | ||
| { familyId: 'sql' as const, targetId: 'postgres' as const }, | ||
| driver, | ||
| ) as SqlRuntimeDriverInstance<'postgres'>; | ||
| }, | ||
| }; | ||
| const targetDescriptor = createTestTargetDescriptor(); | ||
| const adapterDescriptor = createTestAdapterDescriptor(adapter); | ||
|
|
||
| const stack = createExecutionStack({ | ||
| target: createTestTargetDescriptor(), | ||
| adapter: createTestAdapterDescriptor(adapter), | ||
| driver: driverDescriptor, | ||
| target: targetDescriptor, | ||
| adapter: adapterDescriptor, | ||
| extensionPacks: [], | ||
| }); | ||
|
|
||
| const stackInstance = instantiateExecutionStack(stack); | ||
| return { stackInstance, driver }; | ||
|
|
||
| const context = createExecutionContext({ | ||
| contract: testContract, | ||
| stack: { target: targetDescriptor, adapter: adapterDescriptor, extensionPacks: [] }, | ||
| }); | ||
|
|
||
| return { stackInstance: stackInstance as never, context, driver }; | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Clarify the as never cast or use a more descriptive escape.
Line 156 uses stackInstance as never which suppresses type checking. While test-only casts are acceptable, as never is unusually aggressive. Consider using a double cast with explanation:
return {
stackInstance: stackInstance as unknown as Parameters<typeof createRuntime>[0]['stackInstance'],
context,
driver
};Or add a brief comment explaining why the type mismatch exists (e.g., test stub vs. full implementation).
createExecutionStack previously widened target/adapter/extension descriptors to the base Runtime*Descriptor types, which caused SqlStaticContributions to be lost and forced casts when passing stacks into sql-runtime createExecutionContext. Update the function typing to keep the concrete descriptor types while still returning an ExecutionStack shape.
…s and tests With createExecutionStack now preserving SQL descriptor types, these call sites can pass the stack directly to createExecutionContext without unsafe casts. This keeps the demos and helpers type-safe while still using the shared stack construction API.
…tack instantiation Split the no-emit workflow into prisma-no-emit/context.ts (static stack + context + query roots) and prisma-no-emit/runtime.ts (lazy runtime creation). This mirrors the emitted demo structure and ensures instantiateExecutionStack is only called when getRuntime is invoked. Update no-emit query imports and docs, and remove the old query-no-emit/runtime-no-emit modules.
Add afterEach restoration and remove redundant inline comments to keep the no-runtime test focused on observable behavior.
CreateSqlFamilyInstanceOptions now includes DescriptorWithStorageTypes so the metadata registry can be built without unsafe casts.
Drop CodecTypes from sql<> generics so codec and operation types are inferred from the contract, matching the project guidelines.
Replace the as-never escape with a named ExecutionStackInstance type and a single, focused cast to align with the test-only type mismatch.
jkomyno
left a comment
There was a problem hiding this comment.
Approved, with a few recommended changes
| }): Omit< | ||
| ExecutionStack< | ||
| FamilyIdOf<TTargetDescriptor>, | ||
| TargetIdOf<TTargetDescriptor>, | ||
| TAdapterInstance, | ||
| TDriverInstance, | ||
| TExtensionInstance | ||
| >, | ||
| 'target' | 'adapter' | 'driver' | 'extensionPacks' | ||
| > & { | ||
| readonly target: TTargetDescriptor; | ||
| readonly adapter: TAdapterDescriptor; | ||
| readonly driver: TDriverDescriptor | undefined; | ||
| readonly extensionPacks: readonly TExtensionDescriptor[]; |
There was a problem hiding this comment.
Can we simplify createExecutionStack's return type? The Omit<ExecutionStack<...>, 'target' | 'adapter' | 'driver' | 'extensionPacks'> & { ... } removes all 4 properties and re-adds them, effectively making the Omit<...> side boil down to {}. This seems like a no-op that obscures readability.
There was a problem hiding this comment.
Simplified a litte, also added SQL-specific factory functions so users themselves won't see this function.
| return createRuntime({ | ||
| stackInstance, | ||
| contract: fixtureContract, | ||
| stackInstance: stackInstance as never, |
|
|
||
| // Create a test target descriptor | ||
| function createTestTargetDescriptor() { | ||
| function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> { |
There was a problem hiding this comment.
Functions named createTestTargetDescriptor or createTestAdapterDescriptor are defined in many individual test files, with minor variations (if any). test/utils.ts already exports some shared versions of this. Can we DRY these definitions up?
| function parseArrayElements(input: string): string[] { | ||
| const result: string[] = []; | ||
| let i = 0; | ||
| while (i < input.length) { | ||
| if (input[i] === ',') { | ||
| i++; | ||
| continue; | ||
| } | ||
| if (input[i] === '"') { | ||
| i++; | ||
| let element = ''; | ||
| while (i < input.length && input[i] !== '"') { | ||
| if (input[i] === '\\' && i + 1 < input.length) { | ||
| i++; | ||
| element += input[i]; | ||
| } else { | ||
| element += input[i]; | ||
| } | ||
| i++; | ||
| } | ||
| i++; | ||
| result.push(element); | ||
| } else { | ||
| const nextComma = input.indexOf(',', i); | ||
| if (nextComma === -1) { | ||
| result.push(input.slice(i).trim()); | ||
| i = input.length; | ||
| } else { | ||
| result.push(input.slice(i, nextComma).trim()); | ||
| i = nextComma; | ||
| } | ||
| } | ||
| } | ||
| return result; | ||
| } |
There was a problem hiding this comment.
This function silently consumes the rest of the input if an opening " quote has no matching close quote, which could produce incorrect enum values during migration planning. You should add unterminated-quote detection
There was a problem hiding this comment.
Also, we should have a migration planning test catching this
There was a problem hiding this comment.
I'm gonna revert this change and skip the test. Ack?
Introduce a SQL-specific execution stack factory that preserves descriptor contributions and exports a typed stack alias. Update sql-runtime tests and examples in-package to use the new helper, and document the preferred usage.
Adopt the SQL-specific stack factory in the demo contexts and runtime helpers so stacks keep SQL descriptor types without relying on the core generic factory.
Update guides and references to prefer createSqlExecutionStack in SQL examples and extension setup, keeping consumer docs aligned with the new factory.
These files are local-only notes and should remain untracked.
Replace the omit-and-readd pattern with a straight ExecutionStack intersection for improved readability while preserving the concrete descriptor types.
Replace local createTestTargetDescriptor and createTestAdapterDescriptor helpers with the shared versions from test/utils to reduce duplication.
Bind the stack generics to explicit family/target parameters so the returned ExecutionStack type aligns with the provided descriptors without relying on conditional extraction helpers.
Drop explicit generic arguments so createExecutionStack infers the SQL descriptor and instance types correctly under the new core stack signature.
Double the spin-up timeout for dev databases and apply it to all Kysely integration tests to avoid false timeouts on slower environments.
The project is fully delivered; per plan.md task #133, strip the transient `projects/created-updated-at-authoring/` directory and the lone in-test reference to spec.md. The PR description, commit history, and the contract-psl tests themselves are now the canonical record of what shipped.
Summary
Enable a static SQL
ExecutionContext(contract + codec/operation registries + type helpers) to be created from descriptors only — no adapter/extension instantiation required. This unblocks an app structure where importing query roots (sql,orm,schema,tables) has zero runtime side-effects.SqlStaticContributionsinterface (codecs(),operationSignatures(),parameterizedCodecs()). No method is optional; descriptors with nothing to contribute return empty values.createExecutionContextfrom descriptors-only stack: Accepts{ contract, stack }wherestackis descriptors-only. Merges contributions deterministically (target → adapter → extensions), validates parameterized codecs, and returns{ contract, operations, codecs, types }.createRuntime: No longer instantiates stack components, derives context, or constructs drivers. Caller providesExecutionStackInstance,ExecutionContext, and aSqlDriver.OperationManifest,LoweringSpecManifest, andComponentMetadata.operationsfrom framework contract types. SQL operations with lowering are family-owned viaSqlOperationSignature.SqlRuntimeExtensionInstanceis now identity-only — contributions live exclusively on descriptors.context.ts(static setup + query roots) andruntime.ts(dynamic wiring) are cleanly separated.What changed
1. Operations layering (strip manifest hangover)
OperationManifest/LoweringSpecManifestfrom@prisma-next/contractComponentMetadata.operationsfrom framework componentsOperationRegistryfrom descriptoroperationSignatures()2. Descriptor-level static contributions
SqlStaticContributionsinterface in@prisma-next/sql-runtimeSqlRuntimeTargetDescriptor,SqlRuntimeAdapterDescriptor,SqlRuntimeExtensionDescriptortypes extending core descriptors with required contributionstarget-postgres,adapter-postgres,extension-pgvector3.
createExecutionContextfrom descriptors-only stackcreateExecutionContext({ contract, stack })storage.typesvalidation, inline columntypeParamsvalidationtypesregistry always present (may be empty)4. Wafer-thin
createRuntime{ stackInstance, context, driver, verify, plugins }driverOptionsplumbing, offline driver defaulting, context derivation, instantiation5. Demo refactor
context.ts: validates contract, defines descriptors-only stack, exports query rootsruntime.ts: instantiates stack + driver, calls wafer-thincreateRuntime6. Tests
@prisma-next/adapter-postgres)storage.types, inlinetypeParams, duplicates)context.typesalways-present assertion7. Instance contribution surface removed
SqlRuntimeExtensionInstancestripped ofcodecs?(),operations?(),parameterizedCodecs?()create()returns identity-only instance8. Docs & ADR updates
sql-runtimeREADME updated with new two-phase API (static context + dynamic runtime)Why
createRuntimedoes one thing — wire up pre-built componentsTest plan
pnpm --filter @prisma-next/sql-runtime test— 33 tests passpnpm --filter @prisma-next/adapter-postgres test— 142 tests pass (includes parity test)pnpm --filter @prisma-next/extension-pgvector test— 29 tests passpnpm --filter prisma-next-demo test— 22 tests pass (including integration)pnpm lint:deps— 0 violationsSummary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor