@prisma-next/sql-runtime 0.13.0-dev.2 → 0.13.0-dev.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,52 +41,31 @@ Execute SQL query Plans with deterministic verification, guardrails, and feedbac
41
41
 
42
42
  ## Usage
43
43
 
44
- ```typescript
45
- import postgresAdapter from '@prisma-next/adapter-postgres/runtime';
46
- import postgresDriver from '@prisma-next/driver-postgres/runtime';
47
- import pgvector from '@prisma-next/extension-pgvector/runtime';
48
- import postgresTarget from '@prisma-next/target-postgres/runtime';
49
- import { instantiateExecutionStack } from '@prisma-next/framework-components/execution';
50
- import {
51
- budgets,
52
- createExecutionContext,
53
- createRuntime,
54
- createSqlExecutionStack,
55
- } from '@prisma-next/sql-runtime';
56
-
57
- const contract = postgresTarget.contractSerializer.deserializeContract(contractJson);
58
- const stack = createSqlExecutionStack({
59
- target: postgresTarget,
60
- adapter: postgresAdapter,
61
- driver: postgresDriver,
62
- extensionPacks: [pgvector],
63
- });
44
+ `SqlRuntime` is an abstract base class. Construct a runtime via the target factory — `postgres()` from `@prisma-next/postgres` or `sqlite()` from `@prisma-next/sqlite`. You do not call `new SqlRuntime()` directly.
64
45
 
65
- // Static context (no instantiation needed)
66
- const context = createExecutionContext({ contract, stack });
67
-
68
- // Dynamic runtime
69
- const stackInstance = instantiateExecutionStack(stack);
70
- const driver = stack.driver.create({ connect: { connectionString: process.env.DATABASE_URL } });
71
- const runtime = createRuntime({
72
- stackInstance,
73
- context,
74
- driver,
46
+ ```typescript
47
+ import postgres from '@prisma-next/postgres';
48
+ import { budgets } from '@prisma-next/sql-runtime';
49
+ import type { Contract } from './src/contract';
50
+ import contractJson from './src/contract.json' with { type: 'json' };
51
+
52
+ const db = postgres<Contract>({
53
+ contractJson,
54
+ url: process.env.DATABASE_URL,
75
55
  middleware: [budgets()],
76
56
  });
77
57
 
