hekireki 0.48.0 → 0.49.0
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/bin/activerecord.js +1 -1
- package/dist/bin/ajv.js +1 -1
- package/dist/bin/arktype.js +1 -1
- package/dist/bin/atlas.js +1 -1
- package/dist/bin/django.js +1 -1
- package/dist/bin/docs.js +1 -1
- package/dist/bin/drizzle.js +1 -1
- package/dist/bin/ecto.js +1 -1
- package/dist/bin/efcore.js +1 -1
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.js +1 -1
- package/dist/bin/er.js +1 -1
- package/dist/bin/exposed.js +1 -1
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/hekireki.js +17 -5
- package/dist/bin/kysely.js +1 -1
- package/dist/bin/openapi.js +1 -1
- package/dist/bin/pydantic.js +1 -1
- package/dist/bin/sea-orm.js +1 -1
- package/dist/bin/seed.js +1 -1
- package/dist/bin/sqlalchemy.js +1 -1
- package/dist/bin/typebox.js +1 -1
- package/dist/bin/valibot.js +1 -1
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-CVcdvi5w.js → bin-BwEbmAZJ.js} +4 -4
- package/dist/{discover-kVbu9DxT.js → discover-Cl2bvBbf.js} +2 -2
- package/dist/{emit-DF8ehOFH.js → emit-B34moVCH.js} +1 -1
- package/dist/errors-fAN1Og-7.js +217 -0
- package/dist/{migrate-U9pCkJTm.js → migrate-Br4Ihwix.js} +4 -4
- package/dist/native-engine-Chz7hHRS.js +1481 -0
- package/dist/{plan-ChzbNv7_.js → plan-D02O7uP9.js} +130 -1702
- package/dist/{run-Caiu7ebD.js → run-C1XOA4x-.js} +4 -4
- package/dist/{schema-DzF7tKzG.js → schema-E_PyiUp_.js} +1 -1
- package/dist/{sql-DciD3-lE.js → sql-U9Fo2g8L.js} +1 -1
- package/dist/{start-C1n6SWZ3.js → start-Dez8JNe5.js} +5231 -1436
- package/package.json +1 -1
- package/dist/errors-0PjX4y1Z.js +0 -1050
- package/dist/native-engine-D1iZDp41.js +0 -537
|
@@ -0,0 +1,1481 @@
|
|
|
1
|
+
import { a as readBytes, o as readDirectory, t as exists } from "./file-BAVQ-zst.js";
|
|
2
|
+
import { V as isAnnotationLine, Y as parseRelation, m as backRelation, s as environmentVariable } from "./schema-E_PyiUp_.js";
|
|
3
|
+
import { a as splitStatements, c as sqliteAffinity, r as MigrateEngineError } from "./errors-fAN1Og-7.js";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { Effect, Semaphore, Stream } from "effect";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import * as z from "zod";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { createInterface } from "node:readline";
|
|
11
|
+
import { text } from "node:stream/consumers";
|
|
12
|
+
import { getEnginesPath } from "@prisma/engines";
|
|
13
|
+
// src/utils/relation.ts
|
|
14
|
+
function isCardinality(value) {
|
|
15
|
+
return value === "zero-one" || value === "one" || value === "zero-many" || value === "many";
|
|
16
|
+
}
|
|
17
|
+
function erKey(relation) {
|
|
18
|
+
return `${relation.from.model}.${relation.from.field}->${relation.to.model}.${relation.to.field}`;
|
|
19
|
+
}
|
|
20
|
+
function inferredERRelations(models) {
|
|
21
|
+
return models.flatMap((model) => model.fields.filter((field) => field.kind === "object" && field.relationFromFields && field.relationFromFields.length > 0).map((field) => {
|
|
22
|
+
const toModel = model.name;
|
|
23
|
+
const fromModel = field.type;
|
|
24
|
+
const toField = field.relationFromFields?.[0] ?? "";
|
|
25
|
+
const fromField = field.relationToFields?.[0] ?? "id";
|
|
26
|
+
const inverseField = backRelation(field, model, models);
|
|
27
|
+
const fromCardinality = field.isRequired ? "one" : "zero-one";
|
|
28
|
+
const toCardinality = inverseField?.isList ? "zero-many" : inverseField?.isRequired ? "one" : "zero-one";
|
|
29
|
+
return {
|
|
30
|
+
name: field.relationName ?? null,
|
|
31
|
+
from: {
|
|
32
|
+
model: fromModel,
|
|
33
|
+
field: fromField,
|
|
34
|
+
cardinality: fromCardinality
|
|
35
|
+
},
|
|
36
|
+
to: {
|
|
37
|
+
model: toModel,
|
|
38
|
+
field: toField,
|
|
39
|
+
cardinality: toCardinality
|
|
40
|
+
},
|
|
41
|
+
identifying: true,
|
|
42
|
+
origin: "inferred"
|
|
43
|
+
};
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
function annotatedERRelations(models) {
|
|
47
|
+
return models.flatMap((model) => (model.documentation ?? "").split("\n").flatMap((line) => {
|
|
48
|
+
const relation = parseRelation(line);
|
|
49
|
+
if (relation === null) return [];
|
|
50
|
+
const [fromCard, toCard] = relation.type.split("-to-");
|
|
51
|
+
if (!isCardinality(fromCard) || !isCardinality(toCard)) return [];
|
|
52
|
+
return [{
|
|
53
|
+
name: null,
|
|
54
|
+
from: {
|
|
55
|
+
model: relation.fromModel,
|
|
56
|
+
field: relation.fromField,
|
|
57
|
+
cardinality: fromCard
|
|
58
|
+
},
|
|
59
|
+
to: {
|
|
60
|
+
model: relation.toModel,
|
|
61
|
+
field: relation.toField,
|
|
62
|
+
cardinality: toCard
|
|
63
|
+
},
|
|
64
|
+
identifying: true,
|
|
65
|
+
origin: "annotated"
|
|
66
|
+
}];
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
function implicitManyToManyERRelations(models) {
|
|
70
|
+
return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
|
|
71
|
+
const other = models.find((m) => m.name === field.type);
|
|
72
|
+
const inverse = backRelation(field, model, models);
|
|
73
|
+
if (!(other && inverse?.isList)) return [];
|
|
74
|
+
if (`${model.name}.${field.name}` > `${other.name}.${inverse.name}`) return [];
|
|
75
|
+
return [{
|
|
76
|
+
name: field.relationName ?? null,
|
|
77
|
+
from: {
|
|
78
|
+
model: model.name,
|
|
79
|
+
field: field.name,
|
|
80
|
+
cardinality: "zero-many"
|
|
81
|
+
},
|
|
82
|
+
to: {
|
|
83
|
+
model: other.name,
|
|
84
|
+
field: inverse.name,
|
|
85
|
+
cardinality: "zero-many"
|
|
86
|
+
},
|
|
87
|
+
identifying: false,
|
|
88
|
+
origin: "implicit-many-to-many"
|
|
89
|
+
}];
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
function mergeERRelations(models) {
|
|
93
|
+
const inferred = inferredERRelations(models);
|
|
94
|
+
const annotated = annotatedERRelations(models);
|
|
95
|
+
const inferredByKey = new Map(inferred.map((r) => [erKey(r), r]));
|
|
96
|
+
return [...new Map([...inferred.map((r) => [erKey(r), r]), ...annotated.map((r) => {
|
|
97
|
+
const physical = inferredByKey.get(erKey(r));
|
|
98
|
+
return [erKey(r), physical ? {
|
|
99
|
+
...r,
|
|
100
|
+
name: physical.name,
|
|
101
|
+
origin: "inferred"
|
|
102
|
+
} : r];
|
|
103
|
+
})]).values()];
|
|
104
|
+
}
|
|
105
|
+
/** Every relation an ER diagram draws: foreign keys, `/// @relation` and implicit many-to-many. */
|
|
106
|
+
function erRelations(models) {
|
|
107
|
+
return [...mergeERRelations(models), ...implicitManyToManyERRelations(models)];
|
|
108
|
+
}
|
|
109
|
+
// src/studio/server/domain/schema.ts
|
|
110
|
+
const DefaultValue = z.union([
|
|
111
|
+
z.string(),
|
|
112
|
+
z.number(),
|
|
113
|
+
z.boolean(),
|
|
114
|
+
z.object({
|
|
115
|
+
name: z.string().meta({
|
|
116
|
+
description: "The function name.",
|
|
117
|
+
example: "now"
|
|
118
|
+
}),
|
|
119
|
+
args: z.array(z.union([z.string(), z.number()])).readonly().meta({
|
|
120
|
+
description: "The literal arguments.",
|
|
121
|
+
example: []
|
|
122
|
+
})
|
|
123
|
+
}).readonly(),
|
|
124
|
+
z.array(z.union([
|
|
125
|
+
z.string(),
|
|
126
|
+
z.number(),
|
|
127
|
+
z.boolean()
|
|
128
|
+
])).readonly()
|
|
129
|
+
]).optional().meta({ description: "The @default value, a literal or a function call." });
|
|
130
|
+
const NativeType = z.tuple([z.string().meta({
|
|
131
|
+
description: "The @db.* type name.",
|
|
132
|
+
example: "VarChar"
|
|
133
|
+
}), z.array(z.string()).readonly().meta({
|
|
134
|
+
description: "Its arguments.",
|
|
135
|
+
example: ["64"]
|
|
136
|
+
})]).readonly().nullish().meta({ description: "The @db.* native type name and its arguments." });
|
|
137
|
+
const Field = z.object({
|
|
138
|
+
name: z.string().meta({
|
|
139
|
+
description: "The field name as declared.",
|
|
140
|
+
example: "authorId"
|
|
141
|
+
}),
|
|
142
|
+
dbName: z.string().nullish().meta({
|
|
143
|
+
description: "The @map column name, when set.",
|
|
144
|
+
example: "author_id"
|
|
145
|
+
}),
|
|
146
|
+
kind: z.enum([
|
|
147
|
+
"scalar",
|
|
148
|
+
"object",
|
|
149
|
+
"enum",
|
|
150
|
+
"unsupported"
|
|
151
|
+
]).meta({
|
|
152
|
+
description: "What the field holds.",
|
|
153
|
+
example: "scalar"
|
|
154
|
+
}),
|
|
155
|
+
type: z.string().meta({
|
|
156
|
+
description: "The declared type.",
|
|
157
|
+
example: "Int"
|
|
158
|
+
}),
|
|
159
|
+
isList: z.boolean().meta({
|
|
160
|
+
description: "Whether the field is a list.",
|
|
161
|
+
example: false
|
|
162
|
+
}),
|
|
163
|
+
isRequired: z.boolean().meta({
|
|
164
|
+
description: "Whether the field is required.",
|
|
165
|
+
example: true
|
|
166
|
+
}),
|
|
167
|
+
isId: z.boolean().meta({
|
|
168
|
+
description: "Whether the field is @id.",
|
|
169
|
+
example: false
|
|
170
|
+
}),
|
|
171
|
+
isUnique: z.boolean().meta({
|
|
172
|
+
description: "Whether the field is @unique.",
|
|
173
|
+
example: false
|
|
174
|
+
}),
|
|
175
|
+
isUpdatedAt: z.boolean().optional().meta({
|
|
176
|
+
description: "Whether the field carries @updatedAt.",
|
|
177
|
+
example: false
|
|
178
|
+
}),
|
|
179
|
+
documentation: z.string().optional().meta({
|
|
180
|
+
description: "The /// comment above the field.",
|
|
181
|
+
example: "The author."
|
|
182
|
+
}),
|
|
183
|
+
default: DefaultValue,
|
|
184
|
+
nativeType: NativeType,
|
|
185
|
+
relationName: z.string().optional().meta({
|
|
186
|
+
description: "The relation this object field belongs to.",
|
|
187
|
+
example: "PostToUser"
|
|
188
|
+
}),
|
|
189
|
+
relationFromFields: z.array(z.string()).readonly().optional().meta({
|
|
190
|
+
description: "The scalar fields holding the foreign key.",
|
|
191
|
+
example: ["authorId"]
|
|
192
|
+
}),
|
|
193
|
+
relationToFields: z.array(z.string()).readonly().optional().meta({
|
|
194
|
+
description: "The fields they reference.",
|
|
195
|
+
example: ["id"]
|
|
196
|
+
}),
|
|
197
|
+
relationOnDelete: z.string().optional().meta({
|
|
198
|
+
description: "The @relation(onDelete:) action.",
|
|
199
|
+
example: "Cascade"
|
|
200
|
+
}),
|
|
201
|
+
relationOnUpdate: z.string().optional().meta({
|
|
202
|
+
description: "The @relation(onUpdate:) action.",
|
|
203
|
+
example: "Cascade"
|
|
204
|
+
})
|
|
205
|
+
}).readonly().meta({ description: "A DMMF field as Prisma parsed it" });
|
|
206
|
+
const Model = z.custom().meta({ description: "A DMMF model as Prisma parsed it" });
|
|
207
|
+
const Index = z.object({
|
|
208
|
+
model: z.string().meta({
|
|
209
|
+
description: "The model it is declared on.",
|
|
210
|
+
example: "Post"
|
|
211
|
+
}),
|
|
212
|
+
type: z.enum([
|
|
213
|
+
"id",
|
|
214
|
+
"normal",
|
|
215
|
+
"unique",
|
|
216
|
+
"fulltext"
|
|
217
|
+
]).meta({
|
|
218
|
+
description: "Which block attribute it came from.",
|
|
219
|
+
example: "unique"
|
|
220
|
+
}),
|
|
221
|
+
isDefinedOnField: z.boolean().meta({
|
|
222
|
+
description: "Whether it came from a field attribute.",
|
|
223
|
+
example: false
|
|
224
|
+
}),
|
|
225
|
+
name: z.string().nullish().meta({
|
|
226
|
+
description: "The `name:` argument, when given.",
|
|
227
|
+
example: "byEmail"
|
|
228
|
+
}),
|
|
229
|
+
dbName: z.string().nullish().meta({
|
|
230
|
+
description: "The `map:` constraint name, when given.",
|
|
231
|
+
example: "post_slug_key"
|
|
232
|
+
}),
|
|
233
|
+
fields: z.array(z.object({ name: z.string().meta({
|
|
234
|
+
description: "The field name.",
|
|
235
|
+
example: "email"
|
|
236
|
+
}) }).readonly()).readonly().meta({ description: "The fields the index covers, in order." })
|
|
237
|
+
}).readonly().meta({ description: "A DMMF index as Prisma parsed it" });
|
|
238
|
+
const DatamodelEnum = z.object({
|
|
239
|
+
name: z.string().meta({
|
|
240
|
+
description: "The enum name as declared.",
|
|
241
|
+
example: "Role"
|
|
242
|
+
}),
|
|
243
|
+
dbName: z.string().nullish().meta({
|
|
244
|
+
description: "The @@map type name, when set.",
|
|
245
|
+
example: "role"
|
|
246
|
+
}),
|
|
247
|
+
documentation: z.string().optional().meta({
|
|
248
|
+
description: "The /// comment above the block.",
|
|
249
|
+
example: "Who someone is."
|
|
250
|
+
}),
|
|
251
|
+
values: z.array(z.object({
|
|
252
|
+
name: z.string().meta({
|
|
253
|
+
description: "The member name.",
|
|
254
|
+
example: "ADMIN"
|
|
255
|
+
}),
|
|
256
|
+
dbName: z.string().nullish().meta({
|
|
257
|
+
description: "The @map stored value, when set.",
|
|
258
|
+
example: "admin"
|
|
259
|
+
})
|
|
260
|
+
}).readonly()).readonly().meta({ description: "The members of the enum, in order." })
|
|
261
|
+
}).readonly().meta({ description: "A DMMF enum as Prisma parsed it" });
|
|
262
|
+
z.object({
|
|
263
|
+
kind: z.enum([
|
|
264
|
+
"scalar",
|
|
265
|
+
"object",
|
|
266
|
+
"enum",
|
|
267
|
+
"unsupported"
|
|
268
|
+
]).meta({
|
|
269
|
+
description: "What the field holds.",
|
|
270
|
+
example: "scalar"
|
|
271
|
+
}),
|
|
272
|
+
default: DefaultValue
|
|
273
|
+
}).readonly().meta({ description: "The kind and default of a DMMF field" });
|
|
274
|
+
const DefaultCall = z.object({
|
|
275
|
+
name: z.string().meta({
|
|
276
|
+
description: "The function name.",
|
|
277
|
+
example: "now"
|
|
278
|
+
}),
|
|
279
|
+
args: z.array(z.union([
|
|
280
|
+
z.string(),
|
|
281
|
+
z.number(),
|
|
282
|
+
z.boolean()
|
|
283
|
+
])).meta({
|
|
284
|
+
description: "The literal arguments.",
|
|
285
|
+
example: []
|
|
286
|
+
})
|
|
287
|
+
}).meta({ description: "A `@default(fn(args))` value as DMMF encodes it" });
|
|
288
|
+
const DefaultList = z.array(z.union([
|
|
289
|
+
z.string(),
|
|
290
|
+
z.number(),
|
|
291
|
+
z.boolean()
|
|
292
|
+
])).meta({ description: "A `@default([...])` list value as DMMF encodes it" });
|
|
293
|
+
/**
|
|
294
|
+
* Renders a field default the way it is written in a Prisma schema: `now()`, `"anonymous"`, `VIEWER`.
|
|
295
|
+
*
|
|
296
|
+
* @param input.kind - what the field holds; an enum default is a bare member name
|
|
297
|
+
* @param input.default - the `@default` value, a literal or a function call
|
|
298
|
+
* @returns the text inside `@default(...)`, or null when the field has none
|
|
299
|
+
* @example
|
|
300
|
+
* makeDefaultText({ kind: 'scalar', default: { name: 'now', args: [] } })
|
|
301
|
+
* // 'now()'
|
|
302
|
+
*/
|
|
303
|
+
function makeDefaultText(input) {
|
|
304
|
+
const value = input.default;
|
|
305
|
+
if (value === void 0) return null;
|
|
306
|
+
const scalar = (item) => typeof item === "string" ? input.kind === "enum" ? item : JSON.stringify(item) : String(item);
|
|
307
|
+
const result = z.union([DefaultCall, DefaultList]).safeParse(value);
|
|
308
|
+
if (!result.success) return typeof value === "object" ? JSON.stringify(value) : scalar(value);
|
|
309
|
+
if (Array.isArray(result.data)) return `[${result.data.map(scalar).join(", ")}]`;
|
|
310
|
+
const args = result.data.args.map((arg) => typeof arg === "string" ? JSON.stringify(arg) : String(arg));
|
|
311
|
+
return `${result.data.name}(${args.join(", ")})`;
|
|
312
|
+
}
|
|
313
|
+
z.object({ nativeType: NativeType }).readonly().meta({ description: "The nativeType tuple of a DMMF field" });
|
|
314
|
+
/**
|
|
315
|
+
* Renders `@db.VarChar(64)` from a DMMF native type tuple.
|
|
316
|
+
*
|
|
317
|
+
* @param input.nativeType - the `@db.*` native type name and its arguments
|
|
318
|
+
* @returns the attribute, or null when the field has no native type
|
|
319
|
+
* @example
|
|
320
|
+
* makeNativeTypeAttribute({ nativeType: ['VarChar', ['64']] })
|
|
321
|
+
* // '@db.VarChar(64)'
|
|
322
|
+
*/
|
|
323
|
+
function makeNativeTypeAttribute(input) {
|
|
324
|
+
if (!input.nativeType) return null;
|
|
325
|
+
const [name, args] = input.nativeType;
|
|
326
|
+
return args.length > 0 ? `@db.${name}(${args.join(", ")})` : `@db.${name}`;
|
|
327
|
+
}
|
|
328
|
+
z.object({
|
|
329
|
+
a: z.string().meta({
|
|
330
|
+
description: "One model of the relation.",
|
|
331
|
+
example: "User"
|
|
332
|
+
}),
|
|
333
|
+
b: z.string().meta({
|
|
334
|
+
description: "The other model of the relation.",
|
|
335
|
+
example: "Post"
|
|
336
|
+
})
|
|
337
|
+
}).readonly().meta({
|
|
338
|
+
description: "The two model names of a relation",
|
|
339
|
+
example: {
|
|
340
|
+
a: "User",
|
|
341
|
+
b: "Post"
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
/**
|
|
345
|
+
* Prisma's implicit relation name: both model names sorted and joined with `To`.
|
|
346
|
+
*
|
|
347
|
+
* @param input.a - one model of the relation
|
|
348
|
+
* @param input.b - the other model of the relation
|
|
349
|
+
* @returns the relation name Prisma gives it when none is written
|
|
350
|
+
* @example
|
|
351
|
+
* makeRelationName({ a: 'User', b: 'Post' })
|
|
352
|
+
* // 'PostToUser'
|
|
353
|
+
*/
|
|
354
|
+
function makeRelationName(input) {
|
|
355
|
+
return [input.a, input.b].toSorted().join("To");
|
|
356
|
+
}
|
|
357
|
+
z.object({
|
|
358
|
+
field: Field,
|
|
359
|
+
modelName: z.string().meta({
|
|
360
|
+
description: "The model the field belongs to.",
|
|
361
|
+
example: "Post"
|
|
362
|
+
})
|
|
363
|
+
}).readonly().meta({ description: "A DMMF field and the model it belongs to" });
|
|
364
|
+
/**
|
|
365
|
+
* Renders `@relation(...)` for an object field, or null when the field carries no relation attribute.
|
|
366
|
+
*
|
|
367
|
+
* @param input.field - the DMMF field, with its relation name, `fields`, `references` and actions
|
|
368
|
+
* @param input.modelName - the model the field belongs to, to tell a written name from the implicit one
|
|
369
|
+
* @returns the attribute, or null
|
|
370
|
+
* @example
|
|
371
|
+
* makeRelationAttribute({
|
|
372
|
+
* modelName: 'Post',
|
|
373
|
+
* field: {
|
|
374
|
+
* name: 'author', kind: 'object', type: 'User', isList: false, isRequired: true, isId: false, isUnique: false,
|
|
375
|
+
* relationName: 'PostToUser', relationFromFields: ['authorId'], relationToFields: ['id'], relationOnDelete: 'Cascade',
|
|
376
|
+
* },
|
|
377
|
+
* })
|
|
378
|
+
* // '@relation(fields: [authorId], references: [id], onDelete: Cascade)'
|
|
379
|
+
*/
|
|
380
|
+
function makeRelationAttribute(input) {
|
|
381
|
+
const { field, modelName } = input;
|
|
382
|
+
if (field.kind !== "object") return null;
|
|
383
|
+
const customName = field.relationName && field.relationName !== makeRelationName({
|
|
384
|
+
a: modelName,
|
|
385
|
+
b: field.type
|
|
386
|
+
}) ? [JSON.stringify(field.relationName)] : [];
|
|
387
|
+
const fromFields = field.relationFromFields ?? [];
|
|
388
|
+
const toFields = field.relationToFields ?? [];
|
|
389
|
+
const fk = fromFields.length > 0 ? [`fields: [${fromFields.join(", ")}]`, `references: [${toFields.join(", ")}]`] : [];
|
|
390
|
+
const actions = [...field.relationOnDelete ? [`onDelete: ${field.relationOnDelete}`] : [], ...field.relationOnUpdate ? [`onUpdate: ${field.relationOnUpdate}`] : []];
|
|
391
|
+
const parts = [
|
|
392
|
+
...customName,
|
|
393
|
+
...fk,
|
|
394
|
+
...actions
|
|
395
|
+
];
|
|
396
|
+
return parts.length > 0 ? `@relation(${parts.join(", ")})` : null;
|
|
397
|
+
}
|
|
398
|
+
z.object({ documentation: z.string().optional().meta({
|
|
399
|
+
description: "The /// comment above a field or block.",
|
|
400
|
+
example: "Primary key\n@z.uuid()"
|
|
401
|
+
}) }).readonly().meta({
|
|
402
|
+
description: "A DMMF doc comment",
|
|
403
|
+
example: { documentation: "Primary key\n@z.uuid()" }
|
|
404
|
+
});
|
|
405
|
+
/**
|
|
406
|
+
* Separates hekireki annotations (`@z.uuid()`, `@relation ...`) from the prose of a doc comment.
|
|
407
|
+
*
|
|
408
|
+
* @param input.documentation - the `///` comment above a field or block
|
|
409
|
+
* @returns the prose (null when there is none) and the annotation lines
|
|
410
|
+
* @example
|
|
411
|
+
* makeDocumentation({ documentation: 'Primary key\n@z.uuid()' })
|
|
412
|
+
* // { documentation: 'Primary key', annotations: ['@z.uuid()'] }
|
|
413
|
+
*/
|
|
414
|
+
function makeDocumentation(input) {
|
|
415
|
+
const lines = (input.documentation ?? "").split("\n");
|
|
416
|
+
const annotations = lines.map((l) => l.trim()).filter((l) => isAnnotationLine(l));
|
|
417
|
+
const prose = lines.filter((l) => !isAnnotationLine(l)).join("\n").trim();
|
|
418
|
+
return {
|
|
419
|
+
documentation: prose === "" ? null : prose,
|
|
420
|
+
annotations
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
z.object({ index: Index }).readonly().meta({ description: "A DMMF index" });
|
|
424
|
+
/**
|
|
425
|
+
* Renders `@@unique([a, b], name: "x", map: "y")` and friends.
|
|
426
|
+
*
|
|
427
|
+
* @param input.index - the DMMF index: its kind, the fields it covers, and its `name:` and `map:`
|
|
428
|
+
* @returns the block attribute
|
|
429
|
+
* @example
|
|
430
|
+
* makeIndexAttribute({
|
|
431
|
+
* index: { model: 'User', type: 'unique', isDefinedOnField: false, name: null, dbName: 'user_email_key', fields: [{ name: 'email' }, { name: 'role' }] },
|
|
432
|
+
* })
|
|
433
|
+
* // '@@unique([email, role], map: "user_email_key")'
|
|
434
|
+
*/
|
|
435
|
+
function makeIndexAttribute(input) {
|
|
436
|
+
const { index } = input;
|
|
437
|
+
return `${{
|
|
438
|
+
id: "@@id",
|
|
439
|
+
unique: "@@unique",
|
|
440
|
+
normal: "@@index",
|
|
441
|
+
fulltext: "@@fulltext"
|
|
442
|
+
}[index.type]}(${[
|
|
443
|
+
`[${index.fields.map((f) => f.name).join(", ")}]`,
|
|
444
|
+
...index.name ? [`name: ${JSON.stringify(index.name)}`] : [],
|
|
445
|
+
...index.dbName ? [`map: ${JSON.stringify(index.dbName)}`] : []
|
|
446
|
+
].join(", ")})`;
|
|
447
|
+
}
|
|
448
|
+
z.object({ index: Index }).readonly().meta({ description: "A DMMF index" });
|
|
449
|
+
/** Maps a DMMF index to the studio contract. */
|
|
450
|
+
function makeIndex(input) {
|
|
451
|
+
const { index } = input;
|
|
452
|
+
return {
|
|
453
|
+
type: index.type,
|
|
454
|
+
name: index.name ?? null,
|
|
455
|
+
dbName: index.dbName ?? null,
|
|
456
|
+
fields: index.fields.map((f) => f.name),
|
|
457
|
+
attribute: makeIndexAttribute(input)
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
z.object({ model: Model }).readonly().meta({ description: "A DMMF model" });
|
|
461
|
+
/** Names of the scalar fields that back a relation (`@relation(fields: [...])`) on the model. */
|
|
462
|
+
function makeForeignKeyFields(input) {
|
|
463
|
+
return new Set(input.model.fields.flatMap((f) => f.kind === "object" ? f.relationFromFields ?? [] : []));
|
|
464
|
+
}
|
|
465
|
+
z.object({
|
|
466
|
+
field: Field,
|
|
467
|
+
modelName: z.string().meta({
|
|
468
|
+
description: "The model the field belongs to.",
|
|
469
|
+
example: "Post"
|
|
470
|
+
}),
|
|
471
|
+
foreignKeys: z.set(z.string()).meta({ description: "The names of the fields that hold a foreign key." })
|
|
472
|
+
}).readonly().meta({ description: "A DMMF field with its model name and the model foreign-key field names" });
|
|
473
|
+
/** Maps a DMMF field to the studio contract, rendering its attributes as Prisma writes them. */
|
|
474
|
+
function makeField(input) {
|
|
475
|
+
const { field, modelName, foreignKeys } = input;
|
|
476
|
+
const defaultValue = makeDefaultText({
|
|
477
|
+
kind: field.kind,
|
|
478
|
+
default: field.default
|
|
479
|
+
});
|
|
480
|
+
const nativeType = makeNativeTypeAttribute({ nativeType: field.nativeType });
|
|
481
|
+
const relationAttribute = makeRelationAttribute({
|
|
482
|
+
field,
|
|
483
|
+
modelName
|
|
484
|
+
});
|
|
485
|
+
const docs = makeDocumentation({ documentation: field.documentation });
|
|
486
|
+
const attributes = [
|
|
487
|
+
...field.isId ? ["@id"] : [],
|
|
488
|
+
...field.isUnique ? ["@unique"] : [],
|
|
489
|
+
...defaultValue === null ? [] : [`@default(${defaultValue})`],
|
|
490
|
+
...field.isUpdatedAt ? ["@updatedAt"] : [],
|
|
491
|
+
...field.dbName ? [`@map(${JSON.stringify(field.dbName)})`] : [],
|
|
492
|
+
...nativeType === null ? [] : [nativeType],
|
|
493
|
+
...relationAttribute === null ? [] : [relationAttribute]
|
|
494
|
+
];
|
|
495
|
+
const relation = field.kind === "object" && field.relationName ? {
|
|
496
|
+
name: field.relationName,
|
|
497
|
+
fromFields: [...field.relationFromFields ?? []],
|
|
498
|
+
toFields: [...field.relationToFields ?? []],
|
|
499
|
+
onDelete: field.relationOnDelete ?? null,
|
|
500
|
+
onUpdate: field.relationOnUpdate ?? null
|
|
501
|
+
} : null;
|
|
502
|
+
return {
|
|
503
|
+
name: field.name,
|
|
504
|
+
dbName: field.dbName ?? null,
|
|
505
|
+
kind: field.kind,
|
|
506
|
+
type: field.type,
|
|
507
|
+
isList: field.isList,
|
|
508
|
+
isRequired: field.isRequired,
|
|
509
|
+
isId: field.isId,
|
|
510
|
+
isUnique: field.isUnique,
|
|
511
|
+
isUpdatedAt: field.isUpdatedAt ?? false,
|
|
512
|
+
isForeignKey: foreignKeys.has(field.name),
|
|
513
|
+
default: defaultValue,
|
|
514
|
+
nativeType,
|
|
515
|
+
documentation: docs.documentation,
|
|
516
|
+
annotations: docs.annotations,
|
|
517
|
+
relation,
|
|
518
|
+
attributes
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
z.object({
|
|
522
|
+
blocks: z.array(z.object({
|
|
523
|
+
type: z.enum([
|
|
524
|
+
"model",
|
|
525
|
+
"view",
|
|
526
|
+
"type",
|
|
527
|
+
"enum",
|
|
528
|
+
"datasource",
|
|
529
|
+
"generator"
|
|
530
|
+
]).meta({
|
|
531
|
+
description: "The block keyword.",
|
|
532
|
+
example: "model"
|
|
533
|
+
}),
|
|
534
|
+
name: z.string().meta({
|
|
535
|
+
description: "The declared name.",
|
|
536
|
+
example: "User"
|
|
537
|
+
}),
|
|
538
|
+
file: z.string().meta({
|
|
539
|
+
description: "The file as Studio loaded it.",
|
|
540
|
+
example: "prisma/schema.prisma"
|
|
541
|
+
}),
|
|
542
|
+
line: z.number().int().min(1).meta({
|
|
543
|
+
description: "The 1-based line of the block header.",
|
|
544
|
+
example: 7
|
|
545
|
+
})
|
|
546
|
+
}).readonly()).readonly().meta({ description: "Every block of the loaded files, as the language server lists them." }),
|
|
547
|
+
types: z.array(z.enum([
|
|
548
|
+
"model",
|
|
549
|
+
"view",
|
|
550
|
+
"type",
|
|
551
|
+
"enum",
|
|
552
|
+
"datasource",
|
|
553
|
+
"generator"
|
|
554
|
+
])).readonly().meta({
|
|
555
|
+
description: "The block kinds that count.",
|
|
556
|
+
example: ["model", "view"]
|
|
557
|
+
}),
|
|
558
|
+
name: z.string().meta({
|
|
559
|
+
description: "The block name.",
|
|
560
|
+
example: "User"
|
|
561
|
+
})
|
|
562
|
+
}).readonly().meta({
|
|
563
|
+
description: "The outlined blocks and the one to locate",
|
|
564
|
+
example: {
|
|
565
|
+
blocks: [],
|
|
566
|
+
types: ["model", "view"],
|
|
567
|
+
name: "User"
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
/**
|
|
571
|
+
* The file and 1-based line of the first block of one of the kinds with the name, or null.
|
|
572
|
+
*
|
|
573
|
+
* @param input.blocks - every block of the loaded files, as the language server lists them
|
|
574
|
+
* @param input.types - the block kinds that count
|
|
575
|
+
* @param input.name - the block name
|
|
576
|
+
* @returns where the block is declared, or null when no block matches
|
|
577
|
+
* @example
|
|
578
|
+
* makeLocation({
|
|
579
|
+
* blocks: [{ type: 'model', name: 'User', file: 'schema.prisma', line: 7 }],
|
|
580
|
+
* types: ['model', 'view'],
|
|
581
|
+
* name: 'User',
|
|
582
|
+
* })
|
|
583
|
+
* // { file: 'schema.prisma', line: 7 }
|
|
584
|
+
*/
|
|
585
|
+
function makeLocation(input) {
|
|
586
|
+
const types = new Set(input.types);
|
|
587
|
+
const block = input.blocks.find((b) => types.has(b.type) && b.name === input.name);
|
|
588
|
+
return block === void 0 ? null : {
|
|
589
|
+
file: block.file,
|
|
590
|
+
line: block.line
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
z.object({
|
|
594
|
+
model: Model,
|
|
595
|
+
indexes: z.array(Index).readonly().meta({ description: "Every index of the datamodel." }),
|
|
596
|
+
blocks: z.array(z.object({
|
|
597
|
+
type: z.enum([
|
|
598
|
+
"model",
|
|
599
|
+
"view",
|
|
600
|
+
"type",
|
|
601
|
+
"enum",
|
|
602
|
+
"datasource",
|
|
603
|
+
"generator"
|
|
604
|
+
]).meta({
|
|
605
|
+
description: "The block keyword.",
|
|
606
|
+
example: "model"
|
|
607
|
+
}),
|
|
608
|
+
name: z.string().meta({
|
|
609
|
+
description: "The declared name.",
|
|
610
|
+
example: "User"
|
|
611
|
+
}),
|
|
612
|
+
file: z.string().meta({
|
|
613
|
+
description: "The file as Studio loaded it.",
|
|
614
|
+
example: "prisma/schema.prisma"
|
|
615
|
+
}),
|
|
616
|
+
line: z.number().int().min(1).meta({
|
|
617
|
+
description: "The 1-based line of the block header.",
|
|
618
|
+
example: 7
|
|
619
|
+
})
|
|
620
|
+
}).readonly()).readonly().meta({ description: "Every block of the loaded files, as the language server lists them." })
|
|
621
|
+
}).readonly().meta({ description: "A DMMF model, the datamodel indexes and the outlined blocks" });
|
|
622
|
+
/** Maps a DMMF model to the studio contract, with block-level indexes and `@@` attributes rendered. */
|
|
623
|
+
function makeModel(input) {
|
|
624
|
+
const { model, indexes, blocks } = input;
|
|
625
|
+
const blockIndexes = indexes.filter((i) => i.model === model.name && !i.isDefinedOnField).map((index) => makeIndex({ index }));
|
|
626
|
+
const docs = makeDocumentation({ documentation: model.documentation });
|
|
627
|
+
const foreignKeys = makeForeignKeyFields({ model });
|
|
628
|
+
return {
|
|
629
|
+
name: model.name,
|
|
630
|
+
dbName: model.dbName ?? null,
|
|
631
|
+
documentation: docs.documentation,
|
|
632
|
+
annotations: docs.annotations,
|
|
633
|
+
fields: model.fields.map((field) => makeField({
|
|
634
|
+
field,
|
|
635
|
+
modelName: model.name,
|
|
636
|
+
foreignKeys
|
|
637
|
+
})),
|
|
638
|
+
primaryKey: model.primaryKey ? [...model.primaryKey.fields] : null,
|
|
639
|
+
indexes: blockIndexes,
|
|
640
|
+
attributes: [
|
|
641
|
+
...blockIndexes.map((i) => i.attribute),
|
|
642
|
+
...model.dbName ? [`@@map(${JSON.stringify(model.dbName)})`] : [],
|
|
643
|
+
...model.schema ? [`@@schema(${JSON.stringify(model.schema)})`] : []
|
|
644
|
+
],
|
|
645
|
+
location: makeLocation({
|
|
646
|
+
blocks,
|
|
647
|
+
types: ["model", "view"],
|
|
648
|
+
name: model.name
|
|
649
|
+
})
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
z.object({
|
|
653
|
+
value: DatamodelEnum,
|
|
654
|
+
blocks: z.array(z.object({
|
|
655
|
+
type: z.enum([
|
|
656
|
+
"model",
|
|
657
|
+
"view",
|
|
658
|
+
"type",
|
|
659
|
+
"enum",
|
|
660
|
+
"datasource",
|
|
661
|
+
"generator"
|
|
662
|
+
]).meta({
|
|
663
|
+
description: "The block keyword.",
|
|
664
|
+
example: "model"
|
|
665
|
+
}),
|
|
666
|
+
name: z.string().meta({
|
|
667
|
+
description: "The declared name.",
|
|
668
|
+
example: "User"
|
|
669
|
+
}),
|
|
670
|
+
file: z.string().meta({
|
|
671
|
+
description: "The file as Studio loaded it.",
|
|
672
|
+
example: "prisma/schema.prisma"
|
|
673
|
+
}),
|
|
674
|
+
line: z.number().int().min(1).meta({
|
|
675
|
+
description: "The 1-based line of the block header.",
|
|
676
|
+
example: 7
|
|
677
|
+
})
|
|
678
|
+
}).readonly()).readonly().meta({ description: "Every block of the loaded files, as the language server lists them." })
|
|
679
|
+
}).readonly().meta({ description: "A DMMF enum and the outlined blocks" });
|
|
680
|
+
/** Maps a DMMF enum to the studio contract. */
|
|
681
|
+
function makeEnum(input) {
|
|
682
|
+
const { value, blocks } = input;
|
|
683
|
+
return {
|
|
684
|
+
name: value.name,
|
|
685
|
+
dbName: value.dbName ?? null,
|
|
686
|
+
documentation: makeDocumentation({ documentation: value.documentation }).documentation,
|
|
687
|
+
values: value.values.map((v) => ({
|
|
688
|
+
name: v.name,
|
|
689
|
+
dbName: v.dbName ?? null
|
|
690
|
+
})),
|
|
691
|
+
location: makeLocation({
|
|
692
|
+
blocks,
|
|
693
|
+
types: ["enum"],
|
|
694
|
+
name: value.name
|
|
695
|
+
})
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
z.object({ models: z.array(Model).readonly().meta({ description: "Every model of the datamodel." }) }).readonly().meta({ description: "The DMMF models of a datamodel" });
|
|
699
|
+
/**
|
|
700
|
+
* Foreign-key, `/// @relation` and implicit many-to-many relations in the studio contract.
|
|
701
|
+
*
|
|
702
|
+
* @param input.models - every model of the datamodel
|
|
703
|
+
* @returns each relation with its id, name, origin, both ends and its referential actions
|
|
704
|
+
* @example
|
|
705
|
+
* // dmmf parsed from `model User { id Int @id posts Post[] }` and
|
|
706
|
+
* // `model Post { id Int @id authorId Int author User @relation(fields: [authorId], references: [id], onDelete: Cascade) }`
|
|
707
|
+
* makeRelations({ models: dmmf.datamodel.models }).map((relation) => [relation.id, relation.name, relation.onDelete])
|
|
708
|
+
* // [['User.id->Post.authorId', 'PostToUser', 'Cascade']]
|
|
709
|
+
*/
|
|
710
|
+
function makeRelations(input) {
|
|
711
|
+
const { models } = input;
|
|
712
|
+
const byName = new Map(models.map((m) => [m.name, m]));
|
|
713
|
+
return erRelations(models).map((relation) => {
|
|
714
|
+
const fkField = byName.get(relation.to.model)?.fields.find((f) => f.kind === "object" && f.type === relation.from.model && (f.relationFromFields ?? []).includes(relation.to.field));
|
|
715
|
+
return {
|
|
716
|
+
id: erKey(relation),
|
|
717
|
+
name: relation.name ?? fkField?.relationName ?? null,
|
|
718
|
+
origin: relation.origin,
|
|
719
|
+
from: relation.from,
|
|
720
|
+
to: relation.to,
|
|
721
|
+
onDelete: fkField?.relationOnDelete ?? null,
|
|
722
|
+
onUpdate: fkField?.relationOnUpdate ?? null
|
|
723
|
+
};
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
z.object({
|
|
727
|
+
dmmf: z.object({ datamodel: z.object({
|
|
728
|
+
models: z.array(Model).readonly().meta({ description: "Every model block." }),
|
|
729
|
+
enums: z.array(DatamodelEnum).readonly().meta({ description: "Every enum block." }),
|
|
730
|
+
indexes: z.array(Index).readonly().meta({ description: "Every index of every model." })
|
|
731
|
+
}).readonly().meta({ description: "The blocks Prisma parsed from the files." }) }).readonly().meta({ description: "The document Prisma parsed from the files." }),
|
|
732
|
+
files: z.array(z.object({
|
|
733
|
+
path: z.string().meta({
|
|
734
|
+
description: "The file path as Studio loaded it.",
|
|
735
|
+
example: "prisma/schema.prisma"
|
|
736
|
+
}),
|
|
737
|
+
content: z.string().meta({
|
|
738
|
+
description: "The whole file content.",
|
|
739
|
+
example: "model User {\n id Int @id\n}\n"
|
|
740
|
+
})
|
|
741
|
+
}).readonly()).readonly().meta({ description: "The loaded schema files." }),
|
|
742
|
+
provider: z.string().nullable().meta({
|
|
743
|
+
description: "The provider of the first datasource, as Prisma read it.",
|
|
744
|
+
example: "postgresql"
|
|
745
|
+
}),
|
|
746
|
+
blocks: z.array(z.object({
|
|
747
|
+
type: z.enum([
|
|
748
|
+
"model",
|
|
749
|
+
"view",
|
|
750
|
+
"type",
|
|
751
|
+
"enum",
|
|
752
|
+
"datasource",
|
|
753
|
+
"generator"
|
|
754
|
+
]).meta({
|
|
755
|
+
description: "The block keyword.",
|
|
756
|
+
example: "model"
|
|
757
|
+
}),
|
|
758
|
+
name: z.string().meta({
|
|
759
|
+
description: "The declared name.",
|
|
760
|
+
example: "User"
|
|
761
|
+
}),
|
|
762
|
+
file: z.string().meta({
|
|
763
|
+
description: "The file as Studio loaded it.",
|
|
764
|
+
example: "prisma/schema.prisma"
|
|
765
|
+
}),
|
|
766
|
+
line: z.number().int().min(1).meta({
|
|
767
|
+
description: "The 1-based line of the block header.",
|
|
768
|
+
example: 7
|
|
769
|
+
})
|
|
770
|
+
}).readonly()).readonly().meta({ description: "Every block of the loaded files, as the language server lists them." })
|
|
771
|
+
}).readonly().meta({ description: "A parsed DMMF document, the files it came from, the datasource provider and the outlined blocks" });
|
|
772
|
+
/**
|
|
773
|
+
* The whole studio schema contract from a DMMF document.
|
|
774
|
+
*
|
|
775
|
+
* @param input.dmmf - the document Prisma parsed from the files: its models, enums and indexes
|
|
776
|
+
* @param input.files - the loaded schema files
|
|
777
|
+
* @param input.provider - the provider of the first datasource, as Prisma read it
|
|
778
|
+
* @param input.blocks - every block of the loaded files, as the language server lists them
|
|
779
|
+
* @returns the files, the provider, the models and enums with their attributes rendered, and the relations
|
|
780
|
+
* @example
|
|
781
|
+
* // dmmf parsed from `model User { id Int @id posts Post[] }` and
|
|
782
|
+
* // `model Post { id Int @id authorId Int author User @relation(fields: [authorId], references: [id], onDelete: Cascade) }`
|
|
783
|
+
* makeSchema({ dmmf, files, provider: 'sqlite', blocks: [] }).models[1].fields[2].attributes
|
|
784
|
+
* // ['@relation(fields: [authorId], references: [id], onDelete: Cascade)']
|
|
785
|
+
*/
|
|
786
|
+
function makeSchema(input) {
|
|
787
|
+
const { dmmf, files, provider, blocks } = input;
|
|
788
|
+
const { models, enums, indexes } = dmmf.datamodel;
|
|
789
|
+
return {
|
|
790
|
+
files: files.map((f) => ({
|
|
791
|
+
path: f.path,
|
|
792
|
+
content: f.content
|
|
793
|
+
})),
|
|
794
|
+
provider,
|
|
795
|
+
models: models.map((model) => makeModel({
|
|
796
|
+
model,
|
|
797
|
+
indexes,
|
|
798
|
+
blocks
|
|
799
|
+
})),
|
|
800
|
+
enums: enums.map((value) => makeEnum({
|
|
801
|
+
value,
|
|
802
|
+
blocks
|
|
803
|
+
})),
|
|
804
|
+
relations: makeRelations({ models })
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
const AnalysisDialect = z.enum([
|
|
808
|
+
"postgresql",
|
|
809
|
+
"mysql",
|
|
810
|
+
"sqlite"
|
|
811
|
+
]).meta({
|
|
812
|
+
description: "The SQL dialect the analysis reads types for",
|
|
813
|
+
example: "postgresql"
|
|
814
|
+
});
|
|
815
|
+
z.object({
|
|
816
|
+
dialect: AnalysisDialect.nullable().meta({
|
|
817
|
+
description: "The dialect of the connected database, or null while none is connected.",
|
|
818
|
+
example: "sqlite"
|
|
819
|
+
}),
|
|
820
|
+
provider: z.string().nullable().meta({
|
|
821
|
+
description: "The datasource provider of the schema, the fallback for the dialect.",
|
|
822
|
+
example: "postgresql"
|
|
823
|
+
}),
|
|
824
|
+
models: z.array(z.object({
|
|
825
|
+
name: z.string().meta({
|
|
826
|
+
description: "The model name as declared.",
|
|
827
|
+
example: "User"
|
|
828
|
+
}),
|
|
829
|
+
dbName: z.string().nullable().meta({
|
|
830
|
+
description: "The @@map table name, when set.",
|
|
831
|
+
example: "users"
|
|
832
|
+
}),
|
|
833
|
+
fields: z.array(z.object({
|
|
834
|
+
name: z.string().meta({
|
|
835
|
+
description: "The Prisma field name.",
|
|
836
|
+
example: "createdAt"
|
|
837
|
+
}),
|
|
838
|
+
dbName: z.string().nullable().meta({
|
|
839
|
+
description: "The @map column name, when set.",
|
|
840
|
+
example: "created_at"
|
|
841
|
+
}),
|
|
842
|
+
kind: z.string().meta({
|
|
843
|
+
description: "scalar, object, enum or unsupported.",
|
|
844
|
+
example: "scalar"
|
|
845
|
+
}),
|
|
846
|
+
type: z.string().meta({
|
|
847
|
+
description: "The declared type.",
|
|
848
|
+
example: "DateTime"
|
|
849
|
+
}),
|
|
850
|
+
isList: z.boolean().meta({
|
|
851
|
+
description: "Whether the field is a list.",
|
|
852
|
+
example: false
|
|
853
|
+
}),
|
|
854
|
+
isRequired: z.boolean().meta({
|
|
855
|
+
description: "Whether the field is required.",
|
|
856
|
+
example: true
|
|
857
|
+
}),
|
|
858
|
+
nativeType: z.string().nullable().meta({
|
|
859
|
+
description: "The `@db.*` attribute as written, when declared.",
|
|
860
|
+
example: "@db.VarChar(255)"
|
|
861
|
+
})
|
|
862
|
+
}).readonly()).readonly().meta({ description: "The fields of the model, relations included." })
|
|
863
|
+
}).readonly()).readonly().meta({ description: "The models of the schema." })
|
|
864
|
+
}).readonly().meta({
|
|
865
|
+
description: "The Prisma models the SQL analysis reads its tables from",
|
|
866
|
+
example: {
|
|
867
|
+
dialect: "sqlite",
|
|
868
|
+
provider: "sqlite",
|
|
869
|
+
models: []
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
/** The column type Prisma migrates a scalar to when no `@db.*` attribute says otherwise. */
|
|
873
|
+
const PRISMA_COLUMN_TYPES = {
|
|
874
|
+
postgresql: {
|
|
875
|
+
Int: "int4",
|
|
876
|
+
BigInt: "int8",
|
|
877
|
+
Float: "float8",
|
|
878
|
+
Decimal: "numeric",
|
|
879
|
+
String: "text",
|
|
880
|
+
Boolean: "bool",
|
|
881
|
+
DateTime: "timestamp",
|
|
882
|
+
Json: "jsonb",
|
|
883
|
+
Bytes: "bytea"
|
|
884
|
+
},
|
|
885
|
+
mysql: {
|
|
886
|
+
Int: "int",
|
|
887
|
+
BigInt: "bigint",
|
|
888
|
+
Float: "double",
|
|
889
|
+
Decimal: "decimal",
|
|
890
|
+
String: "varchar",
|
|
891
|
+
Boolean: "tinyint",
|
|
892
|
+
DateTime: "datetime",
|
|
893
|
+
Json: "json",
|
|
894
|
+
Bytes: "longblob"
|
|
895
|
+
},
|
|
896
|
+
sqlite: {
|
|
897
|
+
Int: "INTEGER",
|
|
898
|
+
BigInt: "BIGINT",
|
|
899
|
+
Float: "REAL",
|
|
900
|
+
Decimal: "DECIMAL",
|
|
901
|
+
String: "TEXT",
|
|
902
|
+
Boolean: "BOOLEAN",
|
|
903
|
+
DateTime: "DATETIME",
|
|
904
|
+
Json: "JSONB",
|
|
905
|
+
Bytes: "BLOB"
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
/** An enum column is stored as text everywhere; MySQL has its own `enum` type for it. */
|
|
909
|
+
const ENUM_COLUMN_TYPES = {
|
|
910
|
+
postgresql: "text",
|
|
911
|
+
mysql: "enum",
|
|
912
|
+
sqlite: "TEXT"
|
|
913
|
+
};
|
|
914
|
+
function analysisDialect(input) {
|
|
915
|
+
if (input.dialect !== null) return input.dialect;
|
|
916
|
+
const result = AnalysisDialect.safeParse(input.provider);
|
|
917
|
+
return result.success ? result.data : "sqlite";
|
|
918
|
+
}
|
|
919
|
+
function columnDataType(dialect, field) {
|
|
920
|
+
const base = (field.nativeType === null ? null : field.nativeType.replace(/^@db\./u, "")) ?? (field.kind === "enum" ? ENUM_COLUMN_TYPES[dialect] : PRISMA_COLUMN_TYPES[dialect][field.type] ?? "unknown");
|
|
921
|
+
return field.isList && dialect === "postgresql" ? `${base}[]` : base;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* The tables the SQL analysis runs against, read off the Prisma models: `@@map` / `@map` give
|
|
925
|
+
* the names the database knows, relation fields are left out (they are not columns), and a
|
|
926
|
+
* scalar's column type is its `@db.*` attribute or the type Prisma migrates it to.
|
|
927
|
+
*
|
|
928
|
+
* @param input.dialect - the dialect of the connected database, or null while none is connected
|
|
929
|
+
* @param input.provider - the datasource provider of the schema, the fallback for the dialect
|
|
930
|
+
* @param input.models - the models of the schema, relations included
|
|
931
|
+
* @returns the dialect the analysis reads types for, and the tables with their columns
|
|
932
|
+
* @example
|
|
933
|
+
* makeAnalysisSchema({
|
|
934
|
+
* dialect: null,
|
|
935
|
+
* provider: 'postgresql',
|
|
936
|
+
* models: [{ name: 'User', dbName: 'users', fields: [
|
|
937
|
+
* { name: 'tags', dbName: null, kind: 'scalar', type: 'String', isList: true, isRequired: true, nativeType: null },
|
|
938
|
+
* { name: 'posts', dbName: null, kind: 'object', type: 'Post', isList: true, isRequired: true, nativeType: null },
|
|
939
|
+
* ] }],
|
|
940
|
+
* })
|
|
941
|
+
* // { dialect: 'postgresql', tables: [{ name: 'users', columns: [{ name: 'tags', dataType: 'text[]', nullable: false }] }] }
|
|
942
|
+
*/
|
|
943
|
+
function makeAnalysisSchema(input) {
|
|
944
|
+
const dialect = analysisDialect(input);
|
|
945
|
+
return {
|
|
946
|
+
dialect,
|
|
947
|
+
tables: input.models.map((model) => ({
|
|
948
|
+
name: model.dbName ?? model.name,
|
|
949
|
+
columns: model.fields.filter((field) => field.kind !== "object").map((field) => ({
|
|
950
|
+
name: field.dbName ?? field.name,
|
|
951
|
+
dataType: columnDataType(dialect, field),
|
|
952
|
+
nullable: !field.isRequired
|
|
953
|
+
}))
|
|
954
|
+
}))
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
// src/migrate/adapter/column-types.ts
|
|
958
|
+
/**
|
|
959
|
+
* The `ColumnType` codes the Prisma schema engine reads a result set by; it converts every value
|
|
960
|
+
* it is handed according to the code the column was given, so a wrong code is a wrong value.
|
|
961
|
+
* Taken from `ColumnTypeEnum` of `@prisma/driver-adapter-utils`.
|
|
962
|
+
*/
|
|
963
|
+
const COLUMN_TYPE = {
|
|
964
|
+
int32: 0,
|
|
965
|
+
int64: 1,
|
|
966
|
+
float: 2,
|
|
967
|
+
double: 3,
|
|
968
|
+
numeric: 4,
|
|
969
|
+
boolean: 5,
|
|
970
|
+
character: 6,
|
|
971
|
+
text: 7,
|
|
972
|
+
date: 8,
|
|
973
|
+
time: 9,
|
|
974
|
+
datetime: 10,
|
|
975
|
+
json: 11,
|
|
976
|
+
enum: 12,
|
|
977
|
+
bytes: 13,
|
|
978
|
+
set: 14,
|
|
979
|
+
uuid: 15,
|
|
980
|
+
int32Array: 64,
|
|
981
|
+
int64Array: 65,
|
|
982
|
+
floatArray: 66,
|
|
983
|
+
doubleArray: 67,
|
|
984
|
+
numericArray: 68,
|
|
985
|
+
booleanArray: 69,
|
|
986
|
+
characterArray: 70,
|
|
987
|
+
textArray: 71,
|
|
988
|
+
dateArray: 72,
|
|
989
|
+
timeArray: 73,
|
|
990
|
+
datetimeArray: 74,
|
|
991
|
+
jsonArray: 75,
|
|
992
|
+
enumArray: 76,
|
|
993
|
+
bytesArray: 77,
|
|
994
|
+
uuidArray: 78
|
|
995
|
+
};
|
|
996
|
+
/** The type OID of `pg_type`, as `pg` reports it on every column it returns. */
|
|
997
|
+
const POSTGRES_OIDS = {
|
|
998
|
+
16: COLUMN_TYPE.boolean,
|
|
999
|
+
17: COLUMN_TYPE.bytes,
|
|
1000
|
+
18: COLUMN_TYPE.character,
|
|
1001
|
+
19: COLUMN_TYPE.text,
|
|
1002
|
+
20: COLUMN_TYPE.int64,
|
|
1003
|
+
21: COLUMN_TYPE.int32,
|
|
1004
|
+
23: COLUMN_TYPE.int32,
|
|
1005
|
+
25: COLUMN_TYPE.text,
|
|
1006
|
+
26: COLUMN_TYPE.int64,
|
|
1007
|
+
114: COLUMN_TYPE.json,
|
|
1008
|
+
700: COLUMN_TYPE.float,
|
|
1009
|
+
701: COLUMN_TYPE.double,
|
|
1010
|
+
1042: COLUMN_TYPE.character,
|
|
1011
|
+
1043: COLUMN_TYPE.text,
|
|
1012
|
+
1082: COLUMN_TYPE.date,
|
|
1013
|
+
1083: COLUMN_TYPE.time,
|
|
1014
|
+
1114: COLUMN_TYPE.datetime,
|
|
1015
|
+
1184: COLUMN_TYPE.datetime,
|
|
1016
|
+
1266: COLUMN_TYPE.time,
|
|
1017
|
+
1700: COLUMN_TYPE.numeric,
|
|
1018
|
+
2950: COLUMN_TYPE.uuid,
|
|
1019
|
+
3802: COLUMN_TYPE.json,
|
|
1020
|
+
1e3: COLUMN_TYPE.booleanArray,
|
|
1021
|
+
1001: COLUMN_TYPE.bytesArray,
|
|
1022
|
+
1002: COLUMN_TYPE.characterArray,
|
|
1023
|
+
1005: COLUMN_TYPE.int32Array,
|
|
1024
|
+
1007: COLUMN_TYPE.int32Array,
|
|
1025
|
+
1009: COLUMN_TYPE.textArray,
|
|
1026
|
+
1014: COLUMN_TYPE.characterArray,
|
|
1027
|
+
1015: COLUMN_TYPE.textArray,
|
|
1028
|
+
1016: COLUMN_TYPE.int64Array,
|
|
1029
|
+
1021: COLUMN_TYPE.floatArray,
|
|
1030
|
+
1022: COLUMN_TYPE.doubleArray,
|
|
1031
|
+
1028: COLUMN_TYPE.int64Array,
|
|
1032
|
+
1115: COLUMN_TYPE.datetimeArray,
|
|
1033
|
+
1182: COLUMN_TYPE.dateArray,
|
|
1034
|
+
1183: COLUMN_TYPE.timeArray,
|
|
1035
|
+
1185: COLUMN_TYPE.datetimeArray,
|
|
1036
|
+
1231: COLUMN_TYPE.numericArray,
|
|
1037
|
+
199: COLUMN_TYPE.jsonArray,
|
|
1038
|
+
3807: COLUMN_TYPE.jsonArray,
|
|
1039
|
+
2951: COLUMN_TYPE.uuidArray
|
|
1040
|
+
};
|
|
1041
|
+
/** The type code of the MySQL protocol, as `mysql2` reports it on every column. */
|
|
1042
|
+
const MYSQL_CODES = {
|
|
1043
|
+
0: COLUMN_TYPE.numeric,
|
|
1044
|
+
1: COLUMN_TYPE.int32,
|
|
1045
|
+
2: COLUMN_TYPE.int32,
|
|
1046
|
+
3: COLUMN_TYPE.int32,
|
|
1047
|
+
4: COLUMN_TYPE.float,
|
|
1048
|
+
5: COLUMN_TYPE.double,
|
|
1049
|
+
7: COLUMN_TYPE.datetime,
|
|
1050
|
+
8: COLUMN_TYPE.int64,
|
|
1051
|
+
9: COLUMN_TYPE.int32,
|
|
1052
|
+
10: COLUMN_TYPE.date,
|
|
1053
|
+
11: COLUMN_TYPE.time,
|
|
1054
|
+
12: COLUMN_TYPE.datetime,
|
|
1055
|
+
13: COLUMN_TYPE.int32,
|
|
1056
|
+
15: COLUMN_TYPE.text,
|
|
1057
|
+
16: COLUMN_TYPE.bytes,
|
|
1058
|
+
245: COLUMN_TYPE.json,
|
|
1059
|
+
246: COLUMN_TYPE.numeric,
|
|
1060
|
+
247: COLUMN_TYPE.enum,
|
|
1061
|
+
248: COLUMN_TYPE.set,
|
|
1062
|
+
249: COLUMN_TYPE.bytes,
|
|
1063
|
+
250: COLUMN_TYPE.bytes,
|
|
1064
|
+
251: COLUMN_TYPE.bytes,
|
|
1065
|
+
252: COLUMN_TYPE.bytes,
|
|
1066
|
+
253: COLUMN_TYPE.text,
|
|
1067
|
+
254: COLUMN_TYPE.text,
|
|
1068
|
+
255: COLUMN_TYPE.bytes
|
|
1069
|
+
};
|
|
1070
|
+
/** The declared type of a SQLite column; a `PRAGMA` or an expression has none. */
|
|
1071
|
+
function sqliteColumnType(declared) {
|
|
1072
|
+
const upper = declared.toUpperCase().replace(/\(.*\)$/u, "").trim();
|
|
1073
|
+
if (upper === "BOOLEAN") return COLUMN_TYPE.boolean;
|
|
1074
|
+
if (upper === "DATETIME" || upper === "TIMESTAMP") return COLUMN_TYPE.datetime;
|
|
1075
|
+
if (upper === "DATE") return COLUMN_TYPE.date;
|
|
1076
|
+
if (upper === "TIME") return COLUMN_TYPE.time;
|
|
1077
|
+
if (upper === "JSON" || upper === "JSONB") return COLUMN_TYPE.json;
|
|
1078
|
+
if (upper === "BLOB") return COLUMN_TYPE.bytes;
|
|
1079
|
+
if (upper === "DECIMAL" || upper === "NUMERIC") return COLUMN_TYPE.numeric;
|
|
1080
|
+
const affinity = sqliteAffinity(upper);
|
|
1081
|
+
if (affinity === "integer") return COLUMN_TYPE.int64;
|
|
1082
|
+
if (affinity === "text") return COLUMN_TYPE.text;
|
|
1083
|
+
if (affinity === "real") return COLUMN_TYPE.double;
|
|
1084
|
+
return null;
|
|
1085
|
+
}
|
|
1086
|
+
/** What a value says about its column, for a column the database gives no type for. */
|
|
1087
|
+
function columnTypeOfValue(value) {
|
|
1088
|
+
if (typeof value === "bigint") return COLUMN_TYPE.int64;
|
|
1089
|
+
if (typeof value === "number") return Number.isInteger(value) ? COLUMN_TYPE.int32 : COLUMN_TYPE.double;
|
|
1090
|
+
if (typeof value === "boolean") return COLUMN_TYPE.boolean;
|
|
1091
|
+
if (value instanceof Uint8Array) return COLUMN_TYPE.bytes;
|
|
1092
|
+
return COLUMN_TYPE.text;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* The `ColumnType` of a column as the database types it: the OID on PostgreSQL, the protocol type
|
|
1096
|
+
* code on MySQL, the declared type on SQLite. Null for a type not listed, and for the columns of a
|
|
1097
|
+
* `PRAGMA`, so the caller reads those from the values instead.
|
|
1098
|
+
*/
|
|
1099
|
+
function columnTypeOfNative(dialect, nativeType) {
|
|
1100
|
+
if (nativeType === null) return null;
|
|
1101
|
+
if (dialect === "postgresql") return typeof nativeType === "number" ? POSTGRES_OIDS[nativeType] ?? null : null;
|
|
1102
|
+
if (dialect === "mysql") return typeof nativeType === "number" ? MYSQL_CODES[nativeType] ?? null : null;
|
|
1103
|
+
return typeof nativeType === "string" ? sqliteColumnType(nativeType) : null;
|
|
1104
|
+
}
|
|
1105
|
+
// src/migrate/adapter/engine-adapter.ts
|
|
1106
|
+
function engineSuccess(value) {
|
|
1107
|
+
return {
|
|
1108
|
+
ok: true,
|
|
1109
|
+
value,
|
|
1110
|
+
map: (fn) => engineSuccess(fn(value)),
|
|
1111
|
+
flatMap: (fn) => fn(value)
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
function engineFailure(error) {
|
|
1115
|
+
return {
|
|
1116
|
+
ok: false,
|
|
1117
|
+
error,
|
|
1118
|
+
map: () => engineFailure(error),
|
|
1119
|
+
flatMap: () => engineFailure(error)
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* A driver failure as the engine reads it. The message is what reaches the user; the codes are
|
|
1124
|
+
* each dialect's "unspecified error", because `Driver` reports a failure as its message and the
|
|
1125
|
+
* engine acts on none of the others.
|
|
1126
|
+
*/
|
|
1127
|
+
function adapterError(dialect, message) {
|
|
1128
|
+
if (dialect === "postgresql") return {
|
|
1129
|
+
kind: "postgres",
|
|
1130
|
+
code: "XX000",
|
|
1131
|
+
severity: "ERROR",
|
|
1132
|
+
message,
|
|
1133
|
+
detail: void 0,
|
|
1134
|
+
column: void 0,
|
|
1135
|
+
hint: void 0
|
|
1136
|
+
};
|
|
1137
|
+
if (dialect === "mysql") return {
|
|
1138
|
+
kind: "mysql",
|
|
1139
|
+
code: 1105,
|
|
1140
|
+
message,
|
|
1141
|
+
state: "HY000"
|
|
1142
|
+
};
|
|
1143
|
+
return {
|
|
1144
|
+
kind: "sqlite",
|
|
1145
|
+
extendedCode: 1,
|
|
1146
|
+
message
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
/** The three column types the engine reads as a string, whatever the database keeps them as. */
|
|
1150
|
+
const INSTANTS = /* @__PURE__ */ new Set([
|
|
1151
|
+
COLUMN_TYPE.datetime,
|
|
1152
|
+
COLUMN_TYPE.date,
|
|
1153
|
+
COLUMN_TYPE.time
|
|
1154
|
+
]);
|
|
1155
|
+
/** What the engine sends to hold a SQLite file for itself: `PRAGMA main.locking_mode=EXCLUSIVE`. */
|
|
1156
|
+
const EXCLUSIVE_LOCK = /^\s*PRAGMA\s+(?:\w+\.)?locking_mode\s*=\s*EXCLUSIVE\s*;?\s*$/iu;
|
|
1157
|
+
/** Runs a driver operation for the engine, its failure handed back as an error the engine reads. */
|
|
1158
|
+
function runForEngine(dialect, operation) {
|
|
1159
|
+
return Effect.runPromise(operation.pipe(Effect.match({
|
|
1160
|
+
onFailure: (error) => engineFailure(adapterError(dialect, error.cause)),
|
|
1161
|
+
onSuccess: (value) => engineSuccess(value)
|
|
1162
|
+
})));
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* The open connection the engine sends its statements through. Only `queryRaw`, `executeRaw` and
|
|
1166
|
+
* `executeScript` are ever reached for: the schema engine reads catalogues and runs DDL, and does
|
|
1167
|
+
* none of the value conversion the query engine needs a full adapter for.
|
|
1168
|
+
*/
|
|
1169
|
+
function connection(driver, dispose = () => Promise.resolve(engineSuccess(void 0))) {
|
|
1170
|
+
return {
|
|
1171
|
+
provider: driver.dialect === "postgresql" ? "postgres" : driver.dialect,
|
|
1172
|
+
adapterName: "hekireki",
|
|
1173
|
+
queryRaw: (query) => runForEngine(driver.dialect, driver.queryRaw({
|
|
1174
|
+
sql: query.sql,
|
|
1175
|
+
params: query.args
|
|
1176
|
+
}).pipe(Effect.map((rows) => {
|
|
1177
|
+
const columnTypes = rows.columns.map((column, index) => {
|
|
1178
|
+
const declared = columnTypeOfNative(driver.dialect, column.nativeType);
|
|
1179
|
+
if (declared !== null) return declared;
|
|
1180
|
+
return columnTypeOfValue(rows.rows.find((candidate) => candidate[index] !== null)?.[index] ?? null);
|
|
1181
|
+
});
|
|
1182
|
+
return {
|
|
1183
|
+
columnNames: rows.columns.map((column) => column.name),
|
|
1184
|
+
columnTypes,
|
|
1185
|
+
rows: rows.rows.map((row) => row.map((value, index) => {
|
|
1186
|
+
const plain = typeof value === "bigint" ? Number(value) : value;
|
|
1187
|
+
return INSTANTS.has(columnTypes[index] ?? COLUMN_TYPE.text) && typeof plain === "number" ? new Date(plain).toISOString() : plain;
|
|
1188
|
+
}))
|
|
1189
|
+
};
|
|
1190
|
+
}))),
|
|
1191
|
+
executeRaw: (query) => driver.dialect === "sqlite" && EXCLUSIVE_LOCK.test(query.sql) ? Promise.resolve(engineSuccess(0)) : query.args.length === 0 && splitStatements(query.sql).filter((statement) => statement.trim() !== "").length > 1 ? runForEngine(driver.dialect, driver.executeScript(query.sql).pipe(Effect.as(0))) : runForEngine(driver.dialect, driver.executeRaw({
|
|
1192
|
+
sql: query.sql,
|
|
1193
|
+
params: query.args
|
|
1194
|
+
})),
|
|
1195
|
+
executeScript: (script) => runForEngine(driver.dialect, driver.executeScript(script)),
|
|
1196
|
+
dispose
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* The database Studio already has open, as the Prisma schema engine takes it. Studio ships no
|
|
1201
|
+
* driver adapter of its own and reaches for none in the project: the connection the rest of
|
|
1202
|
+
* Studio reads and writes through is the one the engine migrates. `dispose` does nothing, because
|
|
1203
|
+
* the connection outlives any one command and is closed with Studio itself.
|
|
1204
|
+
*
|
|
1205
|
+
* @param driver - the open connection every statement of the engine goes through
|
|
1206
|
+
* @returns the adapter factory `openSchemaEngine` is given
|
|
1207
|
+
*/
|
|
1208
|
+
function makeSchemaEngineAdapter(driver, openShadow) {
|
|
1209
|
+
const opened = connection(driver);
|
|
1210
|
+
return {
|
|
1211
|
+
provider: opened.provider,
|
|
1212
|
+
adapterName: opened.adapterName,
|
|
1213
|
+
connect: () => Promise.resolve(engineSuccess(opened)),
|
|
1214
|
+
...openShadow === void 0 ? {} : { connectToShadowDb: () => runForEngine(driver.dialect, openShadow().pipe(Effect.mapError((error) => ({ cause: error.reason })), Effect.map((shadow) => connection(shadow, () => Effect.runPromise(shadow.close.pipe(Effect.as(engineSuccess(void 0)))))))) }
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
/**
|
|
1218
|
+
* An adapter with no database behind it, for the commands that read only the schema: the
|
|
1219
|
+
* migration from an empty database to it. The engine still connects as it starts, and asks
|
|
1220
|
+
* PostgreSQL for its version and to make `public`; every statement is answered with nothing,
|
|
1221
|
+
* which is what an empty database has to say.
|
|
1222
|
+
*
|
|
1223
|
+
* @param dialect - the SQL the engine writes: PostgreSQL's or SQLite's (the wasm engine has no
|
|
1224
|
+
* MySQL connector)
|
|
1225
|
+
* @returns the adapter factory `openSchemaEngine` is given
|
|
1226
|
+
*/
|
|
1227
|
+
function makeOfflineSchemaEngineAdapter(dialect) {
|
|
1228
|
+
const provider = dialect === "postgresql" ? "postgres" : dialect;
|
|
1229
|
+
const empty = {
|
|
1230
|
+
columnNames: [],
|
|
1231
|
+
columnTypes: [],
|
|
1232
|
+
rows: []
|
|
1233
|
+
};
|
|
1234
|
+
return {
|
|
1235
|
+
provider,
|
|
1236
|
+
adapterName: "hekireki",
|
|
1237
|
+
connect: () => Promise.resolve(engineSuccess({
|
|
1238
|
+
provider,
|
|
1239
|
+
adapterName: "hekireki",
|
|
1240
|
+
queryRaw: () => Promise.resolve(engineSuccess(empty)),
|
|
1241
|
+
executeRaw: () => Promise.resolve(engineSuccess(0)),
|
|
1242
|
+
executeScript: () => Promise.resolve(engineSuccess(void 0)),
|
|
1243
|
+
dispose: () => Promise.resolve(engineSuccess(void 0))
|
|
1244
|
+
}))
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
// src/migrate/adapter/engine.ts
|
|
1248
|
+
const WasmStart = z.custom((value) => typeof value === "function").meta({ description: "The start hook wasm-bindgen puts on the instantiated module." });
|
|
1249
|
+
/**
|
|
1250
|
+
* Where a panic in the engine writes its message before the WebAssembly trap unwinds. Without
|
|
1251
|
+
* this global the trap surfaces as `Cannot read properties of undefined (reading 'set_message')`,
|
|
1252
|
+
* which says nothing about what went wrong.
|
|
1253
|
+
*/
|
|
1254
|
+
const panics = { message: null };
|
|
1255
|
+
/**
|
|
1256
|
+
* What a failed command is reported as: the panic the engine wrote, else the thrown error. The
|
|
1257
|
+
* panic is taken as it is read, so a later failure cannot report a stale one.
|
|
1258
|
+
*/
|
|
1259
|
+
function engineError(error) {
|
|
1260
|
+
const { message } = panics;
|
|
1261
|
+
panics.message = null;
|
|
1262
|
+
return new MigrateEngineError({ message: message ?? (error instanceof Error ? error.message : String(error)) });
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* The bindings, instantiated once. `schema_engine_bg.js` holds the instance in a module-level
|
|
1266
|
+
* cell that `__wbg_set_wasm` writes, so a second instantiation would pull the memory out from
|
|
1267
|
+
* under the first engine.
|
|
1268
|
+
*/
|
|
1269
|
+
const loaded = { bindings: null };
|
|
1270
|
+
const lock = Semaphore.makeUnsafe(1);
|
|
1271
|
+
function instantiate() {
|
|
1272
|
+
return Effect.gen(function* () {
|
|
1273
|
+
const entry = yield* Effect.try({
|
|
1274
|
+
try: () => createRequire(import.meta.url).resolve("@prisma/schema-engine-wasm/schema_engine_bg"),
|
|
1275
|
+
catch: engineError
|
|
1276
|
+
});
|
|
1277
|
+
const bindings = yield* Effect.tryPromise({
|
|
1278
|
+
try: () => import(pathToFileURL(entry).href),
|
|
1279
|
+
catch: engineError
|
|
1280
|
+
});
|
|
1281
|
+
const bytes = yield* readBytes(path.join(path.dirname(entry), "schema_engine_bg.wasm")).pipe(Effect.mapError(engineError));
|
|
1282
|
+
return yield* Effect.try({
|
|
1283
|
+
try: () => {
|
|
1284
|
+
const instance = new WebAssembly.Instance(new WebAssembly.Module(Uint8Array.from(bytes)), { "./schema_engine_bg.js": bindings });
|
|
1285
|
+
const result = WasmStart.safeParse(instance.exports.__wbindgen_start);
|
|
1286
|
+
if (!result.success) throw new TypeError("The engine module exports no __wbindgen_start.");
|
|
1287
|
+
bindings.__wbg_set_wasm(instance.exports);
|
|
1288
|
+
result.data();
|
|
1289
|
+
return bindings;
|
|
1290
|
+
},
|
|
1291
|
+
catch: engineError
|
|
1292
|
+
});
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
/** The bindings of the engine, loaded the first time they are asked for. */
|
|
1296
|
+
function schemaEngineBindings() {
|
|
1297
|
+
return Effect.gen(function* () {
|
|
1298
|
+
Reflect.set(globalThis, "PRISMA_WASM_PANIC_REGISTRY", { set_message: (message) => {
|
|
1299
|
+
panics.message = message;
|
|
1300
|
+
} });
|
|
1301
|
+
if (loaded.bindings !== null) return loaded.bindings;
|
|
1302
|
+
const bindings = yield* instantiate();
|
|
1303
|
+
loaded.bindings = bindings;
|
|
1304
|
+
return bindings;
|
|
1305
|
+
}).pipe(Semaphore.withPermit(lock));
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* An engine connected through `adapter`, reading `files` as its datamodel. The engine panics on
|
|
1309
|
+
* an empty datamodel (`psl::validate_multi_file() must be called with at least one file`), so
|
|
1310
|
+
* only a schema that parsed is ever handed to it.
|
|
1311
|
+
*
|
|
1312
|
+
* @param input - the schema files the commands are read against, the adapter every statement
|
|
1313
|
+
* goes through, and where the engine's log lines go
|
|
1314
|
+
*/
|
|
1315
|
+
function openSchemaEngine(input) {
|
|
1316
|
+
return Effect.gen(function* () {
|
|
1317
|
+
if (input.files.length === 0) return yield* new MigrateEngineError({ message: "The schema engine needs at least one schema file." });
|
|
1318
|
+
const bindings = yield* schemaEngineBindings();
|
|
1319
|
+
return yield* Effect.tryPromise({
|
|
1320
|
+
try: () => bindings.SchemaEngine.new({ datamodels: input.files.map((file) => [file.path, file.content]) }, input.onLog ?? ((line) => line), input.adapter),
|
|
1321
|
+
catch: engineError
|
|
1322
|
+
});
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
/** Sends one command to the engine, a panic reported as the message the engine wrote. */
|
|
1326
|
+
function engineCommand(run) {
|
|
1327
|
+
return Effect.tryPromise({
|
|
1328
|
+
try: run,
|
|
1329
|
+
catch: engineError
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
// src/migrate/adapter/native-engine.ts
|
|
1333
|
+
const RpcMessage = z.object({
|
|
1334
|
+
id: z.number().optional().meta({
|
|
1335
|
+
description: "The request it answers, or its own.",
|
|
1336
|
+
example: 1
|
|
1337
|
+
}),
|
|
1338
|
+
method: z.string().optional().meta({
|
|
1339
|
+
description: "A request of the engine to its caller.",
|
|
1340
|
+
example: "print"
|
|
1341
|
+
}),
|
|
1342
|
+
params: z.object({ content: z.string().optional().meta({
|
|
1343
|
+
description: "What to print.",
|
|
1344
|
+
example: "-- AlterTable"
|
|
1345
|
+
}) }).optional().meta({ description: "The parameters of a request of the engine." }),
|
|
1346
|
+
result: z.unknown().optional().meta({ description: "What the command returned." }),
|
|
1347
|
+
error: z.object({
|
|
1348
|
+
message: z.string().meta({
|
|
1349
|
+
description: "The JSON-RPC message.",
|
|
1350
|
+
example: "An error happened."
|
|
1351
|
+
}),
|
|
1352
|
+
data: z.object({ message: z.string().optional().meta({
|
|
1353
|
+
description: "The engine's own words for it.",
|
|
1354
|
+
example: "P3005"
|
|
1355
|
+
}) }).optional().meta({ description: "What the engine adds to it." })
|
|
1356
|
+
}).optional().meta({ description: "Why the command failed." })
|
|
1357
|
+
}).meta({ description: "One line the schema engine writes on its stdout" });
|
|
1358
|
+
const DiffResult = z.custom((value) => typeof value === "object" && value !== null && "exitCode" in value).meta({ description: "What `diff` returns: its exit code, and the script when it was not printed." });
|
|
1359
|
+
const DiagnoseResult = z.custom((value) => typeof value === "object" && value !== null && "failedMigrationNames" in value).meta({ description: "What `diagnoseMigrationHistory` returns." });
|
|
1360
|
+
const ApplyResult = z.custom((value) => typeof value === "object" && value !== null && "appliedMigrationNames" in value).meta({ description: "What `applyMigrations` returns." });
|
|
1361
|
+
const MarkedResult = z.custom((value) => typeof value === "object" && value !== null).meta({ description: "What `markMigrationApplied` and `markMigrationRolledBack` return." });
|
|
1362
|
+
/**
|
|
1363
|
+
* Where the native schema engine is: `PRISMA_SCHEMA_ENGINE_BINARY` when it is set, as the Prisma
|
|
1364
|
+
* CLI reads it, else the `schema-engine-<platform>` `@prisma/engines` downloaded as it installed.
|
|
1365
|
+
*
|
|
1366
|
+
* @param cwd - what a relative `PRISMA_SCHEMA_ENGINE_BINARY` is resolved from
|
|
1367
|
+
* @returns the binary, or null when there is none to run
|
|
1368
|
+
*/
|
|
1369
|
+
function findSchemaEngineBinary(cwd) {
|
|
1370
|
+
return Effect.gen(function* () {
|
|
1371
|
+
const configured = yield* environmentVariable("PRISMA_SCHEMA_ENGINE_BINARY");
|
|
1372
|
+
if (configured !== null) {
|
|
1373
|
+
const file = path.resolve(cwd, configured);
|
|
1374
|
+
return (yield* exists(file).pipe(Effect.orElseSucceed(() => false))) ? file : null;
|
|
1375
|
+
}
|
|
1376
|
+
const directory = yield* Effect.try({
|
|
1377
|
+
try: () => getEnginesPath(),
|
|
1378
|
+
catch: () => null
|
|
1379
|
+
}).pipe(Effect.orElseSucceed(() => null));
|
|
1380
|
+
if (directory === null) return null;
|
|
1381
|
+
const found = (yield* readDirectory(directory).pipe(Effect.orElseSucceed(() => []))).find((name) => /^schema-engine-[\w.-]+$/u.test(name) && !name.endsWith(".gz"));
|
|
1382
|
+
return found === void 0 ? null : path.join(directory, found);
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* One command of the native engine: the binary started on the schema and the URL, the request
|
|
1387
|
+
* written, every `print` it asks for answered (a script it writes comes that way, not in the
|
|
1388
|
+
* result), and the binary let go once it has answered. A process per command: the datamodel is
|
|
1389
|
+
* fixed when the engine starts, and nothing is left running between requests.
|
|
1390
|
+
*/
|
|
1391
|
+
async function command(input, method, params) {
|
|
1392
|
+
const child = spawn(input.binary, [
|
|
1393
|
+
...input.files.flatMap((file) => ["--datamodels", file.path]),
|
|
1394
|
+
"--datasource",
|
|
1395
|
+
JSON.stringify({ url: input.url })
|
|
1396
|
+
], {
|
|
1397
|
+
cwd: input.cwd,
|
|
1398
|
+
stdio: [
|
|
1399
|
+
"pipe",
|
|
1400
|
+
"pipe",
|
|
1401
|
+
"pipe"
|
|
1402
|
+
],
|
|
1403
|
+
env: {
|
|
1404
|
+
...process.env,
|
|
1405
|
+
RUST_BACKTRACE: "1"
|
|
1406
|
+
}
|
|
1407
|
+
});
|
|
1408
|
+
const lines = createInterface({
|
|
1409
|
+
input: child.stdout,
|
|
1410
|
+
crlfDelay: Infinity
|
|
1411
|
+
});
|
|
1412
|
+
lines.on("line", (line) => {
|
|
1413
|
+
const message = RpcMessage.safeParse(JSON.parse(line));
|
|
1414
|
+
if (!message.success) return;
|
|
1415
|
+
if (message.data.method === "print") child.stdin.write(`${JSON.stringify({
|
|
1416
|
+
jsonrpc: "2.0",
|
|
1417
|
+
id: message.data.id,
|
|
1418
|
+
result: {}
|
|
1419
|
+
})}\n`);
|
|
1420
|
+
else if (message.data.id === 1) child.stdin.end();
|
|
1421
|
+
});
|
|
1422
|
+
const logs = text(child.stderr);
|
|
1423
|
+
child.stdin.write(`${JSON.stringify({
|
|
1424
|
+
jsonrpc: "2.0",
|
|
1425
|
+
id: 1,
|
|
1426
|
+
method,
|
|
1427
|
+
params
|
|
1428
|
+
})}\n`);
|
|
1429
|
+
const messages = (await Effect.runPromise(Stream.runCollect(Stream.fromAsyncIterable(lines, (error) => error)))).flatMap((line) => {
|
|
1430
|
+
const message = RpcMessage.safeParse(JSON.parse(line));
|
|
1431
|
+
return message.success ? [message.data] : [];
|
|
1432
|
+
});
|
|
1433
|
+
const answer = messages.find((message) => message.id === 1 && message.method === void 0);
|
|
1434
|
+
if (answer === void 0) {
|
|
1435
|
+
const written = await logs;
|
|
1436
|
+
throw new Error(`The schema engine stopped without answering ${method}: ${written}`);
|
|
1437
|
+
}
|
|
1438
|
+
if (answer.error !== void 0) throw new Error(answer.error.data?.message ?? answer.error.message);
|
|
1439
|
+
const printed = messages.flatMap((message) => message.method === "print" && message.params?.content !== void 0 ? [message.params.content] : []);
|
|
1440
|
+
return {
|
|
1441
|
+
result: answer.result,
|
|
1442
|
+
printed
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
/**
|
|
1446
|
+
* The native engine on the schema and the database's URL, answering the commands Studio sends
|
|
1447
|
+
* with the shapes the wasm engine answers them with.
|
|
1448
|
+
*
|
|
1449
|
+
* @param input - the binary, the schema files (read from where they are), the URL and the directory
|
|
1450
|
+
* the engine runs in
|
|
1451
|
+
* @returns the engine
|
|
1452
|
+
*/
|
|
1453
|
+
function openNativeSchemaEngine(input) {
|
|
1454
|
+
return {
|
|
1455
|
+
diff: async (params) => {
|
|
1456
|
+
const { result, printed } = await command(input, "diff", params);
|
|
1457
|
+
const read = DiffResult.parse(result);
|
|
1458
|
+
return {
|
|
1459
|
+
...read,
|
|
1460
|
+
stdout: printed.length === 0 ? read.stdout ?? null : `${printed.join("\n")}\n`
|
|
1461
|
+
};
|
|
1462
|
+
},
|
|
1463
|
+
diagnoseMigrationHistory: async (params) => {
|
|
1464
|
+
const { result } = await command(input, "diagnoseMigrationHistory", params);
|
|
1465
|
+
return DiagnoseResult.parse(result);
|
|
1466
|
+
},
|
|
1467
|
+
applyMigrations: async (params) => {
|
|
1468
|
+
const { result } = await command(input, "applyMigrations", params);
|
|
1469
|
+
return ApplyResult.parse(result);
|
|
1470
|
+
},
|
|
1471
|
+
markMigrationApplied: async (params) => {
|
|
1472
|
+
const { result } = await command(input, "markMigrationApplied", params);
|
|
1473
|
+
return MarkedResult.parse(result);
|
|
1474
|
+
},
|
|
1475
|
+
markMigrationRolledBack: async (params) => {
|
|
1476
|
+
const { result } = await command(input, "markMigrationRolledBack", params);
|
|
1477
|
+
return MarkedResult.parse(result);
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
export { makeOfflineSchemaEngineAdapter as a, makeSchema as c, erRelations as d, inferredERRelations as f, openSchemaEngine as i, annotatedERRelations as l, openNativeSchemaEngine as n, makeSchemaEngineAdapter as o, engineCommand as r, makeAnalysisSchema as s, findSchemaEngineBinary as t, erKey as u };
|