@prisma-next/adapter-postgres 0.5.0-dev.6 → 0.5.0-dev.61
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 +14 -16
- package/dist/adapter-D0MBaNqv.mjs +47 -0
- package/dist/adapter-D0MBaNqv.mjs.map +1 -0
- package/dist/adapter.d.mts +3 -4
- package/dist/adapter.d.mts.map +1 -1
- package/dist/adapter.mjs +1 -1
- package/dist/column-types.d.mts +20 -24
- package/dist/column-types.d.mts.map +1 -1
- package/dist/column-types.mjs +19 -58
- package/dist/column-types.mjs.map +1 -1
- package/dist/control.d.mts +76 -3
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +48 -9
- package/dist/control.mjs.map +1 -1
- package/dist/{descriptor-meta-RTDzyrae.mjs → descriptor-meta-D8znZhXl.mjs} +35 -24
- package/dist/descriptor-meta-D8znZhXl.mjs.map +1 -0
- package/dist/operation-types.d.mts +11 -10
- package/dist/operation-types.d.mts.map +1 -1
- package/dist/runtime.d.mts +3 -11
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +17 -77
- package/dist/runtime.mjs.map +1 -1
- package/dist/{sql-renderer-pEaSP82_.mjs → sql-renderer-Qt6yk5Qj.mjs} +89 -46
- package/dist/sql-renderer-Qt6yk5Qj.mjs.map +1 -0
- package/dist/{types-CfRPdAk8.d.mts → types-tLtmYqCO.d.mts} +12 -1
- package/dist/types-tLtmYqCO.d.mts.map +1 -0
- package/dist/types.d.mts +1 -1
- package/package.json +21 -21
- package/src/core/adapter.ts +15 -41
- package/src/core/codec-lookup.ts +19 -0
- package/src/core/control-adapter.ts +68 -1
- package/src/core/control-mutation-defaults.ts +24 -18
- package/src/core/descriptor-meta.ts +39 -19
- package/src/core/sql-renderer.ts +111 -66
- package/src/core/types.ts +11 -0
- package/src/exports/column-types.ts +21 -61
- package/src/exports/control.ts +3 -2
- package/src/exports/runtime.ts +27 -66
- package/src/types/operation-types.ts +19 -9
- package/dist/adapter-hNElNHo4.mjs +0 -60
- package/dist/adapter-hNElNHo4.mjs.map +0 -1
- package/dist/descriptor-meta-RTDzyrae.mjs.map +0 -1
- package/dist/sql-renderer-pEaSP82_.mjs.map +0 -1
- package/dist/types-CfRPdAk8.d.mts.map +0 -1
- package/src/core/json-schema-validator.ts +0 -54
- package/src/core/standard-schema.ts +0 -71
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Column type descriptors for Postgres adapter.
|
|
3
3
|
*
|
|
4
|
-
* These descriptors provide both codecId and nativeType for use in contract authoring.
|
|
5
|
-
* They are derived from the same source of truth as codec definitions and manifests.
|
|
4
|
+
* These descriptors provide both codecId and nativeType for use in contract authoring. They are derived from the same source of truth as codec definitions and manifests.
|
|
6
5
|
*/
|
|
7
6
|
|
|
8
|
-
import type { ColumnTypeDescriptor } from '@prisma-next/
|
|
7
|
+
import type { ColumnTypeDescriptor } from '@prisma-next/framework-components/codec';
|
|
9
8
|
import type { StorageTypeInstance } from '@prisma-next/sql-contract/types';
|
|
10
9
|
import {
|
|
11
10
|
PG_BIT_CODEC_ID,
|
|
12
11
|
PG_BOOL_CODEC_ID,
|
|
12
|
+
PG_BYTEA_CODEC_ID,
|
|
13
13
|
PG_ENUM_CODEC_ID,
|
|
14
14
|
PG_FLOAT4_CODEC_ID,
|
|
15
15
|
PG_FLOAT8_CODEC_ID,
|
|
@@ -29,12 +29,6 @@ import {
|
|
|
29
29
|
SQL_CHAR_CODEC_ID,
|
|
30
30
|
SQL_VARCHAR_CODEC_ID,
|
|
31
31
|
} from '@prisma-next/target-postgres/codec-ids';
|
|
32
|
-
import {
|
|
33
|
-
extractStandardSchemaOutputJsonSchema,
|
|
34
|
-
extractStandardSchemaTypeExpression,
|
|
35
|
-
isStandardSchemaLike,
|
|
36
|
-
type StandardSchemaLike,
|
|
37
|
-
} from '../core/standard-schema';
|
|
38
32
|
|
|
39
33
|
export const textColumn = {
|
|
40
34
|
codecId: PG_TEXT_CODEC_ID,
|
|
@@ -154,6 +148,16 @@ export function varbitColumn(length: number): ColumnTypeDescriptor & {
|
|
|
154
148
|
} as const;
|
|
155
149
|
}
|
|
156
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Postgres `bytea` column descriptor — variable-length binary string.
|
|
153
|
+
*
|
|
154
|
+
* Round-trips as `Uint8Array` on the JS side. The pg wire-protocol text encoding (`\x` followed by hex-encoded bytes, canonical for Postgres ≥ 9.0) and binary encoding are both handled by the underlying driver; the codec only normalizes the JS-side representation to a plain `Uint8Array` view.
|
|
155
|
+
*/
|
|
156
|
+
export const byteaColumn = {
|
|
157
|
+
codecId: PG_BYTEA_CODEC_ID,
|
|
158
|
+
nativeType: 'bytea',
|
|
159
|
+
} as const satisfies ColumnTypeDescriptor;
|
|
160
|
+
|
|
157
161
|
export function intervalColumn(precision?: number): ColumnTypeDescriptor & {
|
|
158
162
|
readonly typeParams?: { readonly precision: number };
|
|
159
163
|
} {
|
|
@@ -164,68 +168,24 @@ export function intervalColumn(precision?: number): ColumnTypeDescriptor & {
|
|
|
164
168
|
} as const;
|
|
165
169
|
}
|
|
166
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Postgres `json` column descriptor — untyped raw JSON.
|
|
173
|
+
*
|
|
174
|
+
* For schema-typed JSON columns, use the per-library extension package (`@prisma-next/extension-arktype-json` ships `arktypeJson(schema)` for arktype). The schema-accepting `json(schema)` / `jsonb(schema)` overloads previously shipped from this module retired in Phase C of the codec-registry-unification project — see spec § AC-7.
|
|
175
|
+
*/
|
|
167
176
|
export const jsonColumn = {
|
|
168
177
|
codecId: PG_JSON_CODEC_ID,
|
|
169
178
|
nativeType: 'json',
|
|
170
179
|
} as const satisfies ColumnTypeDescriptor;
|
|
171
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Postgres `jsonb` column descriptor — untyped raw JSONB. Same retirement note as {@link jsonColumn}.
|
|
183
|
+
*/
|
|
172
184
|
export const jsonbColumn = {
|
|
173
185
|
codecId: PG_JSONB_CODEC_ID,
|
|
174
186
|
nativeType: 'jsonb',
|
|
175
187
|
} as const satisfies ColumnTypeDescriptor;
|
|
176
188
|
|
|
177
|
-
type JsonSchemaTypeParams = {
|
|
178
|
-
readonly schemaJson: Record<string, unknown>;
|
|
179
|
-
readonly type?: string;
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
function createJsonTypeParams(schema: StandardSchemaLike): JsonSchemaTypeParams {
|
|
183
|
-
const outputSchema = extractStandardSchemaOutputJsonSchema(schema);
|
|
184
|
-
if (!outputSchema) {
|
|
185
|
-
throw new Error('JSON schema must expose ~standard.jsonSchema.output()');
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const expression = extractStandardSchemaTypeExpression(schema);
|
|
189
|
-
if (expression) {
|
|
190
|
-
return { schemaJson: outputSchema, type: expression };
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
return { schemaJson: outputSchema };
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function createJsonColumnFactory(
|
|
197
|
-
codecId: string,
|
|
198
|
-
nativeType: string,
|
|
199
|
-
staticDescriptor: ColumnTypeDescriptor,
|
|
200
|
-
) {
|
|
201
|
-
return (schema?: StandardSchemaLike): ColumnTypeDescriptor => {
|
|
202
|
-
if (!schema) {
|
|
203
|
-
return staticDescriptor;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
if (!isStandardSchemaLike(schema)) {
|
|
207
|
-
throw new Error(`${nativeType}(schema) expects a Standard Schema value`);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
return {
|
|
211
|
-
codecId,
|
|
212
|
-
nativeType,
|
|
213
|
-
typeParams: createJsonTypeParams(schema),
|
|
214
|
-
};
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const _json = createJsonColumnFactory(PG_JSON_CODEC_ID, 'json', jsonColumn);
|
|
219
|
-
const _jsonb = createJsonColumnFactory(PG_JSONB_CODEC_ID, 'jsonb', jsonbColumn);
|
|
220
|
-
|
|
221
|
-
export function json(schema?: StandardSchemaLike): ColumnTypeDescriptor {
|
|
222
|
-
return _json(schema);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export function jsonb(schema?: StandardSchemaLike): ColumnTypeDescriptor {
|
|
226
|
-
return _jsonb(schema);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
189
|
export function enumType<const Values extends readonly string[]>(
|
|
230
190
|
name: string,
|
|
231
191
|
values: Values,
|
package/src/exports/control.ts
CHANGED
|
@@ -21,8 +21,8 @@ const postgresAdapterDescriptor: SqlControlAdapterDescriptor<'postgres'> = {
|
|
|
21
21
|
defaultFunctionRegistry: createPostgresDefaultFunctionRegistry(),
|
|
22
22
|
generatorDescriptors: createPostgresMutationDefaultGeneratorDescriptors(),
|
|
23
23
|
},
|
|
24
|
-
create(
|
|
25
|
-
return new PostgresControlAdapter();
|
|
24
|
+
create(stack): SqlControlAdapter<'postgres'> {
|
|
25
|
+
return new PostgresControlAdapter(stack.codecLookup);
|
|
26
26
|
},
|
|
27
27
|
};
|
|
28
28
|
|
|
@@ -31,3 +31,4 @@ export default postgresAdapterDescriptor;
|
|
|
31
31
|
export { parsePostgresDefault } from '@prisma-next/target-postgres/default-normalizer';
|
|
32
32
|
export { normalizeSchemaNativeType } from '@prisma-next/target-postgres/native-type-normalizer';
|
|
33
33
|
export { escapeLiteral, qualifyName, quoteIdentifier, SqlEscapeError };
|
|
34
|
+
export { PostgresControlAdapter } from '../core/control-adapter';
|
package/src/exports/runtime.ts
CHANGED
|
@@ -1,88 +1,49 @@
|
|
|
1
1
|
import type { GeneratedValueSpec } from '@prisma-next/contract/types';
|
|
2
|
+
import { timestampNowRuntimeGenerator } from '@prisma-next/family-sql/runtime';
|
|
3
|
+
import { extractCodecLookup } from '@prisma-next/framework-components/control';
|
|
2
4
|
import type { RuntimeAdapterInstance } from '@prisma-next/framework-components/execution';
|
|
3
5
|
import { builtinGeneratorIds } from '@prisma-next/ids';
|
|
4
6
|
import { generateId } from '@prisma-next/ids/runtime';
|
|
5
|
-
import type { Adapter, AnyQueryAst
|
|
6
|
-
import {
|
|
7
|
-
import
|
|
8
|
-
RuntimeParameterizedCodecDescriptor,
|
|
9
|
-
SqlRuntimeAdapterDescriptor,
|
|
10
|
-
} from '@prisma-next/sql-runtime';
|
|
11
|
-
import { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';
|
|
12
|
-
import { codecDefinitions } from '@prisma-next/target-postgres/codecs';
|
|
13
|
-
import { type as arktype } from 'arktype';
|
|
7
|
+
import type { Adapter, AnyQueryAst } from '@prisma-next/sql-relational-core/ast';
|
|
8
|
+
import type { SqlRuntimeAdapterDescriptor } from '@prisma-next/sql-runtime';
|
|
9
|
+
import { postgresCodecRegistry } from '@prisma-next/target-postgres/codecs';
|
|
14
10
|
import { createPostgresAdapter } from '../core/adapter';
|
|
15
11
|
import { postgresAdapterDescriptorMeta, postgresQueryOperations } from '../core/descriptor-meta';
|
|
16
|
-
import {
|
|
17
|
-
compileJsonSchemaValidator,
|
|
18
|
-
type JsonSchemaValidateFn,
|
|
19
|
-
} from '../core/json-schema-validator';
|
|
20
12
|
import type { PostgresContract, PostgresLoweredStatement } from '../core/types';
|
|
21
13
|
|
|
22
14
|
export interface SqlRuntimeAdapter
|
|
23
15
|
extends RuntimeAdapterInstance<'sql', 'postgres'>,
|
|
24
16
|
Adapter<AnyQueryAst, PostgresContract, PostgresLoweredStatement> {}
|
|
25
17
|
|
|
26
|
-
function createPostgresCodecRegistry(): CodecRegistry {
|
|
27
|
-
const registry = createCodecRegistry();
|
|
28
|
-
for (const definition of Object.values(codecDefinitions)) {
|
|
29
|
-
registry.register(definition.codec);
|
|
30
|
-
}
|
|
31
|
-
return registry;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const jsonTypeParamsSchema = arktype({
|
|
35
|
-
schemaJson: 'object',
|
|
36
|
-
'type?': 'string',
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
/** The inferred type params shape from the arktype schema. */
|
|
40
|
-
type JsonTypeParams = typeof jsonTypeParamsSchema.infer;
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Helper returned by the JSON/JSONB `init` hook.
|
|
44
|
-
* Contains a compiled JSON Schema validate function for runtime conformance checks.
|
|
45
|
-
*/
|
|
46
|
-
export type JsonCodecHelper = { readonly validate: JsonSchemaValidateFn };
|
|
47
|
-
|
|
48
18
|
function createPostgresMutationDefaultGenerators() {
|
|
49
|
-
return
|
|
50
|
-
id
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
19
|
+
return [
|
|
20
|
+
...builtinGeneratorIds.map((id) => ({
|
|
21
|
+
id,
|
|
22
|
+
generate: (params?: Record<string, unknown>) => {
|
|
23
|
+
const spec: GeneratedValueSpec = params ? { id, params } : { id };
|
|
24
|
+
return generateId(spec);
|
|
25
|
+
},
|
|
26
|
+
stability: 'field' as const,
|
|
27
|
+
})),
|
|
28
|
+
timestampNowRuntimeGenerator(),
|
|
29
|
+
];
|
|
56
30
|
}
|
|
57
31
|
|
|
58
|
-
function initJsonCodecHelper(params: JsonTypeParams): JsonCodecHelper {
|
|
59
|
-
return { validate: compileJsonSchemaValidator(params.schemaJson as Record<string, unknown>) };
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const parameterizedCodecDescriptors = [
|
|
63
|
-
{
|
|
64
|
-
codecId: PG_JSON_CODEC_ID,
|
|
65
|
-
paramsSchema: jsonTypeParamsSchema,
|
|
66
|
-
init: initJsonCodecHelper,
|
|
67
|
-
},
|
|
68
|
-
{
|
|
69
|
-
codecId: PG_JSONB_CODEC_ID,
|
|
70
|
-
paramsSchema: jsonTypeParamsSchema,
|
|
71
|
-
init: initJsonCodecHelper,
|
|
72
|
-
},
|
|
73
|
-
] as const satisfies ReadonlyArray<
|
|
74
|
-
RuntimeParameterizedCodecDescriptor<JsonTypeParams, JsonCodecHelper>
|
|
75
|
-
>;
|
|
76
|
-
|
|
77
32
|
const postgresRuntimeAdapterDescriptor: SqlRuntimeAdapterDescriptor<'postgres', SqlRuntimeAdapter> =
|
|
78
33
|
{
|
|
79
34
|
...postgresAdapterDescriptorMeta,
|
|
80
|
-
codecs:
|
|
81
|
-
|
|
82
|
-
queryOperations: () => postgresQueryOperations,
|
|
35
|
+
codecs: () => Array.from(postgresCodecRegistry.values()),
|
|
36
|
+
queryOperations: () => postgresQueryOperations(),
|
|
83
37
|
mutationDefaultGenerators: createPostgresMutationDefaultGenerators,
|
|
84
|
-
create(
|
|
85
|
-
|
|
38
|
+
create(stack): SqlRuntimeAdapter {
|
|
39
|
+
// The runtime `ExecutionStack` does not (yet) carry a pre-assembled `codecLookup` field the way the control `ControlStack` does, so we derive an equivalent lookup here from the stack's component metadata (target + adapter + extension packs) using the same assembly helper that `createControlStack` uses. This keeps the renderer fed with the same codec set on both planes — including extension-contributed codecs like
|
|
40
|
+
// `pg/vector@1` from `@prisma-next/extension-pgvector`.
|
|
41
|
+
const codecLookup = extractCodecLookup([
|
|
42
|
+
stack.target,
|
|
43
|
+
stack.adapter,
|
|
44
|
+
...stack.extensionPacks,
|
|
45
|
+
]);
|
|
46
|
+
return createPostgresAdapter({ codecLookup });
|
|
86
47
|
},
|
|
87
48
|
};
|
|
88
49
|
|
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import type { SqlQueryOperationTypes } from '@prisma-next/sql-contract/types';
|
|
2
|
+
import type {
|
|
3
|
+
CodecExpression,
|
|
4
|
+
Expression,
|
|
5
|
+
TraitExpression,
|
|
6
|
+
} from '@prisma-next/sql-relational-core/expression';
|
|
2
7
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
type CodecTypesBase = Record<string, { readonly input: unknown; readonly output: unknown }>;
|
|
9
|
+
|
|
10
|
+
export type QueryOperationTypes<CT extends CodecTypesBase> = SqlQueryOperationTypes<
|
|
11
|
+
CT,
|
|
12
|
+
{
|
|
13
|
+
readonly ilike: {
|
|
14
|
+
readonly self: { readonly traits: readonly ['textual'] };
|
|
15
|
+
readonly impl: (
|
|
16
|
+
self: TraitExpression<readonly ['textual'], false, CT>,
|
|
17
|
+
pattern: CodecExpression<'pg/text@1', false, CT>,
|
|
18
|
+
) => Expression<{ codecId: 'pg/bool@1'; nullable: false }>;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
>;
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { t as renderLoweredSql } from "./sql-renderer-pEaSP82_.mjs";
|
|
2
|
-
import { createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
|
|
3
|
-
import { codecDefinitions } from "@prisma-next/target-postgres/codecs";
|
|
4
|
-
import { ifDefined } from "@prisma-next/utils/defined";
|
|
5
|
-
|
|
6
|
-
//#region src/core/adapter.ts
|
|
7
|
-
const defaultCapabilities = Object.freeze({
|
|
8
|
-
postgres: {
|
|
9
|
-
orderBy: true,
|
|
10
|
-
limit: true,
|
|
11
|
-
lateral: true,
|
|
12
|
-
jsonAgg: true,
|
|
13
|
-
returning: true
|
|
14
|
-
},
|
|
15
|
-
sql: {
|
|
16
|
-
enums: true,
|
|
17
|
-
returning: true,
|
|
18
|
-
defaultInInsert: true
|
|
19
|
-
}
|
|
20
|
-
});
|
|
21
|
-
const parameterizedCodecs = Object.values(codecDefinitions).map((definition) => definition.codec).filter((codec) => codec.paramsSchema !== void 0).map((codec) => Object.freeze({
|
|
22
|
-
codecId: codec.id,
|
|
23
|
-
paramsSchema: codec.paramsSchema,
|
|
24
|
-
...ifDefined("init", codec.init)
|
|
25
|
-
}));
|
|
26
|
-
var PostgresAdapterImpl = class {
|
|
27
|
-
familyId = "sql";
|
|
28
|
-
targetId = "postgres";
|
|
29
|
-
profile;
|
|
30
|
-
codecRegistry = (() => {
|
|
31
|
-
const registry = createCodecRegistry();
|
|
32
|
-
for (const definition of Object.values(codecDefinitions)) registry.register(definition.codec);
|
|
33
|
-
return registry;
|
|
34
|
-
})();
|
|
35
|
-
constructor(options) {
|
|
36
|
-
this.profile = Object.freeze({
|
|
37
|
-
id: options?.profileId ?? "postgres/default@1",
|
|
38
|
-
target: "postgres",
|
|
39
|
-
capabilities: defaultCapabilities,
|
|
40
|
-
codecs: () => this.codecRegistry,
|
|
41
|
-
readMarkerStatement: () => ({
|
|
42
|
-
sql: "select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1",
|
|
43
|
-
params: [1]
|
|
44
|
-
})
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
parameterizedCodecs() {
|
|
48
|
-
return parameterizedCodecs;
|
|
49
|
-
}
|
|
50
|
-
lower(ast, context) {
|
|
51
|
-
return renderLoweredSql(ast, context.contract);
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
function createPostgresAdapter(options) {
|
|
55
|
-
return Object.freeze(new PostgresAdapterImpl(options));
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
//#endregion
|
|
59
|
-
export { createPostgresAdapter as t };
|
|
60
|
-
//# sourceMappingURL=adapter-hNElNHo4.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-hNElNHo4.mjs","names":["parameterizedCodecs: ReadonlyArray<CodecParamsDescriptor>"],"sources":["../src/core/adapter.ts"],"sourcesContent":["import {\n type Adapter,\n type AdapterProfile,\n type AnyQueryAst,\n type CodecParamsDescriptor,\n createCodecRegistry,\n type LowererContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { renderLoweredSql } from './sql-renderer';\nimport type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';\n\nconst defaultCapabilities = Object.freeze({\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n sql: {\n enums: true,\n returning: true,\n defaultInInsert: true,\n },\n});\n\ntype AdapterCodec = (typeof codecDefinitions)[keyof typeof codecDefinitions]['codec'];\ntype ParameterizedCodec = AdapterCodec & {\n readonly paramsSchema: NonNullable<AdapterCodec['paramsSchema']>;\n};\n\nconst parameterizedCodecs: ReadonlyArray<CodecParamsDescriptor> = Object.values(codecDefinitions)\n .map((definition) => definition.codec)\n .filter((codec): codec is ParameterizedCodec => codec.paramsSchema !== undefined)\n .map((codec) =>\n Object.freeze({\n codecId: codec.id,\n paramsSchema: codec.paramsSchema,\n ...ifDefined('init', codec.init),\n }),\n );\n\nclass PostgresAdapterImpl\n implements Adapter<AnyQueryAst, PostgresContract, PostgresLoweredStatement>\n{\n // These fields make the adapter instance structurally compatible with\n // RuntimeAdapterInstance<'sql', 'postgres'> without introducing a runtime-plane dependency.\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n\n readonly profile: AdapterProfile<'postgres'>;\n private readonly codecRegistry = (() => {\n const registry = createCodecRegistry();\n for (const definition of Object.values(codecDefinitions)) {\n registry.register(definition.codec);\n }\n return registry;\n })();\n\n constructor(options?: PostgresAdapterOptions) {\n this.profile = Object.freeze({\n id: options?.profileId ?? 'postgres/default@1',\n target: 'postgres',\n capabilities: defaultCapabilities,\n codecs: () => this.codecRegistry,\n readMarkerStatement: () => ({\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\n parameterizedCodecs(): ReadonlyArray<CodecParamsDescriptor> {\n return parameterizedCodecs;\n }\n\n lower(ast: AnyQueryAst, context: LowererContext<PostgresContract>): PostgresLoweredStatement {\n return renderLoweredSql(ast, context.contract);\n }\n}\n\nexport function createPostgresAdapter(options?: PostgresAdapterOptions) {\n return Object.freeze(new PostgresAdapterImpl(options));\n}\n"],"mappings":";;;;;;AAaA,MAAM,sBAAsB,OAAO,OAAO;CACxC,UAAU;EACR,SAAS;EACT,OAAO;EACP,SAAS;EACT,SAAS;EACT,WAAW;EACZ;CACD,KAAK;EACH,OAAO;EACP,WAAW;EACX,iBAAiB;EAClB;CACF,CAAC;AAOF,MAAMA,sBAA4D,OAAO,OAAO,iBAAiB,CAC9F,KAAK,eAAe,WAAW,MAAM,CACrC,QAAQ,UAAuC,MAAM,iBAAiB,OAAU,CAChF,KAAK,UACJ,OAAO,OAAO;CACZ,SAAS,MAAM;CACf,cAAc,MAAM;CACpB,GAAG,UAAU,QAAQ,MAAM,KAAK;CACjC,CAAC,CACH;AAEH,IAAM,sBAAN,MAEA;CAGE,AAAS,WAAW;CACpB,AAAS,WAAW;CAEpB,AAAS;CACT,AAAiB,uBAAuB;EACtC,MAAM,WAAW,qBAAqB;AACtC,OAAK,MAAM,cAAc,OAAO,OAAO,iBAAiB,CACtD,UAAS,SAAS,WAAW,MAAM;AAErC,SAAO;KACL;CAEJ,YAAY,SAAkC;AAC5C,OAAK,UAAU,OAAO,OAAO;GAC3B,IAAI,SAAS,aAAa;GAC1B,QAAQ;GACR,cAAc;GACd,cAAc,KAAK;GACnB,4BAA4B;IAC1B,KAAK;IACL,QAAQ,CAAC,EAAE;IACZ;GACF,CAAC;;CAGJ,sBAA4D;AAC1D,SAAO;;CAGT,MAAM,KAAkB,SAAqE;AAC3F,SAAO,iBAAiB,KAAK,QAAQ,SAAS;;;AAIlD,SAAgB,sBAAsB,SAAkC;AACtE,QAAO,OAAO,OAAO,IAAI,oBAAoB,QAAQ,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"descriptor-meta-RTDzyrae.mjs","names":["result: string[]","operations: SqlMigrationPlanOperation<unknown>[]","columns: Array<{ table: string; column: string }>","result: Array<{ table: string; column: string }>","pgEnumControlHooks: CodecControlHooks","types: Record<string, StorageTypeInstance>","lengthHooks: CodecControlHooks","precisionHooks: CodecControlHooks","numericHooks: CodecControlHooks","identityHooks: CodecControlHooks","postgresQueryOperations: readonly SqlOperationDescriptor[]"],"sources":["../src/core/enum-control-hooks.ts","../src/core/descriptor-meta.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport { arraysEqual } from '@prisma-next/family-sql/schema-verify';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { PG_ENUM_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';\nimport {\n escapeLiteral,\n qualifyName,\n quoteIdentifier,\n validateEnumValueLength,\n} from '@prisma-next/target-postgres/sql-utils';\n\n/**\n * Postgres enum control hooks.\n *\n * - Plans enum type operations for migrations\n * - Verifies enum types in schema IR\n * - Introspects enum types from the database\n */\ntype EnumRow = {\n schema_name: string;\n type_name: string;\n values: string[];\n};\n\ntype EnumDiff =\n | { kind: 'unchanged' }\n | { kind: 'add_values'; values: readonly string[] }\n | { kind: 'rebuild'; removedValues: readonly string[] };\n\n// ============================================================================\n// Introspection SQL\n// ============================================================================\n\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n\n// ============================================================================\n// Schema Helpers (Simplified)\n// ============================================================================\n\n/**\n * Type guard for string arrays. Used for runtime validation of introspected data.\n */\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Parses a PostgreSQL array value into a JavaScript string array.\n *\n * PostgreSQL's `pg` library may return `array_agg` results either as:\n * - A JavaScript array (when type parsers are configured)\n * - A string in PostgreSQL array literal format: `{value1,value2,...}`\n *\n * Handles PostgreSQL's quoting rules for array elements:\n * - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n * - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n *\n * @param value - The value to parse (array or PostgreSQL array string)\n * @returns A string array, or null if the value cannot be parsed\n */\nexport function parsePostgresArray(value: unknown): string[] | null {\n if (isStringArray(value)) {\n return value;\n }\n if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {\n const inner = value.slice(1, -1);\n if (inner === '') {\n return [];\n }\n return parseArrayElements(inner);\n }\n return null;\n}\n\nfunction parseArrayElements(input: string): string[] {\n const result: string[] = [];\n let i = 0;\n while (i < input.length) {\n if (input[i] === ',') {\n i++;\n continue;\n }\n if (input[i] === '\"') {\n i++;\n let element = '';\n while (i < input.length && input[i] !== '\"') {\n if (input[i] === '\\\\' && i + 1 < input.length) {\n i++;\n element += input[i];\n } else {\n element += input[i];\n }\n i++;\n }\n i++;\n result.push(element);\n } else {\n const nextComma = input.indexOf(',', i);\n if (nextComma === -1) {\n result.push(input.slice(i).trim());\n i = input.length;\n } else {\n result.push(input.slice(i, nextComma).trim());\n i = nextComma;\n }\n }\n }\n return result;\n}\n\n/**\n * Extracts enum values from a StorageTypeInstance.\n * Returns null if values are missing or invalid.\n */\nfunction getEnumValues(typeInstance: StorageTypeInstance): readonly string[] | null {\n const values = typeInstance.typeParams?.['values'];\n return isStringArray(values) ? values : null;\n}\n\n/**\n * Reads existing enum values from the schema IR for a given native type.\n * Uses optional chaining to simplify navigation through the annotations structure.\n */\nfunction readExistingEnumValues(schema: SqlSchemaIR, nativeType: string): readonly string[] | null {\n const storageTypes = (schema.annotations?.['pg'] as Record<string, unknown> | undefined)?.[\n 'storageTypes'\n ] as Record<string, StorageTypeInstance> | undefined;\n\n const existing = storageTypes?.[nativeType];\n if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {\n return null;\n }\n return getEnumValues(existing);\n}\n\n/**\n * Determines what changes are needed to transform existing enum values to desired values.\n *\n * Returns one of:\n * - `unchanged`: No changes needed, values match exactly\n * - `add_values`: New values can be safely appended (PostgreSQL supports this)\n * - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n *\n * Note: PostgreSQL enums can only have values added (not removed or reordered) without\n * a full type rebuild involving temp type creation and column migration.\n *\n * @param existing - Current enum values in the database\n * @param desired - Target enum values from the contract\n * @returns The type of change required\n */\nfunction determineEnumDiff(existing: readonly string[], desired: readonly string[]): EnumDiff {\n if (arraysEqual(existing, desired)) {\n return { kind: 'unchanged' };\n }\n\n // Use Sets for O(1) lookups instead of O(n) array.includes()\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\n\n const missingValues = desired.filter((value) => !existingSet.has(value));\n const removedValues = existing.filter((value) => !desiredSet.has(value));\n const orderMismatch =\n missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\n if (removedValues.length > 0 || orderMismatch) {\n return { kind: 'rebuild', removedValues };\n }\n\n return { kind: 'add_values', values: missingValues };\n}\n\n// ============================================================================\n// SQL Helpers\n// ============================================================================\n\nfunction enumTypeExistsCheck(schemaName: string, typeName: string, exists = true): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\n\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildCreateEnumOperation(\n typeName: string,\n nativeType: string,\n schemaName: string,\n values: readonly string[],\n): SqlMigrationPlanOperation<unknown> {\n // Validate all enum values don't exceed PostgreSQL's label length limit\n for (const value of values) {\n validateEnumValueLength(value, typeName);\n }\n const literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(', ');\n const qualifiedType = qualifyName(schemaName, nativeType);\n return {\n id: `type.${typeName}`,\n label: `Create type ${typeName}`,\n summary: `Creates enum type ${typeName}`,\n operationClass: 'additive',\n target: { id: 'postgres' },\n precheck: [\n {\n description: `ensure type \"${nativeType}\" does not exist`,\n sql: enumTypeExistsCheck(schemaName, nativeType, false),\n },\n ],\n execute: [\n {\n description: `create type \"${nativeType}\"`,\n sql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`,\n },\n ],\n postcheck: [\n {\n description: `verify type \"${nativeType}\" exists`,\n sql: enumTypeExistsCheck(schemaName, nativeType),\n },\n ],\n };\n}\n\n/**\n * Computes the optimal position for inserting a new enum value to maintain\n * the desired order relative to existing values.\n *\n * PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n * This function finds the best reference value by:\n * 1. Looking for the nearest preceding value that already exists\n * 2. Falling back to the nearest following value if no preceding exists\n * 3. Defaulting to end-of-list if no reference is found\n *\n * @param options.desired - The target ordered list of all enum values\n * @param options.desiredIndex - Index of the value being inserted in the desired list\n * @param options.current - Current list of enum values (being built up incrementally)\n * @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n */\nfunction computeInsertPosition(options: {\n desired: readonly string[];\n desiredIndex: number;\n current: readonly string[];\n}): { clause: string; insertAt: number } {\n const { desired, desiredIndex, current } = options;\n const currentSet = new Set(current);\n const previous = desired\n .slice(0, desiredIndex)\n .reverse()\n .find((candidate) => currentSet.has(candidate));\n const next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n const clause = previous\n ? ` AFTER '${escapeLiteral(previous)}'`\n : next\n ? ` BEFORE '${escapeLiteral(next)}'`\n : '';\n const insertAt = previous\n ? current.indexOf(previous) + 1\n : next\n ? current.indexOf(next)\n : current.length;\n\n return { clause, insertAt };\n}\n\n/**\n * Builds operations to add new enum values to an existing PostgreSQL enum type.\n *\n * Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n * Values are inserted in the correct order using BEFORE/AFTER positioning to match\n * the desired final order.\n *\n * This is a safe, non-destructive operation - existing data is not affected.\n *\n * @param options.typeName - Contract-level type name (e.g., 'Role')\n * @param options.nativeType - PostgreSQL type name (e.g., 'role')\n * @param options.schemaName - PostgreSQL schema (e.g., 'public')\n * @param options.desired - Target ordered list of all enum values\n * @param options.existing - Current enum values in the database\n * @returns Array of migration operations to add each missing value\n */\nfunction buildAddValueOperations(options: {\n typeName: string;\n nativeType: string;\n schemaName: string;\n desired: readonly string[];\n existing: readonly string[];\n}): SqlMigrationPlanOperation<unknown>[] {\n const { typeName, nativeType, schemaName } = options;\n const current = [...options.existing];\n const currentSet = new Set(current);\n const operations: SqlMigrationPlanOperation<unknown>[] = [];\n for (let index = 0; index < options.desired.length; index += 1) {\n const value = options.desired[index];\n if (value === undefined) {\n continue;\n }\n if (currentSet.has(value)) {\n continue;\n }\n // Validate the new value doesn't exceed PostgreSQL's label length limit\n validateEnumValueLength(value, typeName);\n const { clause, insertAt } = computeInsertPosition({\n desired: options.desired,\n desiredIndex: index,\n current,\n });\n // Use IF NOT EXISTS for idempotency - safe to re-run after partial failures.\n // Supported in PostgreSQL 9.3+, and we require PostgreSQL 12+.\n operations.push({\n id: `type.${typeName}.value.${value}`,\n label: `Add value ${value} to ${typeName}`,\n summary: `Adds enum value ${value} to ${typeName}`,\n operationClass: 'widening',\n target: { id: 'postgres' },\n precheck: [],\n execute: [\n {\n description: `add value \"${value}\" if not exists`,\n sql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(\n value,\n )}'${clause}`,\n },\n ],\n postcheck: [],\n });\n current.splice(insertAt, 0, value);\n currentSet.add(value);\n }\n return operations;\n}\n\n/**\n * Collects columns using the enum type from the contract (desired state).\n * Used for type-safe reference tracking.\n */\nfunction collectEnumColumnsFromContract(\n contract: Contract<SqlStorage>,\n typeName: string,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const columns: Array<{ table: string; column: string }> = [];\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (\n column.typeRef === typeName ||\n (column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID)\n ) {\n columns.push({ table: tableName, column: columnName });\n }\n }\n }\n return columns;\n}\n\n/**\n * Collects columns using the enum type from the schema IR (live database state).\n * This ensures we find ALL dependent columns, including those added outside the contract\n * (e.g., manual DDL), which is critical for safe enum rebuild operations.\n */\nfunction collectEnumColumnsFromSchema(\n schema: SqlSchemaIR,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const columns: Array<{ table: string; column: string }> = [];\n for (const [tableName, table] of Object.entries(schema.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n // Match by nativeType since schema IR doesn't have codecId/typeRef\n if (column.nativeType === nativeType) {\n columns.push({ table: tableName, column: columnName });\n }\n }\n }\n return columns;\n}\n\n/**\n * Collects all columns using the enum type from both contract AND live database.\n * Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n *\n * This is critical for data integrity: if a column exists in the database using\n * this enum but is not in the contract (e.g., added via manual DDL), we must\n * still migrate it to avoid DROP TYPE failures.\n */\nfunction collectAllEnumColumns(\n contract: Contract<SqlStorage>,\n schema: SqlSchemaIR,\n typeName: string,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n const schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\n // Merge and deduplicate using a Set of \"table.column\" keys\n const seen = new Set<string>();\n const result: Array<{ table: string; column: string }> = [];\n\n for (const col of [...contractColumns, ...schemaColumns]) {\n const key = `${col.table}.${col.column}`;\n if (!seen.has(key)) {\n seen.add(key);\n result.push(col);\n }\n }\n\n // Sort for deterministic operation order\n return result.sort((a, b) => {\n const tableCompare = a.table.localeCompare(b.table);\n return tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n });\n}\n\n/**\n * Builds a SQL check to verify a column's type matches an expected type.\n */\nfunction columnTypeCheck(options: {\n schemaName: string;\n tableName: string;\n columnName: string;\n expectedType: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = '__pn_rebuild';\n\n/**\n * Builds an SQL check to verify no rows contain any of the removed enum values.\n * This prevents data loss during enum rebuild operations.\n *\n * @param schemaName - PostgreSQL schema name\n * @param tableName - Table containing the enum column\n * @param columnName - Column using the enum type\n * @param removedValues - Array of enum values being removed\n * @returns SQL query that returns true if no rows contain removed values\n */\nfunction noRemovedValuesExistCheck(\n schemaName: string,\n tableName: string,\n columnName: string,\n removedValues: readonly string[],\n): string {\n if (removedValues.length === 0) {\n // No values being removed, always passes\n return 'SELECT true';\n }\n const valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n return `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n\n/**\n * Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n *\n * This is required when:\n * - Enum values are removed (PostgreSQL doesn't support direct removal)\n * - Enum values are reordered (PostgreSQL doesn't support reordering)\n *\n * The operation:\n * 1. Creates a new enum type with the desired values (temp name)\n * 2. Migrates all columns to use the new type via text cast\n * 3. Drops the original type\n * 4. Renames the temp type to the original name\n *\n * IMPORTANT: If values are being removed and data exists using those values,\n * the operation will fail at the precheck stage with a clear error message.\n * This prevents silent data loss.\n *\n * @param options.typeName - Contract-level type name\n * @param options.nativeType - PostgreSQL type name\n * @param options.schemaName - PostgreSQL schema\n * @param options.values - Desired final enum values\n * @param options.removedValues - Values being removed (for data loss checks)\n * @param options.contract - Full contract for column discovery\n * @param options.schema - Current schema IR for column discovery\n * @returns Migration operation for full enum rebuild\n */\nfunction buildRecreateEnumOperation(options: {\n typeName: string;\n nativeType: string;\n schemaName: string;\n values: readonly string[];\n removedValues: readonly string[];\n contract: Contract<SqlStorage>;\n schema: SqlSchemaIR;\n}): SqlMigrationPlanOperation<unknown> {\n const tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\n // Validate temp type name length won't exceed PostgreSQL's 63-character limit.\n // If it would, PostgreSQL silently truncates which could cause conflicts.\n if (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n const maxBaseLength = MAX_IDENTIFIER_LENGTH - REBUILD_SUFFIX.length;\n throw new Error(\n `Enum type name \"${options.nativeType}\" is too long for rebuild operation. ` +\n `Maximum length is ${maxBaseLength} characters (type name + \"${REBUILD_SUFFIX}\" suffix ` +\n `must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`,\n );\n }\n\n const qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n const qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n const literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(', ');\n\n // CRITICAL: Collect columns from BOTH contract AND live database.\n // This ensures we migrate ALL dependent columns, including those added\n // outside of Prisma Next (e.g., manual DDL). Without this, DROP TYPE\n // would fail if the database has columns not tracked in the contract.\n const columnRefs = collectAllEnumColumns(\n options.contract,\n options.schema,\n options.typeName,\n options.nativeType,\n );\n\n const alterColumns = columnRefs.map((ref) => ({\n description: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n sql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`,\n }));\n\n // Build postchecks to verify:\n // 1. The final type exists with the correct name\n // 2. The temp type was cleaned up (renamed away)\n // 3. All migrated columns now reference the final type\n const postchecks = [\n {\n description: `verify type \"${options.nativeType}\" exists`,\n sql: enumTypeExistsCheck(options.schemaName, options.nativeType),\n },\n {\n description: `verify temp type \"${tempTypeName}\" was removed`,\n sql: enumTypeExistsCheck(options.schemaName, tempTypeName, false),\n },\n // Verify each column was successfully migrated to the final type\n ...columnRefs.map((ref) => ({\n description: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n sql: columnTypeCheck({\n schemaName: options.schemaName,\n tableName: ref.table,\n columnName: ref.column,\n expectedType: options.nativeType,\n }),\n })),\n ];\n\n return {\n id: `type.${options.typeName}.rebuild`,\n label: `Rebuild type ${options.typeName}`,\n summary: `Recreates enum type ${options.typeName} with updated values`,\n operationClass: 'destructive',\n target: { id: 'postgres' },\n precheck: [\n {\n description: `ensure type \"${options.nativeType}\" exists`,\n sql: enumTypeExistsCheck(options.schemaName, options.nativeType),\n },\n // Note: We don't precheck that temp type doesn't exist because we handle\n // orphaned temp types in the execute step below.\n\n // CRITICAL: If values are being removed, verify no data exists using those values.\n // This prevents silent data loss during the rebuild - the USING cast would fail\n // at runtime if rows contain values that don't exist in the new enum.\n ...(options.removedValues.length > 0\n ? columnRefs.map((ref) => ({\n description: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(', ')})`,\n sql: noRemovedValuesExistCheck(\n options.schemaName,\n ref.table,\n ref.column,\n options.removedValues,\n ),\n }))\n : []),\n ],\n execute: [\n // Clean up any orphaned temp type from a previous failed migration.\n // This makes the operation recoverable without manual intervention.\n // DROP TYPE IF EXISTS is safe - it's a no-op if the type doesn't exist.\n {\n description: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n sql: `DROP TYPE IF EXISTS ${qualifiedTemp}`,\n },\n {\n description: `create temp type \"${tempTypeName}\"`,\n sql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`,\n },\n ...alterColumns,\n {\n description: `drop type \"${options.nativeType}\"`,\n sql: `DROP TYPE ${qualifiedOriginal}`,\n },\n {\n description: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n sql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`,\n },\n ],\n postcheck: postchecks,\n };\n}\n\n// ============================================================================\n// Codec Control Hooks\n// ============================================================================\n\n/**\n * Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n */\nexport const pgEnumControlHooks: CodecControlHooks = {\n planTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n const desired = getEnumValues(typeInstance);\n if (!desired || desired.length === 0) {\n return { operations: [] };\n }\n\n const schemaNamespace = schemaName ?? 'public';\n const existing = readExistingEnumValues(schema, typeInstance.nativeType);\n if (!existing) {\n return {\n operations: [\n buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired),\n ],\n };\n }\n\n const diff = determineEnumDiff(existing, desired);\n if (diff.kind === 'unchanged') {\n return { operations: [] };\n }\n\n if (diff.kind === 'rebuild') {\n return {\n operations: [\n buildRecreateEnumOperation({\n typeName,\n nativeType: typeInstance.nativeType,\n schemaName: schemaNamespace,\n values: desired,\n removedValues: diff.removedValues,\n contract,\n schema,\n }),\n ],\n };\n }\n\n return {\n operations: buildAddValueOperations({\n typeName,\n nativeType: typeInstance.nativeType,\n schemaName: schemaNamespace,\n desired,\n existing,\n }),\n };\n },\n verifyType: ({ typeName, typeInstance, schema }) => {\n const desired = getEnumValues(typeInstance);\n if (!desired) {\n return [];\n }\n const existing = readExistingEnumValues(schema, typeInstance.nativeType);\n if (!existing) {\n return [\n {\n kind: 'type_missing',\n typeName,\n message: `Type \"${typeName}\" is missing from database`,\n },\n ];\n }\n const diff = determineEnumDiff(existing, desired);\n if (diff.kind === 'unchanged') return [];\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\n const addedValues = desired.filter((v) => !existingSet.has(v));\n const removedValues = existing.filter((v) => !desiredSet.has(v));\n return [\n {\n kind: 'enum_values_changed' as const,\n typeName,\n addedValues,\n removedValues,\n message:\n diff.kind === 'add_values'\n ? `Enum type \"${typeName}\" needs new values: ${addedValues.join(', ')}`\n : `Enum type \"${typeName}\" values changed (requires rebuild): +[${addedValues.join(', ')}] -[${removedValues.join(', ')}]`,\n },\n ];\n },\n introspectTypes: async ({ driver, schemaName }) => {\n const namespace = schemaName ?? 'public';\n const result = await driver.query<EnumRow>(ENUM_INTROSPECT_QUERY, [namespace]);\n const types: Record<string, StorageTypeInstance> = {};\n for (const row of result.rows) {\n const values = parsePostgresArray(row.values);\n if (!values) {\n throw new Error(\n `Failed to parse enum values for type \"${row.type_name}\": ` +\n `unexpected format: ${JSON.stringify(row.values)}`,\n );\n }\n types[row.type_name] = {\n codecId: PG_ENUM_CODEC_ID,\n nativeType: row.type_name,\n typeParams: { values },\n };\n }\n return types;\n },\n};\n","import type { CodecControlHooks, ExpandNativeTypeInput } from '@prisma-next/family-sql/control';\nimport type { SqlOperationDescriptor } from '@prisma-next/sql-operations';\nimport {\n PG_BIT_CODEC_ID,\n PG_BOOL_CODEC_ID,\n PG_CHAR_CODEC_ID,\n PG_ENUM_CODEC_ID,\n PG_FLOAT_CODEC_ID,\n PG_FLOAT4_CODEC_ID,\n PG_FLOAT8_CODEC_ID,\n PG_INT_CODEC_ID,\n PG_INT2_CODEC_ID,\n PG_INT4_CODEC_ID,\n PG_INT8_CODEC_ID,\n PG_INTERVAL_CODEC_ID,\n PG_JSON_CODEC_ID,\n PG_JSONB_CODEC_ID,\n PG_NUMERIC_CODEC_ID,\n PG_TEXT_CODEC_ID,\n PG_TIME_CODEC_ID,\n PG_TIMESTAMP_CODEC_ID,\n PG_TIMESTAMPTZ_CODEC_ID,\n PG_TIMETZ_CODEC_ID,\n PG_VARBIT_CODEC_ID,\n PG_VARCHAR_CODEC_ID,\n SQL_CHAR_CODEC_ID,\n SQL_FLOAT_CODEC_ID,\n SQL_INT_CODEC_ID,\n SQL_TEXT_CODEC_ID,\n SQL_TIMESTAMP_CODEC_ID,\n SQL_VARCHAR_CODEC_ID,\n} from '@prisma-next/target-postgres/codec-ids';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\nimport { pgEnumControlHooks } from './enum-control-hooks';\n\n// ============================================================================\n// Helper functions for reducing boilerplate\n// ============================================================================\n\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named: string) =>\n ({\n package: '@prisma-next/target-postgres/codec-types',\n named,\n alias: named,\n }) as const;\n\nfunction isPositiveInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value >= 0\n );\n}\n\nfunction expandLength({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('length' in typeParams)) {\n return nativeType;\n }\n const length = typeParams['length'];\n if (!isPositiveInteger(length)) {\n throw new Error(\n `Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`,\n );\n }\n return `${nativeType}(${length})`;\n}\n\nfunction expandPrecision({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('precision' in typeParams)) {\n return nativeType;\n }\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n return `${nativeType}(${precision})`;\n}\n\nfunction expandNumeric({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n const hasPrecision = typeParams && 'precision' in typeParams;\n const hasScale = typeParams && 'scale' in typeParams;\n\n if (!hasPrecision && !hasScale) {\n return nativeType;\n }\n\n if (!hasPrecision && hasScale) {\n throw new Error(\n `Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`,\n );\n }\n\n if (hasPrecision) {\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n if (hasScale) {\n const scale = typeParams['scale'];\n if (!isNonNegativeInteger(scale)) {\n throw new Error(\n `Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`,\n );\n }\n return `${nativeType}(${precision},${scale})`;\n }\n return `${nativeType}(${precision})`;\n }\n\n return nativeType;\n}\n\nconst lengthHooks: CodecControlHooks = { expandNativeType: expandLength };\nconst precisionHooks: CodecControlHooks = { expandNativeType: expandPrecision };\nconst numericHooks: CodecControlHooks = { expandNativeType: expandNumeric };\nconst identityHooks: CodecControlHooks = { expandNativeType: ({ nativeType }) => nativeType };\n\n// ============================================================================\n// Descriptor metadata\n// ============================================================================\n\nexport const postgresQueryOperations: readonly SqlOperationDescriptor[] = [\n {\n method: 'ilike',\n args: [\n { traits: ['textual'], nullable: false },\n { codecId: PG_TEXT_CODEC_ID, nullable: false },\n ],\n returns: { codecId: PG_BOOL_CODEC_ID, nullable: false },\n lowering: { targetFamily: 'sql', strategy: 'infix', template: '{{self}} ILIKE {{arg0}}' },\n },\n];\n\nexport const postgresAdapterDescriptorMeta = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n sql: {\n enums: true,\n returning: true,\n defaultInInsert: true,\n },\n },\n types: {\n codecTypes: {\n codecInstances: Object.values(codecDefinitions).map((def) => def.codec),\n import: {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'CodecTypes',\n alias: 'PgTypes',\n },\n typeImports: [\n {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'JsonValue',\n alias: 'JsonValue',\n },\n codecTypeImport('Char'),\n codecTypeImport('Varchar'),\n codecTypeImport('Numeric'),\n codecTypeImport('Bit'),\n codecTypeImport('VarBit'),\n codecTypeImport('Timestamp'),\n codecTypeImport('Timestamptz'),\n codecTypeImport('Time'),\n codecTypeImport('Timetz'),\n codecTypeImport('Interval'),\n ],\n controlPlaneHooks: {\n [SQL_CHAR_CODEC_ID]: lengthHooks,\n [SQL_VARCHAR_CODEC_ID]: lengthHooks,\n [SQL_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_CHAR_CODEC_ID]: lengthHooks,\n [PG_VARCHAR_CODEC_ID]: lengthHooks,\n [PG_NUMERIC_CODEC_ID]: numericHooks,\n [PG_BIT_CODEC_ID]: lengthHooks,\n [PG_VARBIT_CODEC_ID]: lengthHooks,\n [PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n [PG_TIME_CODEC_ID]: precisionHooks,\n [PG_TIMETZ_CODEC_ID]: precisionHooks,\n [PG_INTERVAL_CODEC_ID]: precisionHooks,\n [PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n [PG_JSON_CODEC_ID]: identityHooks,\n [PG_JSONB_CODEC_ID]: identityHooks,\n },\n },\n storage: [\n { typeId: PG_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: SQL_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: SQL_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: SQL_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n {\n typeId: SQL_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n { typeId: PG_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: PG_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: PG_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_INT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_INT2_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int2' },\n { typeId: PG_INT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int8' },\n { typeId: PG_FLOAT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float4' },\n { typeId: PG_FLOAT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_NUMERIC_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'numeric' },\n {\n typeId: PG_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n {\n typeId: PG_TIMESTAMPTZ_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamptz',\n },\n { typeId: PG_TIME_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'time' },\n { typeId: PG_TIMETZ_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'timetz' },\n { typeId: PG_BOOL_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bool' },\n { typeId: PG_BIT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bit' },\n {\n typeId: PG_VARBIT_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'bit varying',\n },\n {\n typeId: PG_INTERVAL_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'interval',\n },\n { typeId: PG_JSON_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'json' },\n { typeId: PG_JSONB_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'jsonb' },\n ],\n queryOperationTypes: {\n import: {\n package: '@prisma-next/adapter-postgres/operation-types',\n named: 'QueryOperationTypes',\n alias: 'PgAdapterQueryOps',\n },\n },\n },\n} as const;\n"],"mappings":";;;;;;AAmCA,MAAM,wBAAwB;;;;;;;;;;;;;;;AAoB9B,SAAS,cAAc,OAAmC;AACxD,QAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,OAAO,UAAU,OAAO,UAAU,SAAS;;;;;;;;;;;;;;;;AAiBlF,SAAgB,mBAAmB,OAAiC;AAClE,KAAI,cAAc,MAAM,CACtB,QAAO;AAET,KAAI,OAAO,UAAU,YAAY,MAAM,WAAW,IAAI,IAAI,MAAM,SAAS,IAAI,EAAE;EAC7E,MAAM,QAAQ,MAAM,MAAM,GAAG,GAAG;AAChC,MAAI,UAAU,GACZ,QAAO,EAAE;AAEX,SAAO,mBAAmB,MAAM;;AAElC,QAAO;;AAGT,SAAS,mBAAmB,OAAyB;CACnD,MAAMA,SAAmB,EAAE;CAC3B,IAAI,IAAI;AACR,QAAO,IAAI,MAAM,QAAQ;AACvB,MAAI,MAAM,OAAO,KAAK;AACpB;AACA;;AAEF,MAAI,MAAM,OAAO,MAAK;AACpB;GACA,IAAI,UAAU;AACd,UAAO,IAAI,MAAM,UAAU,MAAM,OAAO,MAAK;AAC3C,QAAI,MAAM,OAAO,QAAQ,IAAI,IAAI,MAAM,QAAQ;AAC7C;AACA,gBAAW,MAAM;UAEjB,YAAW,MAAM;AAEnB;;AAEF;AACA,UAAO,KAAK,QAAQ;SACf;GACL,MAAM,YAAY,MAAM,QAAQ,KAAK,EAAE;AACvC,OAAI,cAAc,IAAI;AACpB,WAAO,KAAK,MAAM,MAAM,EAAE,CAAC,MAAM,CAAC;AAClC,QAAI,MAAM;UACL;AACL,WAAO,KAAK,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;AAC7C,QAAI;;;;AAIV,QAAO;;;;;;AAOT,SAAS,cAAc,cAA6D;CAClF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GACD;IAAE,QAAQ;IAAkB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAQ;GACvF;IAAE,QAAQ;IAAoB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAU;GAC3F;IAAE,QAAQ;IAAkB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAQ;GACvF;IAAE,QAAQ;IAAiB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAO;GACrF;IACE,QAAQ;IACR,UAAU;IACV,UAAU;IACV,YAAY;IACb;GACD;IACE,QAAQ;IACR,UAAU;IACV,UAAU;IACV,YAAY;IACb;GACD;IAAE,QAAQ;IAAkB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAQ;GACvF;IAAE,QAAQ;IAAmB,UAAU;IAAO,UAAU;IAAY,YAAY;IAAS;GAC1F;EACD,qBAAqB,EACnB,QAAQ;GACN,SAAS;GACT,OAAO;GACP,OAAO;GACR,EACF;EACF;CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sql-renderer-pEaSP82_.mjs","names":["paramIndexMap: ParamIndexMap","params: unknown[]","sql: string","right: string","orderedColumns: string[]","value: string"],"sources":["../src/core/sql-renderer.ts"],"sourcesContent":["import {\n type AggregateExpr,\n type AnyExpression,\n type AnyFromSource,\n type AnyQueryAst,\n type BinaryExpr,\n type ColumnRef,\n type DeleteAst,\n type InsertAst,\n type InsertValue,\n type JoinAst,\n type JoinOnExpr,\n type JsonArrayAggExpr,\n type JsonObjectExpr,\n type ListExpression,\n LiteralExpr,\n type NullCheckExpr,\n type OperationExpr,\n type OrderByItem,\n type ParamRef,\n type ProjectionItem,\n type SelectAst,\n type SubqueryExpr,\n type UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';\nimport { escapeLiteral, quoteIdentifier } from '@prisma-next/target-postgres/sql-utils';\nimport type { PostgresContract } from './types';\n\n// Mirrors `VECTOR_CODEC_ID` in `@prisma-next/extension-pgvector/core/constants`.\n// Duplicated here rather than imported because the canonical export is not\n// part of the extension's public subpath surface, and `@prisma-next/adapter-postgres`\n// does not (and should not) take a runtime dependency on the extension package\n// just for one constant. The whole `getCodecParamCast` switch is slated for\n// removal under TML-2310 (\"Move SQL param-cast metadata onto codec descriptors\"),\n// at which point this and the JSON/JSONB IDs below also disappear.\nconst VECTOR_CODEC_ID = 'pg/vector@1' as const;\n\n/**\n * Map a codec ID to its `::cast` suffix, if Postgres requires one for\n * parameterized values (e.g. `$1::vector`, `$1::jsonb`).\n *\n * NOTE: hardcoded codec IDs here are a known wart, tracked separately by\n * TML-2310 (\"Move SQL param-cast metadata onto codec descriptors\").\n * Until that lands the cast lives on the renderer rather than the codec.\n */\nfunction getCodecParamCast(codecId: string | undefined): string | undefined {\n if (codecId === VECTOR_CODEC_ID) {\n return 'vector';\n }\n if (codecId === PG_JSON_CODEC_ID) {\n return 'json';\n }\n if (codecId === PG_JSONB_CODEC_ID) {\n return 'jsonb';\n }\n return undefined;\n}\n\nfunction renderTypedParam(index: number, codecId: string | undefined): string {\n const cast = getCodecParamCast(codecId);\n return cast ? `$${index}::${cast}` : `$${index}`;\n}\n\ntype ParamIndexMap = Map<ParamRef, number>;\n\n/**\n * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.\n *\n * Shared between the runtime (`PostgresAdapterImpl.lower`) and control\n * (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time\n * paths produce byte-identical output for the same AST.\n */\nexport function renderLoweredSql(\n ast: AnyQueryAst,\n contract: PostgresContract,\n): { readonly sql: string; readonly params: readonly unknown[] } {\n const collectedParamRefs = ast.collectParamRefs();\n const paramIndexMap: ParamIndexMap = new Map();\n const params: unknown[] = [];\n for (const ref of collectedParamRefs) {\n if (paramIndexMap.has(ref)) {\n continue;\n }\n paramIndexMap.set(ref, params.length + 1);\n params.push(ref.value);\n }\n\n const node = ast;\n let sql: string;\n switch (node.kind) {\n case 'select':\n sql = renderSelect(node, contract, paramIndexMap);\n break;\n case 'insert':\n sql = renderInsert(node, contract, paramIndexMap);\n break;\n case 'update':\n sql = renderUpdate(node, contract, paramIndexMap);\n break;\n case 'delete':\n sql = renderDelete(node, contract, paramIndexMap);\n break;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported AST node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n\n return Object.freeze({ sql, params: Object.freeze(params) });\n}\n\nfunction renderSelect(ast: SelectAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const selectClause = `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(\n ast.projection,\n contract,\n pim,\n )}`;\n const fromClause = `FROM ${renderSource(ast.from, contract, pim)}`;\n\n const joinsClause = ast.joins?.length\n ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(' ')\n : '';\n\n const whereClause = ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const groupByClause = ast.groupBy?.length\n ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(', ')}`\n : '';\n const havingClause = ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : '';\n const orderClause = ast.orderBy?.length\n ? `ORDER BY ${ast.orderBy\n .map((order) => {\n const expr = renderExpr(order.expr, contract, pim);\n return `${expr} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n const limitClause = typeof ast.limit === 'number' ? `LIMIT ${ast.limit}` : '';\n const offsetClause = typeof ast.offset === 'number' ? `OFFSET ${ast.offset}` : '';\n\n const clauses = [\n selectClause,\n fromClause,\n joinsClause,\n whereClause,\n groupByClause,\n havingClause,\n orderClause,\n limitClause,\n offsetClause,\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n return clauses.trim();\n}\n\nfunction renderProjection(\n projection: ReadonlyArray<ProjectionItem>,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n return projection\n .map((item) => {\n const alias = quoteIdentifier(item.alias);\n if (item.expr.kind === 'literal') {\n return `${renderLiteral(item.expr)} AS ${alias}`;\n }\n return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;\n })\n .join(', ');\n}\n\nfunction renderDistinctPrefix(\n distinct: true | undefined,\n distinctOn: ReadonlyArray<AnyExpression> | undefined,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n if (distinctOn && distinctOn.length > 0) {\n const rendered = distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(', ');\n return `DISTINCT ON (${rendered}) `;\n }\n if (distinct) {\n return 'DISTINCT ';\n }\n return '';\n}\n\nfunction renderSource(\n source: AnyFromSource,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const node = source;\n switch (node.kind) {\n case 'table-source': {\n const table = quoteIdentifier(node.name);\n if (!node.alias) {\n return table;\n }\n return `${table} AS ${quoteIdentifier(node.alias)}`;\n }\n case 'derived-table-source':\n return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction assertScalarSubquery(query: SelectAst): void {\n if (query.projection.length !== 1) {\n throw new Error('Subquery expressions must project exactly one column');\n }\n}\n\nfunction renderSubqueryExpr(\n expr: SubqueryExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n assertScalarSubquery(expr.query);\n return `(${renderSelect(expr.query, contract, pim)})`;\n}\n\nfunction renderWhere(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {\n return renderExpr(expr, contract, pim);\n}\n\nfunction renderNullCheck(\n expr: NullCheckExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const rendered = renderExpr(expr.expr, contract, pim);\n const renderedExpr = isAtomicExpressionKind(expr.expr.kind) ? rendered : `(${rendered})`;\n return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;\n}\n\n/**\n * Atomic expression kinds whose rendered SQL is already self-delimited\n * (a column reference, parameter, literal, function call, aggregate, etc.)\n * and therefore does not need surrounding parentheses when used as the\n * left operand of a postfix predicate like `IS NULL` or `IS NOT NULL`,\n * or as either operand of a binary infix operator.\n *\n * Anything not in this set is treated as composite (binary, AND/OR/NOT,\n * EXISTS, nested IS NULL, subqueries, operation templates) and gets\n * wrapped to preserve grouping.\n */\nfunction isAtomicExpressionKind(kind: AnyExpression['kind']): boolean {\n switch (kind) {\n case 'column-ref':\n case 'identifier-ref':\n case 'param-ref':\n case 'literal':\n case 'aggregate':\n case 'json-object':\n case 'json-array-agg':\n case 'list':\n return true;\n case 'subquery':\n case 'operation':\n case 'binary':\n case 'and':\n case 'or':\n case 'exists':\n case 'null-check':\n case 'not':\n return false;\n }\n}\n\nfunction renderBinary(expr: BinaryExpr, contract: PostgresContract, pim: ParamIndexMap): string {\n if (expr.right.kind === 'list' && expr.right.values.length === 0) {\n if (expr.op === 'in') {\n return 'FALSE';\n }\n if (expr.op === 'notIn') {\n return 'TRUE';\n }\n }\n\n const leftExpr = expr.left;\n const left = renderExpr(leftExpr, contract, pim);\n const leftRendered =\n leftExpr.kind === 'operation' || leftExpr.kind === 'subquery' ? `(${left})` : left;\n\n const rightNode = expr.right;\n let right: string;\n switch (rightNode.kind) {\n case 'list':\n right = renderListLiteral(rightNode, contract, pim);\n break;\n case 'literal':\n right = renderLiteral(rightNode);\n break;\n case 'column-ref':\n right = renderColumn(rightNode);\n break;\n case 'param-ref':\n right = renderParamRef(rightNode, pim);\n break;\n default:\n right = renderExpr(rightNode, contract, pim);\n break;\n }\n\n const operatorMap: Record<BinaryExpr['op'], string> = {\n eq: '=',\n neq: '!=',\n gt: '>',\n lt: '<',\n gte: '>=',\n lte: '<=',\n like: 'LIKE',\n in: 'IN',\n notIn: 'NOT IN',\n };\n\n return `${leftRendered} ${operatorMap[expr.op]} ${right}`;\n}\n\nfunction renderListLiteral(\n expr: ListExpression,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n if (expr.values.length === 0) {\n return '(NULL)';\n }\n const values = expr.values\n .map((v) => {\n if (v.kind === 'param-ref') return renderParamRef(v, pim);\n if (v.kind === 'literal') return renderLiteral(v);\n return renderExpr(v, contract, pim);\n })\n .join(', ');\n return `(${values})`;\n}\n\nfunction renderColumn(ref: ColumnRef): string {\n if (ref.table === 'excluded') {\n return `excluded.${quoteIdentifier(ref.column)}`;\n }\n return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\n\nfunction renderAggregateExpr(\n expr: AggregateExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const fn = expr.fn.toUpperCase();\n if (!expr.expr) {\n return `${fn}(*)`;\n }\n return `${fn}(${renderExpr(expr.expr, contract, pim)})`;\n}\n\nfunction renderJsonObjectExpr(\n expr: JsonObjectExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const args = expr.entries\n .flatMap((entry): [string, string] => {\n const key = `'${escapeLiteral(entry.key)}'`;\n if (entry.value.kind === 'literal') {\n return [key, renderLiteral(entry.value)];\n }\n return [key, renderExpr(entry.value, contract, pim)];\n })\n .join(', ');\n return `json_build_object(${args})`;\n}\n\nfunction renderOrderByItems(\n items: ReadonlyArray<OrderByItem>,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n return items\n .map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`)\n .join(', ');\n}\n\nfunction renderJsonArrayAggExpr(\n expr: JsonArrayAggExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const aggregateOrderBy =\n expr.orderBy && expr.orderBy.length > 0\n ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}`\n : '';\n const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;\n if (expr.onEmpty === 'emptyArray') {\n return `coalesce(${aggregated}, json_build_array())`;\n }\n return aggregated;\n}\n\nfunction renderExpr(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {\n const node = expr;\n switch (node.kind) {\n case 'column-ref':\n return renderColumn(node);\n case 'identifier-ref':\n return quoteIdentifier(node.name);\n case 'operation':\n return renderOperation(node, contract, pim);\n case 'subquery':\n return renderSubqueryExpr(node, contract, pim);\n case 'aggregate':\n return renderAggregateExpr(node, contract, pim);\n case 'json-object':\n return renderJsonObjectExpr(node, contract, pim);\n case 'json-array-agg':\n return renderJsonArrayAggExpr(node, contract, pim);\n case 'binary':\n return renderBinary(node, contract, pim);\n case 'and':\n if (node.exprs.length === 0) {\n return 'TRUE';\n }\n return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' AND ')})`;\n case 'or':\n if (node.exprs.length === 0) {\n return 'FALSE';\n }\n return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' OR ')})`;\n case 'exists': {\n const notKeyword = node.notExists ? 'NOT ' : '';\n const subquery = renderSelect(node.subquery, contract, pim);\n return `${notKeyword}EXISTS (${subquery})`;\n }\n case 'null-check':\n return renderNullCheck(node, contract, pim);\n case 'not':\n return `NOT (${renderExpr(node.expr, contract, pim)})`;\n case 'param-ref':\n return renderParamRef(node, pim);\n case 'literal':\n return renderLiteral(node);\n case 'list':\n return renderListLiteral(node, contract, pim);\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported expression node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction renderParamRef(ref: ParamRef, pim: ParamIndexMap): string {\n const index = pim.get(ref);\n if (index === undefined) {\n throw new Error('ParamRef not found in index map');\n }\n return renderTypedParam(index, ref.codecId);\n}\n\nfunction renderLiteral(expr: LiteralExpr): string {\n if (typeof expr.value === 'string') {\n return `'${escapeLiteral(expr.value)}'`;\n }\n if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {\n return String(expr.value);\n }\n if (typeof expr.value === 'bigint') {\n return String(expr.value);\n }\n if (expr.value === null) {\n return 'NULL';\n }\n if (expr.value === undefined) {\n return 'NULL';\n }\n if (expr.value instanceof Date) {\n return `'${escapeLiteral(expr.value.toISOString())}'`;\n }\n if (Array.isArray(expr.value)) {\n return `ARRAY[${expr.value.map((v: unknown) => renderLiteral(new LiteralExpr(v))).join(', ')}]`;\n }\n const json = JSON.stringify(expr.value);\n if (json === undefined) {\n return 'NULL';\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nfunction renderOperation(\n expr: OperationExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const self = renderExpr(expr.self, contract, pim);\n const args = expr.args.map((arg) => {\n return renderExpr(arg, contract, pim);\n });\n\n // Resolve `{{self}}` and `{{argN}}` from the original template in a single\n // pass. Doing this with sequential `String.prototype.replace` calls is\n // unsafe: a substituted fragment can itself contain text that matches a\n // later token (e.g. an arg literal containing the substring `{{arg1}}`),\n // and the next iteration would corrupt it. A single regex callback never\n // re-scans already-substituted output.\n return expr.lowering.template.replace(\n /\\{\\{self\\}\\}|\\{\\{arg(\\d+)\\}\\}/g,\n (token, argIndex: string | undefined) => {\n if (token === '{{self}}') {\n return self;\n }\n const arg = args[Number(argIndex)];\n if (arg === undefined) {\n throw new Error(\n `Operation lowering template for \"${expr.method}\" referenced missing argument {{arg${argIndex}}}; template has ${args.length} arg(s)`,\n );\n }\n return arg;\n },\n );\n}\n\nfunction renderJoin(join: JoinAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const joinType = join.joinType.toUpperCase();\n const lateral = join.lateral ? 'LATERAL ' : '';\n const source = renderSource(join.source, contract, pim);\n const onClause = renderJoinOn(join.on, contract, pim);\n return `${joinType} JOIN ${lateral}${source} ON ${onClause}`;\n}\n\nfunction renderJoinOn(on: JoinOnExpr, contract: PostgresContract, pim: ParamIndexMap): string {\n if (on.kind === 'eq-col-join-on') {\n const left = renderColumn(on.left);\n const right = renderColumn(on.right);\n return `${left} = ${right}`;\n }\n return renderWhere(on, contract, pim);\n}\n\nfunction getInsertColumnOrder(\n rows: ReadonlyArray<Record<string, InsertValue>>,\n contract: PostgresContract,\n tableName: string,\n): string[] {\n const orderedColumns: string[] = [];\n const seenColumns = new Set<string>();\n\n for (const row of rows) {\n for (const column of Object.keys(row)) {\n if (seenColumns.has(column)) {\n continue;\n }\n seenColumns.add(column);\n orderedColumns.push(column);\n }\n }\n\n if (orderedColumns.length > 0) {\n return orderedColumns;\n }\n\n const table = contract.storage.tables[tableName];\n if (!table) {\n throw new Error(`INSERT target table not found in contract storage: ${tableName}`);\n }\n return Object.keys(table.columns);\n}\n\nfunction renderInsertValue(value: InsertValue | undefined, pim: ParamIndexMap): string {\n if (!value || value.kind === 'default-value') {\n return 'DEFAULT';\n }\n\n switch (value.kind) {\n case 'param-ref':\n return renderParamRef(value, pim);\n case 'column-ref':\n return renderColumn(value);\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported value node in INSERT: ${(value satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction renderInsert(ast: InsertAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const rows = ast.rows;\n if (rows.length === 0) {\n throw new Error('INSERT requires at least one row');\n }\n const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);\n const insertClause = (() => {\n if (!hasExplicitValues) {\n if (rows.length === 1) {\n return `INSERT INTO ${table} DEFAULT VALUES`;\n }\n\n const defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);\n if (defaultColumns.length === 0) {\n return `INSERT INTO ${table} VALUES ${rows.map(() => '()').join(', ')}`;\n }\n\n const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));\n const defaultRow = `(${defaultColumns.map(() => 'DEFAULT').join(', ')})`;\n return `INSERT INTO ${table} (${quotedColumns.join(', ')}) VALUES ${rows\n .map(() => defaultRow)\n .join(', ')}`;\n }\n\n const columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);\n const columns = columnOrder.map((column) => quoteIdentifier(column));\n const values = rows\n .map((row) => {\n const renderedRow = columnOrder.map((column) => renderInsertValue(row[column], pim));\n return `(${renderedRow.join(', ')})`;\n })\n .join(', ');\n\n return `INSERT INTO ${table} (${columns.join(', ')}) VALUES ${values}`;\n })();\n const onConflictClause = ast.onConflict\n ? (() => {\n const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));\n if (conflictColumns.length === 0) {\n throw new Error('INSERT onConflict requires at least one conflict column');\n }\n\n const action = ast.onConflict.action;\n switch (action.kind) {\n case 'do-nothing':\n return ` ON CONFLICT (${conflictColumns.join(', ')}) DO NOTHING`;\n case 'do-update-set': {\n const updateEntries = Object.entries(action.set);\n if (updateEntries.length === 0) {\n throw new Error('INSERT onConflict do-update-set requires at least one assignment');\n }\n const updates = updateEntries.map(([colName, value]) => {\n const target = quoteIdentifier(colName);\n if (value.kind === 'param-ref') {\n return `${target} = ${renderParamRef(value, pim)}`;\n }\n return `${target} = ${renderColumn(value)}`;\n });\n return ` ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${updates.join(', ')}`;\n }\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported onConflict action: ${(action satisfies never as { kind: string }).kind}`,\n );\n }\n })()\n : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `${insertClause}${onConflictClause}${returningClause}`;\n}\n\nfunction renderUpdate(ast: UpdateAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const setEntries = Object.entries(ast.set);\n if (setEntries.length === 0) {\n throw new Error('UPDATE requires at least one SET assignment');\n }\n const setClauses = setEntries.map(([col, val]) => {\n const column = quoteIdentifier(col);\n let value: string;\n switch (val.kind) {\n case 'param-ref':\n value = renderParamRef(val, pim);\n break;\n case 'column-ref':\n value = renderColumn(val);\n break;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported value node in UPDATE: ${(val satisfies never as { kind: string }).kind}`,\n );\n }\n return `${column} = ${value}`;\n });\n\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;\n}\n\nfunction renderDelete(ast: DeleteAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `DELETE FROM ${table}${whereClause}${returningClause}`;\n}\n"],"mappings":";;;;;AAoCA,MAAM,kBAAkB;;;;;;;;;AAUxB,SAAS,kBAAkB,SAAiD;AAC1E,KAAI,YAAY,gBACd,QAAO;AAET,KAAI,YAAY,iBACd,QAAO;AAET,KAAI,YAAY,kBACd,QAAO;;AAKX,SAAS,iBAAiB,OAAe,SAAqC;CAC5E,MAAM,OAAO,kBAAkB,QAAQ;AACvC,QAAO,OAAO,IAAI,MAAM,IAAI,SAAS,IAAI;;;;;;;;;AAY3C,SAAgB,iBACd,KACA,UAC+D;CAC/D,MAAM,qBAAqB,IAAI,kBAAkB;CACjD,MAAMA,gCAA+B,IAAI,KAAK;CAC9C,MAAMC,SAAoB,EAAE;AAC5B,MAAK,MAAM,OAAO,oBAAoB;AACpC,MAAI,cAAc,IAAI,IAAI,CACxB;AAEF,gBAAc,IAAI,KAAK,OAAO,SAAS,EAAE;AACzC,SAAO,KAAK,IAAI,MAAM;;CAGxB,MAAM,OAAO;CACb,IAAIC;AACJ,SAAQ,KAAK,MAAb;EACE,KAAK;AACH,SAAM,aAAa,MAAM,UAAU,cAAc;AACjD;EACF,KAAK;AACH,SAAM,aAAa,MAAM,UAAU,cAAc;AACjD;EACF,KAAK;AACH,SAAM,aAAa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AAG,gBAAgB,IAAI,MAAM,CAAC,GAAG,gBAAgB,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,KACnH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-CfRPdAk8.d.mts","names":[],"sources":["../src/core/types.ts"],"sourcesContent":[],"mappings":";;;;;UAmBiB,sBAAA;;AAAjB;AAIY,KAAA,gBAAA,GAAmB,QAAS,CAAA,UAAT,CAAA,GAAA;EAEnB,SAAI,MAAA,EAAA,UAAA;CAAG;AAAY,KAAnB,IAAA,GAAO,SAAY,GAAA,QAAA,GAAW,gBAAX;AAAW,UAEzB,WAAA,CAFyB;EAAgB,SAAA,IAAA,EAGzC,SAHyC;EAEzC,SAAA,GAAA,EAED,SAFY;AAK5B;KAAY,wBAAA,GAA2B"}
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
JsonSchemaValidateFn,
|
|
3
|
-
JsonSchemaValidationError,
|
|
4
|
-
JsonSchemaValidationResult,
|
|
5
|
-
} from '@prisma-next/sql-relational-core/query-lane-context';
|
|
6
|
-
import Ajv from 'ajv';
|
|
7
|
-
|
|
8
|
-
export type { JsonSchemaValidateFn, JsonSchemaValidationError, JsonSchemaValidationResult };
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Shared Ajv instance for all JSON Schema validators.
|
|
12
|
-
* Reusing a single instance avoids ~50-100KB memory overhead per compiled schema.
|
|
13
|
-
*/
|
|
14
|
-
let sharedAjv: Ajv | undefined;
|
|
15
|
-
|
|
16
|
-
function getSharedAjv(): Ajv {
|
|
17
|
-
if (!sharedAjv) {
|
|
18
|
-
sharedAjv = new Ajv({ allErrors: false, strict: false });
|
|
19
|
-
}
|
|
20
|
-
return sharedAjv;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Compiles a JSON Schema object into a reusable validate function using Ajv.
|
|
25
|
-
*
|
|
26
|
-
* The returned function validates a value against the schema and returns
|
|
27
|
-
* a structured result with error details on failure.
|
|
28
|
-
*
|
|
29
|
-
* Uses a shared Ajv instance and fail-fast mode (`allErrors: false`)
|
|
30
|
-
* to minimize memory and CPU overhead.
|
|
31
|
-
*
|
|
32
|
-
* @param schema - A JSON Schema object (draft-07 compatible)
|
|
33
|
-
* @returns A validate function
|
|
34
|
-
*/
|
|
35
|
-
export function compileJsonSchemaValidator(schema: Record<string, unknown>): JsonSchemaValidateFn {
|
|
36
|
-
const ajv = getSharedAjv();
|
|
37
|
-
const validate = ajv.compile(schema);
|
|
38
|
-
|
|
39
|
-
return (value: unknown): JsonSchemaValidationResult => {
|
|
40
|
-
const valid = validate(value);
|
|
41
|
-
if (valid) {
|
|
42
|
-
return { valid: true };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// biome-ignore lint/style/noNonNullAssertion: Ajv guarantees `errors` is populated whenever `validate(...)` returns false.
|
|
46
|
-
const errors: JsonSchemaValidationError[] = validate.errors!.map((err) => ({
|
|
47
|
-
path: err.instancePath || '/',
|
|
48
|
-
message: err.message ?? 'unknown validation error',
|
|
49
|
-
keyword: err.keyword,
|
|
50
|
-
}));
|
|
51
|
-
|
|
52
|
-
return { valid: false, errors };
|
|
53
|
-
};
|
|
54
|
-
}
|