78
- for await (const row of runtime.execute(plan)) {
58
+ for await (const row of db.runtime().execute(plan)) {
79
59
  console.log(row);
80
60
  }
81
61
  ```
82
62
 
83
- Use `verifyMarker: false` to skip the marker read entirely — e.g. during a known-skewed deploy window where contract drift is expected and tolerated.
63
+ Pass `verifyMarker: false` to skip the marker read entirely — e.g. during a known-skewed deploy window where contract drift is expected and tolerated.
84
64
 
85
65
  ```typescript
86
- const runtime = createRuntime({
87
- stackInstance,
88
- context,
89
- driver,
66
+ const db = postgres<Contract>({
67
+ contractJson,
68
+ url: process.env.DATABASE_URL,
90
69
  verifyMarker: false,
91
70
  middleware: [budgets()],
92
71
  });
@@ -96,9 +75,9 @@ const runtime = createRuntime({
96
75
 
97
76
  ### Runtime
98
77
 
99
- - `createRuntime` - Create a SQL runtime instance
100
- - `Runtime` - Runtime instance type
101
- - `CreateRuntimeOptions` - Options for `createRuntime`
78
+ - `SqlRuntime` - Abstract family-layer base class; subclass to build a target runtime (construction happens via target factories — `postgres()` from `@prisma-next/postgres`, `sqlite()` from `@prisma-next/sqlite`)
79
+ - `Runtime` - Runtime instance interface
80
+ - `withTransaction` - Helper to run a callback inside a transaction against any `Runtime`
102
81
  - `VerifyMarkerOption` - Marker-verification option (`'onFirstUse'` default; `false` to skip)
103
82
  - `RuntimeTelemetryEvent`, `TelemetryOutcome` - Telemetry event types
104
83
 
@@ -159,10 +138,12 @@ The `lints` middleware operates on `plan.ast` when it is a SQL `QueryAst`:
159
138
  When `plan.ast` is missing, the middleware falls back to raw heuristic guardrails (`fallbackWhenAstMissing: 'raw'`) or skips linting (`fallbackWhenAstMissing: 'skip'`). Default is `'raw'`.
160
139
 
161
140
  ```typescript
162
- import { createRuntime, lints } from '@prisma-next/sql-runtime';
141
+ import postgres from '@prisma-next/postgres';
142
+ import { lints } from '@prisma-next/sql-runtime';
163
143
 
164
- const runtime = createRuntime({
165
- // ...
144
+ const db = postgres<Contract>({
145
+ contractJson,
146
+ url: process.env.DATABASE_URL,
166
147
  middleware: [lints({ severities: { noLimit: 'error' } })],
167
148
  });
168
149
  ```
@@ -175,7 +156,7 @@ The SQL runtime extends the abstract `RuntimeCore` base class from `@prisma-next
175
156
  2. **SqlStaticContributions**: Codecs, operation signatures, parameterized codecs, and mutation default generators contributed by each descriptor
176
157
  3. **ExecutionContext**: Built from contract + stack descriptors (no instantiation)
177
158
  4. **ExecutionStackInstance**: Instantiated components used at runtime for execution
178
- 5. **SqlRuntime**: `class SqlRuntimeImpl extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>` — overrides `lower` (with codec param-encoding), `runDriver`, `runBeforeCompile` (delegates to the SQL `beforeCompile` chain), and `close`. The execution path also wraps the `runWithMiddleware` helper from `framework-components/runtime` with codec row-decoding, marker verification (via the `RuntimeFamilyAdapter` defined in `runtime-spi.ts`), and telemetry fingerprinting (via `computeSqlFingerprint` from `fingerprint.ts`).
159
+ 5. **SqlRuntime**: `class SqlRuntime extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>` — overrides `lower` (with codec param-encoding), `runDriver`, `runBeforeCompile` (delegates to the SQL `beforeCompile` chain), and `close`. The execution path also wraps the `runWithMiddleware` helper from `framework-components/runtime` with codec row-decoding, marker verification (via the `RuntimeFamilyAdapter` defined in `runtime-spi.ts`), and telemetry fingerprinting (via `computeSqlFingerprint` from `fingerprint.ts`).
179
160
  6. **SqlMarker**: Provides SQL statements for marker management
180
161
 
181
162
  ```mermaid
@@ -1,3 +1,4 @@
1
+ import { materializeCodec } from "@prisma-next/framework-components/codec";
1
2
  import { AsyncIterableResult, RuntimeCore, checkAborted, checkMiddlewareCompatibility, isRuntimeError, raceAgainstAbort, runBeforeExecuteChain, runWithMiddleware, runtimeError } from "@prisma-next/framework-components/runtime";
2
3
  import { canonicalizeJson } from "@prisma-next/framework-components/utils";
3
4
  import { PreparedParamRef, collectOrderedParamRefs, isQueryAst } from "@prisma-next/sql-relational-core/ast";
@@ -26,31 +27,11 @@ function createAstCodecResolver(descriptors, instanceContextFor) {
26
27
  if (cached) return cached;
27
28
  const descriptor = descriptors.descriptorFor(ref.codecId);
28
29
  if (!descriptor) throw runtimeError("RUNTIME.CODEC_DESCRIPTOR_MISSING", `No codec descriptor registered for codecId '${ref.codecId}'.`, { codecId: ref.codecId });
29
- const validated = validateTypeParams$1(descriptor.paramsSchema, descriptor.isParameterized && ref.typeParams === void 0 ? {
30
- ...ref,
31
- typeParams: {}
32
- } : ref);
33
- const ctx = instanceContextFor(ref);
34
- const codec = descriptor.factory(validated)(ctx);
30
+ const codec = materializeCodec(descriptor, ref, instanceContextFor(ref));
35
31
  cache.set(key, codec);
36
32
  return codec;
37
33
  } };
38
34
  }
39
- function validateTypeParams$1(paramsSchema, ref) {
40
- const result = paramsSchema["~standard"].validate(ref.typeParams);
41
- if (result instanceof Promise) throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `paramsSchema for codec '${ref.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`, {
42
- codecId: ref.codecId,
43
- typeParams: ref.typeParams
44
- });
45
- if ("issues" in result && result.issues) {
46
- const messages = result.issues.map((issue) => issue.message).join("; ");
47
- throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for codec '${ref.codecId}': ${messages}`, {
48
- codecId: ref.codecId,
49
- typeParams: ref.typeParams
50
- });
51
- }
52
- return result.value;
53
- }
54
35
  //#endregion
55
36
  //#region src/codecs/ast-codec-registry.ts
56
37
  /**
@@ -472,6 +453,28 @@ function lints(options) {
472
453
  });
473
454
  }
474
455
  //#endregion
456
+ //#region src/prepared/prepared-statement.ts
457
+ var PreparedStatementImpl = class {
458
+ sql;
459
+ ast;
460
+ meta;
461
+ slots;
462
+ decodeContext;
463
+ paramMetadata;
464
+ constructor(internals) {
465
+ this.sql = internals.sql;
466
+ this.ast = internals.ast;
467
+ this.meta = internals.meta;
468
+ this.slots = internals.slots;
469
+ this.decodeContext = internals.decodeContext;
470
+ this.paramMetadata = internals.paramMetadata;
471
+ Object.freeze(this);
472
+ }
473
+ execute(target, params, options) {
474
+ return target.executePrepared(this, params, options);
475
+ }
476
+ };
477
+ //#endregion
475
478
  //#region src/sql-context.ts
476
479
  function documentScopedCodecTypes(contract) {
477
480
  return blindCast(contract.storage.types);
@@ -1134,28 +1137,6 @@ function resolvePreparedSlotValues(ps, userParams) {
1134
1137
  });
1135
1138
  }
1136
1139
  //#endregion
1137
- //#region src/prepared/prepared-statement.ts
1138
- var PreparedStatementImpl = class {
1139
- sql;
1140
- ast;
1141
- meta;
1142
- slots;
1143
- decodeContext;
1144
- paramMetadata;
1145
- constructor(internals) {
1146
- this.sql = internals.sql;
1147
- this.ast = internals.ast;
1148
- this.meta = internals.meta;
1149
- this.slots = internals.slots;
1150
- this.decodeContext = internals.decodeContext;
1151
- this.paramMetadata = internals.paramMetadata;
1152
- Object.freeze(this);
1153
- }
1154
- execute(target, params, options) {
1155
- return target.executePrepared(this, params, options);
1156
- }
1157
- };
1158
- //#endregion
1159
1140
  //#region src/sql-family-adapter.ts
1160
1141
  var SqlFamilyAdapter = class {
1161
1142
  contract;
@@ -1187,7 +1168,12 @@ const noopLog = {
1187
1168
  warn: noopLogSink,
1188
1169
  error: noopLogSink
1189
1170
  };
1190
- var SqlRuntimeImpl = class extends RuntimeCore {
1171
+ /**
1172
+ * Abstract family-layer base for SQL runtimes. Subclass to build a target runtime
1173
+ * (e.g. `PostgresRuntimeImpl`); app code should consume the `Runtime` interface returned
1174
+ * by the target factories, never this class directly.
1175
+ */
1176
+ var SqlRuntimeBase = class extends RuntimeCore {
1191
1177
  contract;
1192
1178
  adapter;
1193
1179
  driver;
@@ -1305,6 +1291,15 @@ var SqlRuntimeImpl = class extends RuntimeCore {
1305
1291
  executePrepared(ps, params, options) {
1306
1292
  return this.executePreparedAgainstQueryable(ps, params, this.driver, options);
1307
1293
  }
1294
+ /**
1295
+ * Returns the raw driver connection. The connection is a `SqlQueryable` — SQL
1296
+ * issued on it runs below the middleware/codec/telemetry pipeline. It carries
1297
+ * its own lifecycle (`release`/`destroy`/`beginTransaction`); the caller owns
1298
+ * disposal.
1299
+ */
1300
+ acquireRawConnection() {
1301
+ return this.driver.acquireConnection();
1302
+ }
1308
1303
  async *streamRows(exec, decodeContext, driverCall, codecCtx, execMiddlewareCtx) {
1309
1304
  this.familyAdapter.validatePlan(exec, this.contract);
1310
1305
  this._telemetry = null;
@@ -1332,6 +1327,11 @@ var SqlRuntimeImpl = class extends RuntimeCore {
1332
1327
  if (outcome !== null) this.recordTelemetry(exec, outcome, Date.now() - startedAt);
1333
1328
  }
1334
1329
  }
1330
+ /**
1331
+ * Execute a plan against a caller-supplied queryable, running the full
1332
+ * middleware/codec/telemetry pipeline. Use `acquireRawConnection` to obtain a
1333
+ * queryable that subclasses can bind typed plans to.
1334
+ */
1335
1335
  executeAgainstQueryable(plan, queryable, options) {
1336
1336
  this.ensureCodecRegistryValidated();
1337
1337
  const self = this;
@@ -1400,6 +1400,10 @@ var SqlRuntimeImpl = class extends RuntimeCore {
1400
1400
  paramMetadata
1401
1401
  }));
1402
1402
  }
1403
+ /**
1404
+ * Execute a prepared statement against a caller-supplied queryable, running
1405
+ * the full middleware/codec/telemetry pipeline.
1406
+ */
1403
1407
  executePreparedAgainstQueryable(ps, userParams, queryable, options) {
1404
1408
  this.ensureCodecRegistryValidated();
1405
1409
  const self = this;
@@ -1618,19 +1622,7 @@ async function withTransaction(runtime, fn) {
1618
1622
  if (!connectionDisposed) await connection.release();
1619
1623
  }
1620
1624
  }
1621
- function createRuntime(options) {
1622
- const { stackInstance, context, driver, verifyMarker, middleware, mode, log } = options;
1623
- return new SqlRuntimeImpl({
1624
- context,
1625
- adapter: stackInstance.adapter,
1626
- driver,
1627
- ...ifDefined("verifyMarker", verifyMarker),
1628
- ...ifDefined("middleware", middleware),
1629
- ...ifDefined("mode", mode),
1630
- ...ifDefined("log", log)
1631
- });
1632
- }
1633
1625
  //#endregion
1634
- export { lints as a, extractCodecIds as c, deriveParamMetadata as d, encodeParamsWithMetadata as f, createSqlExecutionStack as i, validateCodecRegistryCompleteness as l, withTransaction as n, budgets as o, createAstCodecRegistry as p, createExecutionContext as r, lowerSqlPlan as s, createRuntime as t, validateContractCodecMappings as u };
1626
+ export { PreparedStatementImpl as a, lowerSqlPlan as c, validateContractCodecMappings as d, deriveParamMetadata as f, createSqlExecutionStack as i, extractCodecIds as l, createAstCodecRegistry as m, withTransaction as n, lints as o, encodeParamsWithMetadata as p, createExecutionContext as r, budgets as s, SqlRuntimeBase as t, validateCodecRegistryCompleteness as u };
1635
1627
 
1636
- //# sourceMappingURL=exports-DDqF-xmg.mjs.map
1628
+ //# sourceMappingURL=exports-QqFFY55a.mjs.map