@prisma-next/sql-contract 0.5.0-dev.9 → 0.5.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/dist/factories.d.mts +1 -1
- package/dist/factories.d.mts.map +1 -1
- package/dist/factories.mjs +2 -3
- package/dist/factories.mjs.map +1 -1
- package/dist/index-type-validation.d.mts +9 -0
- package/dist/index-type-validation.d.mts.map +1 -0
- package/dist/index-type-validation.mjs +18 -0
- package/dist/index-type-validation.mjs.map +1 -0
- package/dist/index-types-DqVqGHwg.d.mts +31 -0
- package/dist/index-types-DqVqGHwg.d.mts.map +1 -0
- package/dist/index-types.d.mts +2 -0
- package/dist/index-types.mjs +39 -0
- package/dist/index-types.mjs.map +1 -0
- package/dist/pack-types.d.mts.map +1 -1
- package/dist/pack-types.mjs +1 -1
- package/dist/{types-DRR5stkj.mjs → types-hgzy8ME1.mjs} +4 -4
- package/dist/types-hgzy8ME1.mjs.map +1 -0
- package/dist/{types-DdNz1nUf.d.mts → types-njsiV-Ck.d.mts} +38 -31
- package/dist/types-njsiV-Ck.d.mts.map +1 -0
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs +2 -3
- package/dist/validate.d.mts +1 -1
- package/dist/validate.d.mts.map +1 -1
- package/dist/validate.mjs +2 -3
- package/dist/validate.mjs.map +1 -1
- package/dist/{validators-BjZ6lOS1.mjs → validators-Dm5X-Hvg.mjs} +50 -37
- package/dist/validators-Dm5X-Hvg.mjs.map +1 -0
- package/dist/validators.d.mts +14 -12
- package/dist/validators.d.mts.map +1 -1
- package/dist/validators.mjs +2 -3
- package/package.json +11 -8
- package/src/exports/index-type-validation.ts +1 -0
- package/src/exports/index-types.ts +9 -0
- package/src/exports/types.ts +2 -3
- package/src/index-type-validation.ts +37 -0
- package/src/index-types.ts +77 -0
- package/src/index.ts +2 -0
- package/src/types.ts +28 -28
- package/src/validators.ts +50 -4
- package/dist/types-DRR5stkj.mjs.map +0 -1
- package/dist/types-DdNz1nUf.d.mts.map +0 -1
- package/dist/validators-BjZ6lOS1.mjs.map +0 -1
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ContractValidationError } from "@prisma-next/contract/validate-contract";
|
|
2
2
|
import { type } from "arktype";
|
|
3
|
-
|
|
4
3
|
//#region src/validators.ts
|
|
5
4
|
const literalKindSchema = type("'literal'");
|
|
6
5
|
const functionKindSchema = type("'function'");
|
|
@@ -23,22 +22,21 @@ const ExecutionMutationDefaultValueSchema = type({
|
|
|
23
22
|
id: generatorIdSchema,
|
|
24
23
|
"params?": "Record<string, unknown>"
|
|
25
24
|
});
|
|
26
|
-
const ExecutionMutationDefaultSchema = type({
|
|
27
|
-
"+": "reject",
|
|
28
|
-
ref: {
|
|
29
|
-
"+": "reject",
|
|
30
|
-
table: "string",
|
|
31
|
-
column: "string"
|
|
32
|
-
},
|
|
33
|
-
"onCreate?": ExecutionMutationDefaultValueSchema,
|
|
34
|
-
"onUpdate?": ExecutionMutationDefaultValueSchema
|
|
35
|
-
});
|
|
36
25
|
const ExecutionSchema = type({
|
|
37
26
|
"+": "reject",
|
|
38
27
|
executionHash: "string",
|
|
39
28
|
mutations: {
|
|
40
29
|
"+": "reject",
|
|
41
|
-
defaults:
|
|
30
|
+
defaults: type({
|
|
31
|
+
"+": "reject",
|
|
32
|
+
ref: {
|
|
33
|
+
"+": "reject",
|
|
34
|
+
table: "string",
|
|
35
|
+
column: "string"
|
|
36
|
+
},
|
|
37
|
+
"onCreate?": ExecutionMutationDefaultValueSchema,
|
|
38
|
+
"onUpdate?": ExecutionMutationDefaultValueSchema
|
|
39
|
+
}).array().readonly()
|
|
42
40
|
}
|
|
43
41
|
});
|
|
44
42
|
const StorageColumnSchema = type({
|
|
@@ -69,8 +67,8 @@ const UniqueConstraintSchema = type.declare().type({
|
|
|
69
67
|
const IndexSchema = type({
|
|
70
68
|
columns: type.string.array().readonly(),
|
|
71
69
|
"name?": "string",
|
|
72
|
-
"
|
|
73
|
-
"
|
|
70
|
+
"type?": "string",
|
|
71
|
+
"options?": "Record<string, unknown>"
|
|
74
72
|
});
|
|
75
73
|
const ForeignKeyReferencesSchema = type.declare().type({
|
|
76
74
|
table: "string",
|
|
@@ -86,23 +84,29 @@ const ForeignKeySchema = type.declare().type({
|
|
|
86
84
|
constraint: "boolean",
|
|
87
85
|
index: "boolean"
|
|
88
86
|
});
|
|
89
|
-
const StorageTableSchema = type({
|
|
90
|
-
"+": "reject",
|
|
91
|
-
columns: type({ "[string]": StorageColumnSchema }),
|
|
92
|
-
"primaryKey?": PrimaryKeySchema,
|
|
93
|
-
uniques: UniqueConstraintSchema.array().readonly(),
|
|
94
|
-
indexes: IndexSchema.array().readonly(),
|
|
95
|
-
foreignKeys: ForeignKeySchema.array().readonly()
|
|
96
|
-
});
|
|
97
87
|
const StorageSchema = type({
|
|
98
88
|
"+": "reject",
|
|
99
89
|
storageHash: "string",
|
|
100
|
-
tables: type({ "[string]":
|
|
90
|
+
tables: type({ "[string]": type({
|
|
91
|
+
"+": "reject",
|
|
92
|
+
columns: type({ "[string]": StorageColumnSchema }),
|
|
93
|
+
"primaryKey?": PrimaryKeySchema,
|
|
94
|
+
uniques: UniqueConstraintSchema.array().readonly(),
|
|
95
|
+
indexes: IndexSchema.array().readonly(),
|
|
96
|
+
foreignKeys: ForeignKeySchema.array().readonly()
|
|
97
|
+
}) }),
|
|
101
98
|
"types?": type({ "[string]": StorageTypeInstanceSchema })
|
|
102
99
|
});
|
|
103
100
|
function isPlainRecord(value) {
|
|
104
101
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
105
102
|
}
|
|
103
|
+
function findDuplicateValue(values) {
|
|
104
|
+
const seen = /* @__PURE__ */ new Set();
|
|
105
|
+
for (const value of values) {
|
|
106
|
+
if (seen.has(value)) return value;
|
|
107
|
+
seen.add(value);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
106
110
|
function isContractFieldType(value) {
|
|
107
111
|
if (!isPlainRecord(value)) return false;
|
|
108
112
|
const kind = value["kind"];
|
|
@@ -120,23 +124,21 @@ function isContractFieldType(value) {
|
|
|
120
124
|
}
|
|
121
125
|
return false;
|
|
122
126
|
}
|
|
123
|
-
const ContractFieldTypeSchema = type("unknown").narrow((value, ctx) => isContractFieldType(value) ? true : ctx.mustBe("scalar, valueObject, or union field type"));
|
|
124
127
|
const ModelFieldSchema = type({
|
|
125
128
|
"+": "reject",
|
|
126
129
|
nullable: "boolean",
|
|
127
|
-
type:
|
|
130
|
+
type: type("unknown").narrow((value, ctx) => isContractFieldType(value) ? true : ctx.mustBe("scalar, valueObject, or union field type")),
|
|
128
131
|
"many?": "true",
|
|
129
132
|
"dict?": "true"
|
|
130
133
|
});
|
|
131
|
-
const ModelStorageFieldSchema = type({
|
|
132
|
-
column: "string",
|
|
133
|
-
"codecId?": "string",
|
|
134
|
-
"nullable?": "boolean"
|
|
135
|
-
});
|
|
136
134
|
const ModelSchema = type({
|
|
137
135
|
storage: type({
|
|
138
136
|
table: "string",
|
|
139
|
-
fields: type({ "[string]":
|
|
137
|
+
fields: type({ "[string]": type({
|
|
138
|
+
column: "string",
|
|
139
|
+
"codecId?": "string",
|
|
140
|
+
"nullable?": "boolean"
|
|
141
|
+
}) })
|
|
140
142
|
}),
|
|
141
143
|
"fields?": type({ "[string]": ModelFieldSchema }),
|
|
142
144
|
"relations?": type({ "[string]": "unknown" }),
|
|
@@ -145,7 +147,6 @@ const ModelSchema = type({
|
|
|
145
147
|
"base?": "string",
|
|
146
148
|
"owner?": "string"
|
|
147
149
|
});
|
|
148
|
-
const ContractMetaSchema = type({ "[string]": "unknown" });
|
|
149
150
|
const SqlContractSchema = type({
|
|
150
151
|
"+": "reject",
|
|
151
152
|
target: "string",
|
|
@@ -154,7 +155,7 @@ const SqlContractSchema = type({
|
|
|
154
155
|
profileHash: "string",
|
|
155
156
|
"capabilities?": "Record<string, Record<string, boolean>>",
|
|
156
157
|
"extensionPacks?": "Record<string, unknown>",
|
|
157
|
-
"meta?":
|
|
158
|
+
"meta?": type({ "[string]": "unknown" }),
|
|
158
159
|
"roots?": "Record<string, string>",
|
|
159
160
|
models: type({ "[string]": ModelSchema }),
|
|
160
161
|
"valueObjects?": "Record<string, unknown>",
|
|
@@ -210,6 +211,8 @@ function validateSqlContract(value) {
|
|
|
210
211
|
* Currently checks:
|
|
211
212
|
* - duplicate named primary key / unique / index / foreign key objects within a table
|
|
212
213
|
* - duplicate unique, index, or foreign key declarations within a table
|
|
214
|
+
* - duplicate columns within primary key / unique / index definitions
|
|
215
|
+
* - nullable columns in primary key definitions
|
|
213
216
|
* - `setNull` referential action on a non-nullable FK column (would fail at runtime)
|
|
214
217
|
* - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)
|
|
215
218
|
*/
|
|
@@ -226,8 +229,15 @@ function validateStorageSemantics(storage) {
|
|
|
226
229
|
for (const index of table.indexes) registerNamedObject("index", index.name);
|
|
227
230
|
for (const fk of table.foreignKeys) registerNamedObject("foreign key", fk.name);
|
|
228
231
|
for (const [name, kinds] of namedObjects) if (kinds.length > 1) errors.push(`Table "${tableName}": named object "${name}" is declared multiple times (${kinds.join(", ")})`);
|
|
232
|
+
if (table.primaryKey) {
|
|
233
|
+
const duplicateColumn = findDuplicateValue(table.primaryKey.columns);
|
|
234
|
+
if (duplicateColumn !== void 0) errors.push(`Table "${tableName}": primary key contains duplicate column "${duplicateColumn}"`);
|
|
235
|
+
for (const columnName of table.primaryKey.columns) if (table.columns[columnName]?.nullable === true) errors.push(`Table "${tableName}": primary key column "${columnName}" is nullable; primary key columns must be NOT NULL`);
|
|
236
|
+
}
|
|
229
237
|
const seenUniqueDefinitions = /* @__PURE__ */ new Set();
|
|
230
238
|
for (const unique of table.uniques) {
|
|
239
|
+
const duplicateColumn = findDuplicateValue(unique.columns);
|
|
240
|
+
if (duplicateColumn !== void 0) errors.push(`Table "${tableName}": unique constraint contains duplicate column "${duplicateColumn}"`);
|
|
231
241
|
const signature = JSON.stringify({ columns: unique.columns });
|
|
232
242
|
if (seenUniqueDefinitions.has(signature)) {
|
|
233
243
|
errors.push(`Table "${tableName}": duplicate unique constraint definition on columns [${unique.columns.join(", ")}]`);
|
|
@@ -235,12 +245,15 @@ function validateStorageSemantics(storage) {
|
|
|
235
245
|
}
|
|
236
246
|
seenUniqueDefinitions.add(signature);
|
|
237
247
|
}
|
|
248
|
+
const sortOptions = (o) => o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;
|
|
238
249
|
const seenIndexDefinitions = /* @__PURE__ */ new Set();
|
|
239
250
|
for (const index of table.indexes) {
|
|
251
|
+
const duplicateColumn = findDuplicateValue(index.columns);
|
|
252
|
+
if (duplicateColumn !== void 0) errors.push(`Table "${tableName}": index contains duplicate column "${duplicateColumn}"`);
|
|
240
253
|
const signature = JSON.stringify({
|
|
241
254
|
columns: index.columns,
|
|
242
|
-
|
|
243
|
-
|
|
255
|
+
type: index.type ?? null,
|
|
256
|
+
options: sortOptions(index.options)
|
|
244
257
|
});
|
|
245
258
|
if (seenIndexDefinitions.has(signature)) {
|
|
246
259
|
errors.push(`Table "${tableName}": duplicate index definition on columns [${index.columns.join(", ")}]`);
|
|
@@ -275,7 +288,7 @@ function validateStorageSemantics(storage) {
|
|
|
275
288
|
}
|
|
276
289
|
return errors;
|
|
277
290
|
}
|
|
278
|
-
|
|
279
291
|
//#endregion
|
|
280
292
|
export { ForeignKeySchema as a, validateModel as c, validateStorageSemantics as d, ForeignKeyReferencesSchema as i, validateSqlContract as l, ColumnDefaultLiteralSchema as n, IndexSchema as o, ColumnDefaultSchema as r, ReferentialActionSchema as s, ColumnDefaultFunctionSchema as t, validateStorage as u };
|
|
281
|
-
|
|
293
|
+
|
|
294
|
+
//# sourceMappingURL=validators-Dm5X-Hvg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators-Dm5X-Hvg.mjs","names":[],"sources":["../src/validators.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { ContractValidationError } from '@prisma-next/contract/validate-contract';\nimport { type } from 'arktype';\nimport type {\n ForeignKey,\n ForeignKeyReferences,\n PrimaryKey,\n ReferentialAction,\n SqlStorage,\n StorageTypeInstance,\n UniqueConstraint,\n} from './types';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst generatorKindSchema = type(\"'generator'\");\nconst generatorIdSchema = type('string').narrow((value, ctx) => {\n return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value) ? true : ctx.mustBe('a flat generator id');\n});\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst ExecutionMutationDefaultValueSchema = type({\n '+': 'reject',\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n '+': 'reject',\n ref: {\n '+': 'reject',\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n '+': 'reject',\n executionHash: 'string',\n mutations: {\n '+': 'reject',\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst StorageColumnSchema = type({\n '+': 'reject',\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\n});\n\nconst StorageTypeInstanceSchema = type.declare<StorageTypeInstance>().type({\n codecId: 'string',\n nativeType: 'string',\n typeParams: 'Record<string, unknown>',\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKey>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraint>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nexport const IndexSchema = type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n 'type?': 'string',\n 'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKey>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nconst StorageTableSchema = type({\n '+': 'reject',\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n});\n\nconst StorageSchema = type({\n '+': 'reject',\n storageHash: 'string',\n tables: type({ '[string]': StorageTableSchema }),\n 'types?': type({ '[string]': StorageTypeInstanceSchema }),\n});\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction findDuplicateValue(values: readonly string[]): string | undefined {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n }\n return undefined;\n}\n\nfunction isContractFieldType(value: unknown): boolean {\n if (!isPlainRecord(value)) return false;\n const kind = value['kind'];\n if (kind === 'scalar') {\n if (typeof value['codecId'] !== 'string') return false;\n const typeParams = value['typeParams'];\n if (typeParams !== undefined && !isPlainRecord(typeParams)) return false;\n return true;\n }\n if (kind === 'valueObject') {\n return typeof value['name'] === 'string';\n }\n if (kind === 'union') {\n const members = value['members'];\n if (!Array.isArray(members)) return false;\n return members.every((m) => isContractFieldType(m));\n }\n return false;\n}\n\nconst ContractFieldTypeSchema = type('unknown').narrow((value, ctx) =>\n isContractFieldType(value) ? true : ctx.mustBe('scalar, valueObject, or union field type'),\n);\n\nconst ModelFieldSchema = type({\n '+': 'reject',\n nullable: 'boolean',\n type: ContractFieldTypeSchema,\n 'many?': 'true',\n 'dict?': 'true',\n});\n\nconst ModelStorageFieldSchema = type({\n column: 'string',\n 'codecId?': 'string',\n 'nullable?': 'boolean',\n});\n\nconst ModelStorageSchema = type({\n table: 'string',\n fields: type({ '[string]': ModelStorageFieldSchema }),\n});\n\nconst ModelSchema = type({\n storage: ModelStorageSchema,\n 'fields?': type({ '[string]': ModelFieldSchema }),\n 'relations?': type({ '[string]': 'unknown' }),\n 'discriminator?': 'unknown',\n 'variants?': 'unknown',\n 'base?': 'string',\n 'owner?': 'string',\n});\n\nconst ContractMetaSchema = type({\n '[string]': 'unknown',\n});\n\nconst SqlContractSchema = type({\n '+': 'reject',\n target: 'string',\n targetFamily: \"'sql'\",\n 'coreHash?': 'string',\n profileHash: 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': ContractMetaSchema,\n 'roots?': 'Record<string, string>',\n models: type({ '[string]': ModelSchema }),\n 'valueObjects?': 'Record<string, unknown>',\n storage: StorageSchema,\n 'execution?': ExecutionSchema,\n});\n\n// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()\n// instead of type.declare<T>().type() because the ColumnDefault union's value field\n// includes bigint | Date (runtime-only types after decoding) which cannot be expressed\n// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges\n// the gap between the JSON-safe Arktype output and the runtime TypeScript type.\n// See decodeContractDefaults() in validate.ts for the decoding step.\n\n/**\n * Validates the structural shape of SqlStorage using Arktype.\n *\n * @param value - The storage value to validate\n * @returns The validated storage if structure is valid\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): SqlStorage {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n return result as SqlStorage;\n}\n\nexport function validateModel(value: unknown): unknown {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Validates the structural shape of an SQL contract using Arktype.\n *\n * Ensures all required fields are present and have the correct types,\n * including SQL-specific storage structure (tables, columns, constraints).\n *\n * @param value - The contract value to validate (typically from a JSON import)\n * @returns The validated contract if structure is valid\n * @throws ContractValidationError if the contract structure is invalid\n */\nexport function validateSqlContract<T extends Contract<SqlStorage>>(value: unknown): T {\n if (typeof value !== 'object' || value === null) {\n throw new ContractValidationError(\n 'Contract structural validation failed: value must be an object',\n 'structural',\n );\n }\n\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n throw new ContractValidationError(\n `Unsupported target family: ${rawValue.targetFamily}`,\n 'structural',\n );\n }\n\n const contractResult = SqlContractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new ContractValidationError(\n `Contract structural validation failed: ${messages}`,\n 'structural',\n );\n }\n\n // Arktype's inferred output type differs from T due to exactOptionalPropertyTypes\n // and branded hash types — the runtime value is structurally compatible after validation\n return contractResult as unknown as T;\n}\n\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - duplicate named primary key / unique / index / foreign key objects within a table\n * - duplicate unique, index, or foreign key declarations within a table\n * - duplicate columns within primary key / unique / index definitions\n * - nullable columns in primary key definitions\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const namedObjects = new Map<string, string[]>();\n const registerNamedObject = (kind: string, name: string | undefined) => {\n if (!name) return;\n namedObjects.set(name, [...(namedObjects.get(name) ?? []), kind]);\n };\n\n registerNamedObject('primary key', table.primaryKey?.name);\n for (const unique of table.uniques) {\n registerNamedObject('unique constraint', unique.name);\n }\n for (const index of table.indexes) {\n registerNamedObject('index', index.name);\n }\n for (const fk of table.foreignKeys) {\n registerNamedObject('foreign key', fk.name);\n }\n\n for (const [name, kinds] of namedObjects) {\n if (kinds.length > 1) {\n errors.push(\n `Table \"${tableName}\": named object \"${name}\" is declared multiple times (${kinds.join(', ')})`,\n );\n }\n }\n\n if (table.primaryKey) {\n const duplicateColumn = findDuplicateValue(table.primaryKey.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": primary key contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n for (const columnName of table.primaryKey.columns) {\n const column = table.columns[columnName];\n if (column?.nullable === true) {\n errors.push(\n `Table \"${tableName}\": primary key column \"${columnName}\" is nullable; primary key columns must be NOT NULL`,\n );\n }\n }\n }\n\n const seenUniqueDefinitions = new Set<string>();\n for (const unique of table.uniques) {\n const duplicateColumn = findDuplicateValue(unique.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": unique constraint contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({ columns: unique.columns });\n if (seenUniqueDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate unique constraint definition on columns [${unique.columns.join(', ')}]`,\n );\n continue;\n }\n seenUniqueDefinitions.add(signature);\n }\n\n const sortOptions = (o: Record<string, unknown> | undefined): Record<string, unknown> | null =>\n o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;\n\n const seenIndexDefinitions = new Set<string>();\n for (const index of table.indexes) {\n const duplicateColumn = findDuplicateValue(index.columns);\n if (duplicateColumn !== undefined) {\n errors.push(`Table \"${tableName}\": index contains duplicate column \"${duplicateColumn}\"`);\n }\n\n const signature = JSON.stringify({\n columns: index.columns,\n type: index.type ?? null,\n options: sortOptions(index.options),\n });\n if (seenIndexDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate index definition on columns [${index.columns.join(', ')}]`,\n );\n continue;\n }\n seenIndexDefinitions.add(signature);\n }\n\n const seenForeignKeyDefinitions = new Set<string>();\n for (const fk of table.foreignKeys) {\n const signature = JSON.stringify({\n columns: fk.columns,\n references: fk.references,\n onDelete: fk.onDelete ?? null,\n onUpdate: fk.onUpdate ?? null,\n constraint: fk.constraint,\n index: fk.index,\n });\n if (seenForeignKeyDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate foreign key definition on columns [${fk.columns.join(', ')}]`,\n );\n continue;\n }\n seenForeignKeyDefinitions.add(signature);\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n }\n\n return errors;\n}\n"],"mappings":";;;AAkBA,MAAM,oBAAoB,KAAK,YAAY;AAC3C,MAAM,qBAAqB,KAAK,aAAa;AAC7C,MAAM,sBAAsB,KAAK,cAAc;AAC/C,MAAM,oBAAoB,KAAK,SAAS,CAAC,QAAQ,OAAO,QAAQ;CAC9D,OAAO,8BAA8B,KAAK,MAAM,GAAG,OAAO,IAAI,OAAO,sBAAsB;EAC3F;AAEF,MAAa,6BAA6B,KAAK,SAA+B,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;CACR,CAAC;AAEF,MAAa,8BAA8B,KAAK,SAAgC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;CACb,CAAC;AAEF,MAAa,sBAAsB,2BAA2B,GAAG,4BAA4B;AAE7F,MAAM,sCAAsC,KAAK;CAC/C,KAAK;CACL,MAAM;CACN,IAAI;CACJ,WAAW;CACZ,CAAC;AAaF,MAAM,kBAAkB,KAAK;CAC3B,KAAK;CACL,eAAe;CACf,WAAW;EACT,KAAK;EACL,UAhBmC,KAAK;GAC1C,KAAK;GACL,KAAK;IACH,KAAK;IACL,OAAO;IACP,QAAQ;IACT;GACD,aAAa;GACb,aAAa;GACd,CAO2C,CAAC,OAAO,CAAC,UAAU;EAC5D;CACF,CAAC;AAEF,MAAM,sBAAsB,KAAK;CAC/B,KAAK;CACL,YAAY;CACZ,SAAS;CACT,UAAU;CACV,eAAe;CACf,YAAY;CACZ,YAAY;CACb,CAAC,CAAC,QAAQ,KAAK,QAAQ;CACtB,IAAI,IAAI,eAAe,KAAA,KAAa,IAAI,YAAY,KAAA,GAClD,OAAO,IAAI,OAAO,uDAAuD;CAE3E,OAAO;EAC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AAA,GACzE,OAAO,KACL,UAAU,UAAU,gDAAgD,QAAQ,wCAC7E;GAEH,IAAI,GAAG,aAAa,gBAAgB,CAAC,OAAO,YAAY,OAAO,YAAY,KAAA,GACzE,OAAO,KACL,UAAU,UAAU,gDAAgD,QAAQ,wCAC7E;;;CAMT,OAAO"}
|
package/dist/validators.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as SqlStorage, S as ReferentialAction, f as ForeignKey, m as ForeignKeyReferences } from "./types-njsiV-Ck.mjs";
|
|
2
2
|
import { Contract } from "@prisma-next/contract/types";
|
|
3
|
-
import * as arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
4
|
-
import * as arktype_internal_variants_string_ts0 from "arktype/internal/variants/string.ts";
|
|
3
|
+
import * as _$arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
4
|
+
import * as _$arktype_internal_variants_string_ts0 from "arktype/internal/variants/string.ts";
|
|
5
5
|
|
|
6
6
|
//#region src/validators.d.ts
|
|
7
7
|
type ColumnDefaultLiteral = {
|
|
@@ -12,18 +12,18 @@ type ColumnDefaultFunction = {
|
|
|
12
12
|
readonly kind: 'function';
|
|
13
13
|
readonly expression: string;
|
|
14
14
|
};
|
|
15
|
-
declare const ColumnDefaultLiteralSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral, {}>;
|
|
16
|
-
declare const ColumnDefaultFunctionSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultFunction, {}>;
|
|
17
|
-
declare const ColumnDefaultSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral | ColumnDefaultFunction, {}>;
|
|
18
|
-
declare const IndexSchema: arktype_internal_variants_object_ts0.ObjectType<{
|
|
15
|
+
declare const ColumnDefaultLiteralSchema: _$arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral, {}>;
|
|
16
|
+
declare const ColumnDefaultFunctionSchema: _$arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultFunction, {}>;
|
|
17
|
+
declare const ColumnDefaultSchema: _$arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral | ColumnDefaultFunction, {}>;
|
|
18
|
+
declare const IndexSchema: _$arktype_internal_variants_object_ts0.ObjectType<{
|
|
19
19
|
columns: readonly string[];
|
|
20
20
|
name?: string;
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
type?: string;
|
|
22
|
+
options?: Record<string, unknown>;
|
|
23
23
|
}, {}>;
|
|
24
|
-
declare const ForeignKeyReferencesSchema: arktype_internal_variants_object_ts0.ObjectType<ForeignKeyReferences, {}>;
|
|
25
|
-
declare const ReferentialActionSchema: arktype_internal_variants_string_ts0.StringType<ReferentialAction, {}>;
|
|
26
|
-
declare const ForeignKeySchema: arktype_internal_variants_object_ts0.ObjectType<ForeignKey, {}>;
|
|
24
|
+
declare const ForeignKeyReferencesSchema: _$arktype_internal_variants_object_ts0.ObjectType<ForeignKeyReferences, {}>;
|
|
25
|
+
declare const ReferentialActionSchema: _$arktype_internal_variants_string_ts0.StringType<ReferentialAction, {}>;
|
|
26
|
+
declare const ForeignKeySchema: _$arktype_internal_variants_object_ts0.ObjectType<ForeignKey, {}>;
|
|
27
27
|
/**
|
|
28
28
|
* Validates the structural shape of SqlStorage using Arktype.
|
|
29
29
|
*
|
|
@@ -52,6 +52,8 @@ declare function validateSqlContract<T extends Contract<SqlStorage>>(value: unkn
|
|
|
52
52
|
* Currently checks:
|
|
53
53
|
* - duplicate named primary key / unique / index / foreign key objects within a table
|
|
54
54
|
* - duplicate unique, index, or foreign key declarations within a table
|
|
55
|
+
* - duplicate columns within primary key / unique / index definitions
|
|
56
|
+
* - nullable columns in primary key definitions
|
|
55
57
|
* - `setNull` referential action on a non-nullable FK column (would fail at runtime)
|
|
56
58
|
* - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)
|
|
57
59
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"
|
|
1
|
+
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"mappings":";;;;;;KAaK,oBAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,8BAAmC,MAAA;AAAA;AAAA,KAEzC,qBAAA;EAAA,SAAmC,IAAA;EAAA,SAA2B,UAAA;AAAA;AAAA,cAQtD,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,oBAAA;AAAA,cAK1B,2BAAA,EAA2B,sCAAA,CAAA,UAAA,CAAA,qBAAA;AAAA,cAK3B,mBAAA,EAAmB,sCAAA,CAAA,UAAA,CAAA,oBAAA,GAAA,qBAAA;AAAA,cA4DnB,WAAA,EAKX,sCAAA,CALsB,UAAA;;;;YAKtB,MAAA;AAAA;AAAA,cAEW,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,oBAAA;AAAA,cAK1B,uBAAA,EAAuB,sCAAA,CAAA,UAAA,CAAA,iBAAA;AAAA,cAIvB,gBAAA,EAAgB,sCAAA,CAAA,UAAA,CAAA,UAAA;;;;AAjF7B;;;;iBAiNgB,eAAA,CAAgB,KAAA,YAAiB,UAAA;AAAA,iBASjC,aAAA,CAAc,KAAA;;;;;;;;;;;iBAmBd,mBAAA,WAA8B,QAAA,CAAS,UAAA,EAAA,CAAa,KAAA,YAAiB,CAAA;;AA5KrF;;;;;;;;;;;;iBAwNgB,wBAAA,CAAyB,OAAA,EAAS,UAAA"}
|
package/dist/validators.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import { a as ForeignKeySchema, c as validateModel, d as validateStorageSemantics, i as ForeignKeyReferencesSchema, l as validateSqlContract, n as ColumnDefaultLiteralSchema, o as IndexSchema, r as ColumnDefaultSchema, s as ReferentialActionSchema, t as ColumnDefaultFunctionSchema, u as validateStorage } from "./validators-
|
|
2
|
-
|
|
3
|
-
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateSqlContract, validateStorage, validateStorageSemantics };
|
|
1
|
+
import { a as ForeignKeySchema, c as validateModel, d as validateStorageSemantics, i as ForeignKeyReferencesSchema, l as validateSqlContract, n as ColumnDefaultLiteralSchema, o as IndexSchema, r as ColumnDefaultSchema, s as ReferentialActionSchema, t as ColumnDefaultFunctionSchema, u as validateStorage } from "./validators-Dm5X-Hvg.mjs";
|
|
2
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateSqlContract, validateStorage, validateStorageSemantics };
|
package/package.json
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-contract",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
4
5
|
"type": "module",
|
|
5
6
|
"sideEffects": false,
|
|
6
7
|
"description": "SQL contract types, validators, and IR factories for Prisma Next",
|
|
7
8
|
"dependencies": {
|
|
8
|
-
"arktype": "^2.1.
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/
|
|
9
|
+
"arktype": "^2.1.29",
|
|
10
|
+
"@prisma-next/framework-components": "0.5.1",
|
|
11
|
+
"@prisma-next/contract": "0.5.1"
|
|
11
12
|
},
|
|
12
13
|
"devDependencies": {
|
|
13
|
-
"tsdown": "0.
|
|
14
|
+
"tsdown": "0.22.0",
|
|
14
15
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.
|
|
16
|
-
"@prisma-next/
|
|
16
|
+
"vitest": "4.1.5",
|
|
17
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
17
18
|
"@prisma-next/tsdown": "0.0.0",
|
|
18
|
-
"@prisma-next/
|
|
19
|
+
"@prisma-next/test-utils": "0.0.1"
|
|
19
20
|
},
|
|
20
21
|
"files": [
|
|
21
22
|
"dist",
|
|
@@ -23,6 +24,8 @@
|
|
|
23
24
|
],
|
|
24
25
|
"exports": {
|
|
25
26
|
"./factories": "./dist/factories.mjs",
|
|
27
|
+
"./index-type-validation": "./dist/index-type-validation.mjs",
|
|
28
|
+
"./index-types": "./dist/index-types.mjs",
|
|
26
29
|
"./pack-types": "./dist/pack-types.mjs",
|
|
27
30
|
"./types": "./dist/types.mjs",
|
|
28
31
|
"./validate": "./dist/validate.mjs",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../index-type-validation';
|
package/src/exports/types.ts
CHANGED
|
@@ -12,15 +12,14 @@ export type {
|
|
|
12
12
|
ForeignKeyOptions,
|
|
13
13
|
ForeignKeyReferences,
|
|
14
14
|
Index,
|
|
15
|
-
OperationTypesOf,
|
|
16
15
|
PrimaryKey,
|
|
17
|
-
|
|
16
|
+
QueryOperationReturn,
|
|
17
|
+
QueryOperationSelfSpec,
|
|
18
18
|
QueryOperationTypeEntry,
|
|
19
19
|
QueryOperationTypesBase,
|
|
20
20
|
QueryOperationTypesOf,
|
|
21
21
|
ReferentialAction,
|
|
22
22
|
ResolveCodecTypes,
|
|
23
|
-
ResolveOperationTypes,
|
|
24
23
|
SqlModelFieldStorage,
|
|
25
24
|
SqlModelStorage,
|
|
26
25
|
SqlQueryOperationTypes,
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Contract } from '@prisma-next/contract/types';
|
|
2
|
+
import { ContractValidationError } from '@prisma-next/contract/validate-contract';
|
|
3
|
+
import { type } from 'arktype';
|
|
4
|
+
import type { IndexTypeRegistry } from './index-types';
|
|
5
|
+
import type { SqlStorage } from './types';
|
|
6
|
+
|
|
7
|
+
export function validateIndexTypes(
|
|
8
|
+
contract: Contract<SqlStorage>,
|
|
9
|
+
indexTypeRegistry: IndexTypeRegistry,
|
|
10
|
+
): void {
|
|
11
|
+
for (const [tableName, table] of Object.entries(contract.storage.tables)) {
|
|
12
|
+
for (const index of table.indexes) {
|
|
13
|
+
if (index.type === undefined && index.options !== undefined) {
|
|
14
|
+
throw new ContractValidationError(
|
|
15
|
+
`Table "${tableName}" index on columns [${index.columns.join(', ')}] has options without a type`,
|
|
16
|
+
'storage',
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
if (index.type === undefined) continue;
|
|
20
|
+
const entry = indexTypeRegistry.get(index.type);
|
|
21
|
+
if (entry === undefined) {
|
|
22
|
+
throw new ContractValidationError(
|
|
23
|
+
`Table "${tableName}" index on columns [${index.columns.join(', ')}] uses unregistered index type "${index.type}"`,
|
|
24
|
+
'storage',
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
const optionsValue = index.options ?? {};
|
|
28
|
+
const result = entry.options(optionsValue);
|
|
29
|
+
if (result instanceof type.errors) {
|
|
30
|
+
throw new ContractValidationError(
|
|
31
|
+
`Table "${tableName}" index on columns [${index.columns.join(', ')}] has invalid options for type "${index.type}": ${result.summary}`,
|
|
32
|
+
'storage',
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Type } from 'arktype';
|
|
2
|
+
|
|
3
|
+
export interface IndexTypeEntry<TOptions = unknown> {
|
|
4
|
+
readonly type: string;
|
|
5
|
+
readonly options: Type<TOptions>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type IndexTypeMap = { readonly [K in string]: { readonly options: unknown } };
|
|
9
|
+
|
|
10
|
+
export interface IndexTypeRegistration<TMap extends IndexTypeMap = Record<never, never>> {
|
|
11
|
+
readonly IndexTypes: TMap;
|
|
12
|
+
readonly entries: ReadonlyArray<IndexTypeEntry>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface IndexTypeBuilder<TMap extends IndexTypeMap = Record<never, never>>
|
|
16
|
+
extends IndexTypeRegistration<TMap> {
|
|
17
|
+
add<TLit extends string, TOpts>(
|
|
18
|
+
typeLiteral: TLit,
|
|
19
|
+
entry: { readonly options: Type<TOpts> },
|
|
20
|
+
): IndexTypeBuilder<TMap & Record<TLit, { readonly options: TOpts }>>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
class IndexTypeBuilderImpl<TMap extends IndexTypeMap> implements IndexTypeBuilder<TMap> {
|
|
24
|
+
readonly entries: ReadonlyArray<IndexTypeEntry>;
|
|
25
|
+
readonly IndexTypes: TMap;
|
|
26
|
+
|
|
27
|
+
constructor(entries: ReadonlyArray<IndexTypeEntry>) {
|
|
28
|
+
this.entries = entries;
|
|
29
|
+
this.IndexTypes = {} as TMap;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
add<TLit extends string, TOpts>(
|
|
33
|
+
typeLiteral: TLit,
|
|
34
|
+
entry: { readonly options: Type<TOpts> },
|
|
35
|
+
): IndexTypeBuilder<TMap & Record<TLit, { readonly options: TOpts }>> {
|
|
36
|
+
if (this.entries.some((e) => e.type === typeLiteral)) {
|
|
37
|
+
throw new Error(`Index type "${typeLiteral}" is already declared in this builder`);
|
|
38
|
+
}
|
|
39
|
+
return new IndexTypeBuilderImpl<TMap & Record<TLit, { readonly options: TOpts }>>([
|
|
40
|
+
...this.entries,
|
|
41
|
+
{ type: typeLiteral, options: entry.options as Type<unknown> },
|
|
42
|
+
]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function defineIndexTypes(): IndexTypeBuilder<Record<never, never>> {
|
|
47
|
+
return new IndexTypeBuilderImpl([]);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface IndexTypeRegistry {
|
|
51
|
+
register(entry: IndexTypeEntry): void;
|
|
52
|
+
get(typeLiteral: string): IndexTypeEntry | undefined;
|
|
53
|
+
has(typeLiteral: string): boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class IndexTypeRegistryImpl implements IndexTypeRegistry {
|
|
57
|
+
private readonly entries = new Map<string, IndexTypeEntry>();
|
|
58
|
+
|
|
59
|
+
register(entry: IndexTypeEntry): void {
|
|
60
|
+
if (this.entries.has(entry.type)) {
|
|
61
|
+
throw new Error(`Index type "${entry.type}" is already registered`);
|
|
62
|
+
}
|
|
63
|
+
this.entries.set(entry.type, entry);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
get(typeLiteral: string): IndexTypeEntry | undefined {
|
|
67
|
+
return this.entries.get(typeLiteral);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
has(typeLiteral: string): boolean {
|
|
71
|
+
return this.entries.has(typeLiteral);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createIndexTypeRegistry(): IndexTypeRegistry {
|
|
76
|
+
return new IndexTypeRegistryImpl();
|
|
77
|
+
}
|
package/src/index.ts
CHANGED
package/src/types.ts
CHANGED
|
@@ -43,16 +43,8 @@ export type UniqueConstraint = {
|
|
|
43
43
|
export type Index = {
|
|
44
44
|
readonly columns: readonly string[];
|
|
45
45
|
readonly name?: string;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
* Extension-specific methods are represented as strings and interpreted
|
|
49
|
-
* by the owning extension package.
|
|
50
|
-
*/
|
|
51
|
-
readonly using?: string;
|
|
52
|
-
/**
|
|
53
|
-
* Optional extension-owned index configuration payload.
|
|
54
|
-
*/
|
|
55
|
-
readonly config?: Record<string, unknown>;
|
|
46
|
+
readonly type?: string;
|
|
47
|
+
readonly options?: Record<string, unknown>;
|
|
56
48
|
};
|
|
57
49
|
|
|
58
50
|
export type ForeignKeyReferences = {
|
|
@@ -139,13 +131,11 @@ export function applyFkDefaults(
|
|
|
139
131
|
|
|
140
132
|
export type TypeMaps<
|
|
141
133
|
TCodecTypes extends Record<string, { output: unknown }> = Record<string, never>,
|
|
142
|
-
TOperationTypes extends Record<string, unknown> = Record<string, never>,
|
|
143
134
|
TQueryOperationTypes extends Record<string, unknown> = Record<string, never>,
|
|
144
135
|
TFieldOutputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,
|
|
145
136
|
TFieldInputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,
|
|
146
137
|
> = {
|
|
147
138
|
readonly codecTypes: TCodecTypes;
|
|
148
|
-
readonly operationTypes: TOperationTypes;
|
|
149
139
|
readonly queryOperationTypes: TQueryOperationTypes;
|
|
150
140
|
readonly fieldOutputTypes: TFieldOutputTypes;
|
|
151
141
|
readonly fieldInputTypes: TFieldInputTypes;
|
|
@@ -159,26 +149,38 @@ export type CodecTypesOf<T> = [T] extends [never]
|
|
|
159
149
|
: Record<string, never>
|
|
160
150
|
: Record<string, never>;
|
|
161
151
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Dispatch hint identifying the first-argument target of an operation.
|
|
154
|
+
*
|
|
155
|
+
* Used by ORM column helpers to decide whether an operation is reachable on a
|
|
156
|
+
* field. Either names a concrete codec identity or a set of capability traits
|
|
157
|
+
* that the field's codec must carry.
|
|
158
|
+
*/
|
|
159
|
+
export type QueryOperationSelfSpec =
|
|
160
|
+
| { readonly codecId: string; readonly traits?: never }
|
|
161
|
+
| { readonly traits: readonly CodecTrait[]; readonly codecId?: never };
|
|
169
162
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
163
|
+
/**
|
|
164
|
+
* Structural shape an operation's impl must return: any value carrying a
|
|
165
|
+
* codec-exact `returnType` descriptor. `Expression<T>` (from
|
|
166
|
+
* `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`)
|
|
167
|
+
* extends this. Trait-targeted returns are deliberately excluded — predicate
|
|
168
|
+
* detection and result decoding both depend on knowing the concrete return
|
|
169
|
+
* codec.
|
|
170
|
+
*/
|
|
171
|
+
export type QueryOperationReturn = {
|
|
172
|
+
readonly returnType: { readonly codecId: string; readonly nullable: boolean };
|
|
174
173
|
};
|
|
175
174
|
|
|
176
175
|
export type QueryOperationTypeEntry = {
|
|
177
|
-
readonly
|
|
178
|
-
readonly
|
|
176
|
+
readonly self?: QueryOperationSelfSpec;
|
|
177
|
+
readonly impl: (...args: never[]) => QueryOperationReturn;
|
|
179
178
|
};
|
|
180
179
|
|
|
181
|
-
export type SqlQueryOperationTypes<
|
|
180
|
+
export type SqlQueryOperationTypes<
|
|
181
|
+
_CT extends Record<string, { readonly input: unknown; readonly output: unknown }>,
|
|
182
|
+
T extends Record<string, QueryOperationTypeEntry>,
|
|
183
|
+
> = T;
|
|
182
184
|
|
|
183
185
|
export type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>;
|
|
184
186
|
|
|
@@ -224,5 +226,3 @@ export type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromCon
|
|
|
224
226
|
export type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never]
|
|
225
227
|
? ExtractCodecTypes<TContract>
|
|
226
228
|
: CodecTypesOf<TTypeMaps>;
|
|
227
|
-
|
|
228
|
-
export type ResolveOperationTypes<_TContract, TTypeMaps> = OperationTypesOf<TTypeMaps>;
|