@prisma-next/sql-runtime 0.5.0-dev.9 → 0.6.0-dev.1
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 +2 -1
- package/dist/exports-BSTHn_rH.mjs +1516 -0
- package/dist/exports-BSTHn_rH.mjs.map +1 -0
- package/dist/{index-CZmC2kD3.d.mts → index-CTCvZOWI.d.mts} +87 -44
- package/dist/index-CTCvZOWI.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -3
- package/dist/test/utils.d.mts +33 -29
- package/dist/test/utils.d.mts.map +1 -1
- package/dist/test/utils.mjs +104 -64
- package/dist/test/utils.mjs.map +1 -1
- package/package.json +15 -14
- package/src/codecs/alias-resolver.ts +37 -0
- package/src/codecs/decoding.ts +163 -129
- package/src/codecs/encoding.ts +121 -46
- package/src/codecs/validation.ts +4 -4
- package/src/content-hash.ts +44 -0
- package/src/exports/index.ts +4 -1
- package/src/guardrails/raw.ts +1 -50
- package/src/marker.ts +13 -20
- package/src/middleware/before-compile-chain.ts +1 -31
- package/src/middleware/budgets.ts +26 -113
- package/src/middleware/lints.ts +17 -23
- package/src/middleware/sql-middleware.ts +21 -2
- package/src/runtime-spi.ts +3 -8
- package/src/sql-context.ts +320 -109
- package/src/sql-marker.ts +88 -50
- package/src/sql-runtime.ts +108 -90
- package/dist/exports-BOHa3Emo.mjs +0 -1334
- package/dist/exports-BOHa3Emo.mjs.map +0 -1
- package/dist/index-CZmC2kD3.d.mts.map +0 -1
- package/src/codecs/json-schema-validation.ts +0 -61
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
|
|
3
|
-
export { budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
|
1
|
+
import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-BSTHn_rH.mjs";
|
|
2
|
+
export { APP_SPACE_ID, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/test/utils.d.mts
CHANGED
|
@@ -1,25 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as SqlRuntimeTargetDescriptor, D as SqlRuntimeDriverInstance, E as SqlRuntimeAdapterInstance, O as SqlRuntimeExtensionDescriptor, T as SqlRuntimeAdapterDescriptor, d as createRuntime, k as SqlRuntimeExtensionInstance, m as SqlStatement, y as ExecutionContext } from "../index-CTCvZOWI.mjs";
|
|
2
2
|
import { ResultType } from "@prisma-next/framework-components/runtime";
|
|
3
|
-
import { Adapter, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
|
|
4
|
-
import * as _prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
|
|
3
|
+
import { Adapter, Codec, ContractCodecRegistry, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
|
|
4
|
+
import * as _$_prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
|
|
5
5
|
import { RuntimeDriverDescriptor } from "@prisma-next/framework-components/execution";
|
|
6
6
|
import { Contract } from "@prisma-next/contract/types";
|
|
7
|
+
import { CodecDescriptor } from "@prisma-next/framework-components/codec";
|
|
7
8
|
import { DevDatabase, collectAsync, createDevDatabase, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
|
|
8
9
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
9
10
|
import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
10
11
|
import { Client } from "pg";
|
|
11
12
|
|
|
12
13
|
//#region test/utils.d.ts
|
|
13
|
-
|
|
14
14
|
/**
|
|
15
|
-
* Executes a plan and collects all results into an array.
|
|
16
|
-
* This helper DRYs up the common pattern of executing plans in tests.
|
|
17
|
-
* The return type is inferred from the plan's type parameter.
|
|
15
|
+
* Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.
|
|
18
16
|
*/
|
|
19
17
|
declare function executePlanAndCollect<P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]>;
|
|
20
18
|
/**
|
|
21
|
-
* Drains a plan execution, consuming all results without collecting them.
|
|
22
|
-
* Useful for testing side effects without memory overhead.
|
|
19
|
+
* Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.
|
|
23
20
|
*/
|
|
24
21
|
declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan: SqlExecutionPlan | SqlQueryPlan<unknown>): Promise<void>;
|
|
25
22
|
/**
|
|
@@ -27,52 +24,59 @@ declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, p
|
|
|
27
24
|
*/
|
|
28
25
|
declare function executeStatement(client: Client, statement: SqlStatement): Promise<void>;
|
|
29
26
|
/**
|
|
30
|
-
* Sets up database schema and data, then writes the contract marker.
|
|
31
|
-
* This helper DRYs up the common pattern of database setup in tests.
|
|
27
|
+
* Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.
|
|
32
28
|
*/
|
|
33
29
|
declare function setupTestDatabase(client: Client, contract: Contract<SqlStorage>, setupFn: (client: Client) => Promise<void>): Promise<void>;
|
|
34
30
|
/**
|
|
35
|
-
* Writes a contract marker to the database.
|
|
36
|
-
* This helper DRYs up the common pattern of writing contract markers in tests.
|
|
31
|
+
* Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.
|
|
37
32
|
*/
|
|
38
33
|
declare function writeTestContractMarker(client: Client, contract: Contract<SqlStorage>): Promise<void>;
|
|
39
34
|
/**
|
|
40
|
-
* Creates a test adapter descriptor from a raw adapter.
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
* Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.
|
|
43
39
|
*/
|
|
44
|
-
declare function
|
|
40
|
+
declare function buildTestContractCodecs(codecs: ReadonlyArray<Codec<string>>): ContractCodecRegistry;
|
|
41
|
+
/**
|
|
42
|
+
* Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry
|
|
43
|
+
* `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.
|
|
44
|
+
*/
|
|
45
|
+
declare function descriptorsFromCodecs(codecs: ReadonlyArray<Codec<string>>): ReadonlyArray<CodecDescriptor>;
|
|
46
|
+
declare function createTestAdapterDescriptor(adapter: StubAdapter): SqlRuntimeAdapterDescriptor<'postgres'>;
|
|
45
47
|
/**
|
|
46
48
|
* Creates a test target descriptor with empty static contributions.
|
|
47
49
|
*/
|
|
48
50
|
declare function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'>;
|
|
49
51
|
/**
|
|
50
|
-
* Creates an ExecutionContext for testing.
|
|
51
|
-
* This helper DRYs up the common pattern of context creation in tests.
|
|
52
|
+
* Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.
|
|
52
53
|
*
|
|
53
|
-
* Accepts a raw adapter and optional extension descriptors, wrapping the
|
|
54
|
-
* adapter in a descriptor internally for descriptor-first context creation.
|
|
54
|
+
* Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.
|
|
55
55
|
*/
|
|
56
|
-
declare function createTestContext<TContract extends Contract<SqlStorage>>(contract: TContract, adapter:
|
|
56
|
+
declare function createTestContext<TContract extends Contract<SqlStorage>>(contract: TContract, adapter: StubAdapter, options?: {
|
|
57
57
|
extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;
|
|
58
58
|
}): ExecutionContext<TContract>;
|
|
59
59
|
declare function createTestStackInstance(options?: {
|
|
60
60
|
extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;
|
|
61
61
|
driver?: RuntimeDriverDescriptor<'sql', 'postgres', unknown, SqlRuntimeDriverInstance<'postgres'>>;
|
|
62
|
-
}): _prisma_next_framework_components_execution0.ExecutionStackInstance<"sql", "postgres", SqlRuntimeAdapterInstance<"postgres">, SqlRuntimeDriverInstance<"postgres">, SqlRuntimeExtensionInstance<"postgres">>;
|
|
62
|
+
}): _$_prisma_next_framework_components_execution0.ExecutionStackInstance<"sql", "postgres", SqlRuntimeAdapterInstance<"postgres">, SqlRuntimeDriverInstance<"postgres">, SqlRuntimeExtensionInstance<"postgres">>;
|
|
63
|
+
/**
|
|
64
|
+
* Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.
|
|
65
|
+
*/
|
|
66
|
+
type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {
|
|
67
|
+
readonly __codecs: ReadonlyArray<Codec<string>>;
|
|
68
|
+
};
|
|
63
69
|
/**
|
|
64
|
-
* Creates a stub adapter for testing.
|
|
65
|
-
* This helper DRYs up the common pattern of adapter creation in tests.
|
|
70
|
+
* Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.
|
|
66
71
|
*
|
|
67
|
-
* The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)
|
|
68
|
-
* to enable type inference in tests without requiring the postgres adapter package.
|
|
72
|
+
* The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.
|
|
69
73
|
*/
|
|
70
|
-
declare function createStubAdapter():
|
|
74
|
+
declare function createStubAdapter(): StubAdapter;
|
|
71
75
|
declare function createTestContract(contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {
|
|
72
76
|
storageHash?: string;
|
|
73
77
|
profileHash?: string;
|
|
74
78
|
storage?: Omit<SqlStorage, 'storageHash'>;
|
|
75
79
|
}): Contract<SqlStorage>;
|
|
76
80
|
//#endregion
|
|
77
|
-
export { type DevDatabase, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
|
|
81
|
+
export { type DevDatabase, StubAdapter, buildTestContractCodecs, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, descriptorsFromCodecs, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
|
|
78
82
|
//# sourceMappingURL=utils.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.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AA,GAAS,uBAAA,6BAIP,wBAAA;AAAA,IAEH,8CAAA,CAAA,sBAAA,oBAAA,yBAAA,cAAA,wBAAA,cAAA,2BAAA;;;;KAcW,WAAA,GAAc,OAAA,CAAQ,SAAA,EAAW,QAAA,CAAS,UAAA,GAAa,gBAAA;EAAA,SACxD,QAAA,EAAU,aAAA,CAAc,KAAA;AAAA;AAjLnC;;;;;AAAA,iBAyLgB,iBAAA,CAAA,GAAqB,WAAA;AAAA,iBA4CrB,kBAAA,CACd,QAAA,EAAU,OAAA,CAAQ,IAAA,CAAK,QAAA,CAAS,UAAA;EAC9B,WAAA;EACA,WAAA;EACA,OAAA,GAAU,IAAA,CAAK,UAAA;AAAA,IAEhB,QAAA,CAAS,UAAA"}
|
package/dist/test/utils.mjs
CHANGED
|
@@ -1,11 +1,37 @@
|
|
|
1
|
-
import { c as
|
|
2
|
-
import { codec, createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
|
|
1
|
+
import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-BSTHn_rH.mjs";
|
|
3
2
|
import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
|
|
4
3
|
import { coreHash, profileHash } from "@prisma-next/contract/types";
|
|
4
|
+
import { voidParamsSchema } from "@prisma-next/framework-components/codec";
|
|
5
5
|
import { builtinGeneratorIds } from "@prisma-next/ids";
|
|
6
6
|
import { generateId } from "@prisma-next/ids/runtime";
|
|
7
7
|
import { collectAsync, collectAsync as collectAsync$1, createDevDatabase, drainAsyncIterable, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
|
|
8
|
-
|
|
8
|
+
//#region test/test-codec.ts
|
|
9
|
+
function defineTestCodec(config) {
|
|
10
|
+
const identity = (v) => v;
|
|
11
|
+
const userEncode = config.encode;
|
|
12
|
+
const userDecode = config.decode;
|
|
13
|
+
const widenedConfig = config;
|
|
14
|
+
return {
|
|
15
|
+
id: config.typeId,
|
|
16
|
+
encode: (value, ctx) => {
|
|
17
|
+
try {
|
|
18
|
+
return Promise.resolve(userEncode(value, ctx));
|
|
19
|
+
} catch (error) {
|
|
20
|
+
return Promise.reject(error);
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
decode: (wire, ctx) => {
|
|
24
|
+
try {
|
|
25
|
+
return Promise.resolve(userDecode(wire, ctx));
|
|
26
|
+
} catch (error) {
|
|
27
|
+
return Promise.reject(error);
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
encodeJson: widenedConfig.encodeJson ?? identity,
|
|
31
|
+
decodeJson: widenedConfig.decodeJson ?? identity
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
9
35
|
//#region test/utils.ts
|
|
10
36
|
function createTestMutationDefaultGenerators() {
|
|
11
37
|
return builtinGeneratorIds.map((id) => ({
|
|
@@ -13,20 +39,18 @@ function createTestMutationDefaultGenerators() {
|
|
|
13
39
|
generate: (params) => generateId(params ? {
|
|
14
40
|
id,
|
|
15
41
|
params
|
|
16
|
-
} : { id })
|
|
42
|
+
} : { id }),
|
|
43
|
+
stability: "field"
|
|
17
44
|
}));
|
|
18
45
|
}
|
|
19
46
|
/**
|
|
20
|
-
* Executes a plan and collects all results into an array.
|
|
21
|
-
* This helper DRYs up the common pattern of executing plans in tests.
|
|
22
|
-
* The return type is inferred from the plan's type parameter.
|
|
47
|
+
* Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.
|
|
23
48
|
*/
|
|
24
49
|
async function executePlanAndCollect(runtime, plan) {
|
|
25
50
|
return collectAsync$1(runtime.execute(plan));
|
|
26
51
|
}
|
|
27
52
|
/**
|
|
28
|
-
* Drains a plan execution, consuming all results without collecting them.
|
|
29
|
-
* Useful for testing side effects without memory overhead.
|
|
53
|
+
* Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.
|
|
30
54
|
*/
|
|
31
55
|
async function drainPlanExecution(runtime, plan) {
|
|
32
56
|
return drainAsyncIterable(runtime.execute(plan));
|
|
@@ -42,8 +66,7 @@ async function executeStatement(client, statement) {
|
|
|
42
66
|
await client.query(statement.sql);
|
|
43
67
|
}
|
|
44
68
|
/**
|
|
45
|
-
* Sets up database schema and data, then writes the contract marker.
|
|
46
|
-
* This helper DRYs up the common pattern of database setup in tests.
|
|
69
|
+
* Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.
|
|
47
70
|
*/
|
|
48
71
|
async function setupTestDatabase(client, contract, setupFn) {
|
|
49
72
|
await client.query("drop schema if exists prisma_contract cascade");
|
|
@@ -52,6 +75,7 @@ async function setupTestDatabase(client, contract, setupFn) {
|
|
|
52
75
|
await executeStatement(client, ensureSchemaStatement);
|
|
53
76
|
await executeStatement(client, ensureTableStatement);
|
|
54
77
|
await executeStatement(client, writeContractMarker({
|
|
78
|
+
space: APP_SPACE_ID,
|
|
55
79
|
storageHash: contract.storage.storageHash,
|
|
56
80
|
profileHash: contract.profileHash,
|
|
57
81
|
contractJson: contract,
|
|
@@ -59,11 +83,11 @@ async function setupTestDatabase(client, contract, setupFn) {
|
|
|
59
83
|
}).insert);
|
|
60
84
|
}
|
|
61
85
|
/**
|
|
62
|
-
* Writes a contract marker to the database.
|
|
63
|
-
* This helper DRYs up the common pattern of writing contract markers in tests.
|
|
86
|
+
* Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.
|
|
64
87
|
*/
|
|
65
88
|
async function writeTestContractMarker(client, contract) {
|
|
66
89
|
await executeStatement(client, writeContractMarker({
|
|
90
|
+
space: APP_SPACE_ID,
|
|
67
91
|
storageHash: contract.storage.storageHash,
|
|
68
92
|
profileHash: contract.profileHash,
|
|
69
93
|
contractJson: contract,
|
|
@@ -71,20 +95,48 @@ async function writeTestContractMarker(client, contract) {
|
|
|
71
95
|
}).insert);
|
|
72
96
|
}
|
|
73
97
|
/**
|
|
74
|
-
* Creates a test adapter descriptor from a raw adapter.
|
|
75
|
-
|
|
76
|
-
|
|
98
|
+
* Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.
|
|
99
|
+
*/
|
|
100
|
+
/**
|
|
101
|
+
* Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.
|
|
77
102
|
*/
|
|
103
|
+
function buildTestContractCodecs(codecs) {
|
|
104
|
+
const byId = /* @__PURE__ */ new Map();
|
|
105
|
+
for (const codec of codecs) byId.set(codec.id, codec);
|
|
106
|
+
return {
|
|
107
|
+
forColumn: () => void 0,
|
|
108
|
+
forCodecId: (codecId) => byId.get(codecId)
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry
|
|
113
|
+
* `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.
|
|
114
|
+
*/
|
|
115
|
+
function descriptorsFromCodecs(codecs) {
|
|
116
|
+
const descriptors = [];
|
|
117
|
+
for (const instance of codecs) {
|
|
118
|
+
const legacy = instance;
|
|
119
|
+
descriptors.push({
|
|
120
|
+
codecId: instance.id,
|
|
121
|
+
traits: legacy.traits ?? [],
|
|
122
|
+
targetTypes: legacy.targetTypes ?? [],
|
|
123
|
+
paramsSchema: voidParamsSchema,
|
|
124
|
+
isParameterized: false,
|
|
125
|
+
factory: () => () => instance,
|
|
126
|
+
...legacy.meta !== void 0 ? { meta: legacy.meta } : {}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return descriptors;
|
|
130
|
+
}
|
|
78
131
|
function createTestAdapterDescriptor(adapter) {
|
|
79
|
-
const
|
|
132
|
+
const descriptors = descriptorsFromCodecs(adapter.__codecs);
|
|
80
133
|
return {
|
|
81
134
|
kind: "adapter",
|
|
82
135
|
id: "test-adapter",
|
|
83
136
|
version: "0.0.1",
|
|
84
137
|
familyId: "sql",
|
|
85
138
|
targetId: "postgres",
|
|
86
|
-
codecs: () =>
|
|
87
|
-
parameterizedCodecs: () => [],
|
|
139
|
+
codecs: () => descriptors,
|
|
88
140
|
mutationDefaultGenerators: createTestMutationDefaultGenerators,
|
|
89
141
|
create(_stack) {
|
|
90
142
|
return Object.assign({
|
|
@@ -104,8 +156,7 @@ function createTestTargetDescriptor() {
|
|
|
104
156
|
version: "0.0.1",
|
|
105
157
|
familyId: "sql",
|
|
106
158
|
targetId: "postgres",
|
|
107
|
-
codecs: () =>
|
|
108
|
-
parameterizedCodecs: () => [],
|
|
159
|
+
codecs: () => [],
|
|
109
160
|
create() {
|
|
110
161
|
return {
|
|
111
162
|
familyId: "sql",
|
|
@@ -115,11 +166,9 @@ function createTestTargetDescriptor() {
|
|
|
115
166
|
};
|
|
116
167
|
}
|
|
117
168
|
/**
|
|
118
|
-
* Creates an ExecutionContext for testing.
|
|
119
|
-
* This helper DRYs up the common pattern of context creation in tests.
|
|
169
|
+
* Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.
|
|
120
170
|
*
|
|
121
|
-
* Accepts a raw adapter and optional extension descriptors, wrapping the
|
|
122
|
-
* adapter in a descriptor internally for descriptor-first context creation.
|
|
171
|
+
* Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.
|
|
123
172
|
*/
|
|
124
173
|
function createTestContext(contract, adapter, options) {
|
|
125
174
|
return createExecutionContext({
|
|
@@ -140,51 +189,42 @@ function createTestStackInstance(options) {
|
|
|
140
189
|
}));
|
|
141
190
|
}
|
|
142
191
|
/**
|
|
143
|
-
* Creates a stub adapter for testing.
|
|
144
|
-
* This helper DRYs up the common pattern of adapter creation in tests.
|
|
192
|
+
* Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.
|
|
145
193
|
*
|
|
146
|
-
* The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)
|
|
147
|
-
* to enable type inference in tests without requiring the postgres adapter package.
|
|
194
|
+
* The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.
|
|
148
195
|
*/
|
|
149
196
|
function createStubAdapter() {
|
|
150
|
-
const codecRegistry = createCodecRegistry();
|
|
151
|
-
codecRegistry.register(codec({
|
|
152
|
-
typeId: "pg/int4@1",
|
|
153
|
-
targetTypes: ["int4"],
|
|
154
|
-
encode: (value) => value,
|
|
155
|
-
decode: (wire) => wire
|
|
156
|
-
}));
|
|
157
|
-
codecRegistry.register(codec({
|
|
158
|
-
typeId: "pg/text@1",
|
|
159
|
-
targetTypes: ["text"],
|
|
160
|
-
encode: (value) => value,
|
|
161
|
-
decode: (wire) => wire
|
|
162
|
-
}));
|
|
163
|
-
codecRegistry.register(codec({
|
|
164
|
-
typeId: "pg/timestamptz@1",
|
|
165
|
-
targetTypes: ["timestamptz"],
|
|
166
|
-
encode: (value) => value instanceof Date ? value.toISOString() : value,
|
|
167
|
-
decode: (wire) => wire instanceof Date ? wire : new Date(wire),
|
|
168
|
-
encodeJson: (value) => value instanceof Date ? value.toISOString() : value,
|
|
169
|
-
decodeJson: (json) => {
|
|
170
|
-
if (typeof json !== "string") throw new Error("expected ISO date string");
|
|
171
|
-
return new Date(json);
|
|
172
|
-
}
|
|
173
|
-
}));
|
|
174
197
|
return {
|
|
198
|
+
__codecs: [
|
|
199
|
+
defineTestCodec({
|
|
200
|
+
typeId: "pg/int4@1",
|
|
201
|
+
targetTypes: ["int4"],
|
|
202
|
+
encode: (value) => value,
|
|
203
|
+
decode: (wire) => wire
|
|
204
|
+
}),
|
|
205
|
+
defineTestCodec({
|
|
206
|
+
typeId: "pg/text@1",
|
|
207
|
+
targetTypes: ["text"],
|
|
208
|
+
encode: (value) => value,
|
|
209
|
+
decode: (wire) => wire
|
|
210
|
+
}),
|
|
211
|
+
defineTestCodec({
|
|
212
|
+
typeId: "pg/timestamptz@1",
|
|
213
|
+
targetTypes: ["timestamptz"],
|
|
214
|
+
encode: (value) => value,
|
|
215
|
+
decode: (wire) => wire,
|
|
216
|
+
encodeJson: (value) => value.toISOString(),
|
|
217
|
+
decodeJson: (json) => {
|
|
218
|
+
if (typeof json !== "string") throw new Error("expected ISO date string");
|
|
219
|
+
return new Date(json);
|
|
220
|
+
}
|
|
221
|
+
})
|
|
222
|
+
],
|
|
175
223
|
profile: {
|
|
176
224
|
id: "stub-profile",
|
|
177
225
|
target: "postgres",
|
|
178
226
|
capabilities: {},
|
|
179
|
-
|
|
180
|
-
return codecRegistry;
|
|
181
|
-
},
|
|
182
|
-
readMarkerStatement() {
|
|
183
|
-
return {
|
|
184
|
-
sql: "select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1",
|
|
185
|
-
params: [1]
|
|
186
|
-
};
|
|
187
|
-
}
|
|
227
|
+
readMarker: async () => ({ kind: "absent" })
|
|
188
228
|
},
|
|
189
229
|
lower(ast, ctx) {
|
|
190
230
|
const sqlText = JSON.stringify(ast);
|
|
@@ -217,7 +257,7 @@ function createTestContract(contract) {
|
|
|
217
257
|
profileHash: profileHash(rest["profileHash"] ?? "sha256:testprofile")
|
|
218
258
|
};
|
|
219
259
|
}
|
|
220
|
-
|
|
221
260
|
//#endregion
|
|
222
|
-
export { collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
|
|
261
|
+
export { buildTestContractCodecs, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, descriptorsFromCodecs, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
|
|
262
|
+
|
|
223
263
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/test/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/utils.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, LoweredStatement, SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { codec, createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array.\n * This helper DRYs up the common pattern of executing plans in tests.\n * The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them.\n * Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker.\n * This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database.\n * This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter.\n * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions\n * derived from the adapter's codec registry.\n */\nexport function createTestAdapterDescriptor(\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const codecRegistry = adapter.profile.codecs();\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => codecRegistry,\n parameterizedCodecs: () => [],\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => createCodecRegistry(),\n parameterizedCodecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing.\n * This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the\n * adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Creates a stub adapter for testing.\n * This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)\n * to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> {\n const codecRegistry = createCodecRegistry();\n\n // Register stub codecs for common test types\n // These match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1)\n // but don't require importing from the postgres adapter package\n codecRegistry.register(\n codec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decode: (wire: string | Date) => (wire instanceof Date ? wire : new Date(wire)),\n // string | Date includes Date which is not assignable to JsonValue, so\n // the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n );\n\n return {\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n codecs() {\n return codecRegistry;\n },\n readMarkerStatement() {\n return {\n sql: 'select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1',\n params: [1],\n };\n },\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;AAiCA,SAAS,sCAAsC;AAC7C,QAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG,EAAE,IAAI,CAAC;EAC7F,EAAE;;;;;;;AAQL,eAAsB,sBAEpB,SAA2C,MAAmC;AAE9E,QAAOA,eAAkB,QAAQ,QAAa,KAAK,CAAC;;;;;;AAOtD,eAAsB,mBACpB,SACA,MACe;AACf,QAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC;;;;;AAMlD,eAAsB,iBAAiB,QAAgB,WAAwC;AAC7F,KAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,QAAM,OAAO,MAAM,UAAU,KAAK,CAAC,GAAG,UAAU,OAAO,CAAC;AACxD;;AAGF,OAAM,OAAO,MAAM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B,kBAAkB;AAE3E,QAAO;EACL,QAAQ,KAAK,aAAa;EAC1B,cAAc,KAAK,mBAAmB;EACtC,SAAS,KAAK,aACV;GAAE,GAAG,KAAK;GAAY,aAAa;GAAkB,GACrD;GAAE,aAAa;GAAkB,QAAQ,EAAE;GAAE;EACjD,QAAQ,KAAK,aAAa,EAAE;EAC5B,OAAO,KAAK,YAAY,EAAE;EAC1B,cAAc,KAAK,mBAAmB,EAAE;EACxC,gBAAgB,KAAK,qBAAqB,EAAE;EAC5C,MAAM,KAAK,WAAW,EAAE;EACxB,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport { voidParamsSchema } from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n return {\n forColumn: () => undefined,\n forCodecId: (codecId) => byId.get(codecId),\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: voidParamsSchema,\n isParameterized: false,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for common test types — match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1) without importing from the postgres adapter package.\n const codecs: ReadonlyArray<Codec<string>> = [\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarker: async () => ({ kind: 'absent' as const }),\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;AAmBA,SAAgB,gBAMd,QAOmC;CACnC,MAAM,YAAY,MAAe;CACjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGh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WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE"}
|
package/package.json
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-dev.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
4
5
|
"type": "module",
|
|
5
6
|
"sideEffects": false,
|
|
6
7
|
"description": "SQL runtime implementation for Prisma Next",
|
|
7
8
|
"dependencies": {
|
|
8
|
-
"arktype": "^2.1.
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/
|
|
11
|
-
"@prisma-next/
|
|
12
|
-
"@prisma-next/
|
|
13
|
-
"@prisma-next/
|
|
14
|
-
"@prisma-next/sql-
|
|
15
|
-
"@prisma-next/
|
|
16
|
-
"@prisma-next/sql-relational-core": "0.
|
|
9
|
+
"arktype": "^2.1.29",
|
|
10
|
+
"@prisma-next/contract": "0.6.0-dev.1",
|
|
11
|
+
"@prisma-next/framework-components": "0.6.0-dev.1",
|
|
12
|
+
"@prisma-next/operations": "0.6.0-dev.1",
|
|
13
|
+
"@prisma-next/utils": "0.6.0-dev.1",
|
|
14
|
+
"@prisma-next/sql-contract": "0.6.0-dev.1",
|
|
15
|
+
"@prisma-next/sql-operations": "0.6.0-dev.1",
|
|
16
|
+
"@prisma-next/ids": "0.6.0-dev.1",
|
|
17
|
+
"@prisma-next/sql-relational-core": "0.6.0-dev.1"
|
|
17
18
|
},
|
|
18
19
|
"devDependencies": {
|
|
19
|
-
"@types/pg": "8.
|
|
20
|
-
"pg": "8.
|
|
21
|
-
"tsdown": "0.
|
|
20
|
+
"@types/pg": "8.20.0",
|
|
21
|
+
"pg": "8.20.0",
|
|
22
|
+
"tsdown": "0.22.0",
|
|
22
23
|
"typescript": "5.9.3",
|
|
23
|
-
"vitest": "4.
|
|
24
|
+
"vitest": "4.1.5",
|
|
24
25
|
"@prisma-next/tsconfig": "0.0.0",
|
|
25
26
|
"@prisma-next/tsdown": "0.0.0",
|
|
26
27
|
"@prisma-next/test-utils": "0.0.1"
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { AnyFromSource, AnyQueryAst } from '@prisma-next/sql-relational-core/ast';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Build a map from query-local table aliases to their underlying source table names.
|
|
5
|
+
*
|
|
6
|
+
* Self-joins like `db.sql.post.as('p1').innerJoin(db.sql.post.as('p2'), …)` produce `ColumnRef`s whose `table` is the alias (`p1`, `p2`) — the SQL renderer needs the alias for `SELECT p1.id, …`. Codec dispatch keys `byColumn` by the underlying source table, so aliases must be resolved back to the source name for `forColumn(...)` to hit. Tables that already use their canonical name (no alias) are also entered so a single
|
|
7
|
+
* lookup works for both shapes.
|
|
8
|
+
*/
|
|
9
|
+
function buildAliasMap(ast: AnyQueryAst): ReadonlyMap<string, string> {
|
|
10
|
+
const aliases = new Map<string, string>();
|
|
11
|
+
const recordSource = (source: AnyFromSource): void => {
|
|
12
|
+
if (source.kind === 'table-source') {
|
|
13
|
+
const key = source.alias ?? source.name;
|
|
14
|
+
aliases.set(key, source.name);
|
|
15
|
+
} else {
|
|
16
|
+
aliases.set(source.alias, source.alias);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
if (ast.kind === 'select') {
|
|
20
|
+
recordSource(ast.from);
|
|
21
|
+
for (const join of ast.joins ?? []) {
|
|
22
|
+
recordSource(join.source);
|
|
23
|
+
}
|
|
24
|
+
} else if (ast.kind === 'raw-sql') {
|
|
25
|
+
// Raw-SQL ASTs do not bind a single primary table — alias resolution
|
|
26
|
+
// is driven by inline `IdentifierRef`s the caller embedded directly.
|
|
27
|
+
} else {
|
|
28
|
+
recordSource(ast.table);
|
|
29
|
+
}
|
|
30
|
+
return aliases;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function makeAliasResolver(ast: AnyQueryAst | undefined): (alias: string) => string {
|
|
34
|
+
if (!ast) return (alias) => alias;
|
|
35
|
+
const map = buildAliasMap(ast);
|
|
36
|
+
return (alias) => map.get(alias) ?? alias;
|
|
37
|
+
}
|