hekireki 0.52.0 → 0.52.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- 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 +5 -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-openapi-hono.js +1 -1
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-BcqPhgiX.js → bin-i7iQQ-V-.js} +3295 -2428
- package/dist/case-D3JCqTLI.js +54 -0
- package/dist/{discover-BKlX-LLS.js → discover-CLLycWcR.js} +3 -3
- package/dist/{emit-BSQAIFiF.js → emit-DsCT5gLu.js} +5 -2
- package/dist/{errors-fAN1Og-7.js → errors-CRIxtr-P.js} +88 -26
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{migrate-BS6d_8aA.js → migrate-1xVrRUlb.js} +77 -21
- package/dist/{native-engine-DcZUEqO8.js → native-engine-DeQEnJxi.js} +145 -30
- package/dist/{plan-BMypogKp.js → plan-8rsBBJcs.js} +1294 -768
- package/dist/{run-BYq7BEVd.js → run-DbZYkHVI.js} +235 -128
- package/dist/{schema-B7beUJic.js → schema-CyJTUCF1.js} +54 -182
- package/dist/{sql-BwL2BncN.js → sql-LMMCiAlf.js} +48 -19
- package/dist/{start-s1j4PqUM.js → start-Ba8wQAD1.js} +1304 -929
- package/dist/studio/assets/client-8R97eV42.js +2 -0
- package/dist/studio/assets/{confirm-dialog-CKCkchiq.js → confirm-dialog-BfMzwGyk.js} +1 -1
- package/dist/studio/assets/docs-C7FtC4KG.js +1 -0
- package/dist/studio/assets/enums._name-DLAiEdMc.js +1 -0
- package/dist/studio/assets/{field-icon-C1wSRFKO.js → field-icon-LVK7vIIn.js} +1 -1
- package/dist/studio/assets/index-T46k2NyA.js +15 -0
- package/dist/studio/assets/{labels-B5gZ2suK.js → labels-Bn-KWaMa.js} +2 -2
- package/dist/studio/assets/{marked-text-B27DfhKS.js → marked-text-BdU5_qSK.js} +1 -1
- package/dist/studio/assets/models._name-BKzAVcW3.js +1 -0
- package/dist/studio/assets/{monaco-DRYJTcJl.js → monaco-33yj-p0X.js} +1 -1
- package/dist/studio/assets/prisma-DqpMbUwJ.js +2 -0
- package/dist/studio/assets/result-table-PN64JbsN.js +1 -0
- package/dist/studio/assets/{routes-Bl7HRpBJ.js → routes-C1Aze5QM.js} +1 -1
- package/dist/studio/assets/{schema-view-BEdx0cC2.js → schema-view-Bq2_9B5a.js} +4 -4
- package/dist/studio/assets/sql-FZV6GAdV.js +6 -0
- package/dist/studio/assets/{tabs-BpZ0hh1V.js → tabs-GBri63Xo.js} +1 -1
- package/dist/studio/index.html +2 -2
- package/package.json +12 -5
- package/dist/studio/assets/client-C-v3Paav.js +0 -2
- package/dist/studio/assets/docs-CXORFY0Y.js +0 -1
- package/dist/studio/assets/enums._name-BUBU_WMt.js +0 -1
- package/dist/studio/assets/index-DzCcMC-d.js +0 -15
- package/dist/studio/assets/models._name-CQFgPD0T.js +0 -1
- package/dist/studio/assets/prisma-1nDx08Wb.js +0 -2
- package/dist/studio/assets/result-table-0P18Nywh.js +0 -1
- package/dist/studio/assets/sql-GBZZtEKI.js +0 -6
|
@@ -32,120 +32,7 @@ function fmtMarkdown(input) {
|
|
|
32
32
|
return code;
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
|
-
// src/
|
|
36
|
-
function parseRelation(line) {
|
|
37
|
-
const match = line.trim().match(/^@relation\s+(\w+)\.(\w+)\s+(\w+)\.(\w+)\s+(\w+-to-\w+)$/u);
|
|
38
|
-
if (!match) return null;
|
|
39
|
-
const [, fromModel = "", fromField = "", toModel = "", toField = "", type = ""] = match;
|
|
40
|
-
return {
|
|
41
|
-
fromModel,
|
|
42
|
-
fromField,
|
|
43
|
-
toModel,
|
|
44
|
-
toField,
|
|
45
|
-
type
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
function getString(v) {
|
|
49
|
-
return typeof v === "string" ? v : Array.isArray(v) ? v[0] : void 0;
|
|
50
|
-
}
|
|
51
|
-
function getStrings(v) {
|
|
52
|
-
return typeof v === "string" ? [v] : Array.isArray(v) ? v : void 0;
|
|
53
|
-
}
|
|
54
|
-
function getBool(v, fallback = false) {
|
|
55
|
-
return v === true || v === "true" || Array.isArray(v) && v[0] === "true" ? true : fallback;
|
|
56
|
-
}
|
|
57
|
-
function makeSnakeCase(name) {
|
|
58
|
-
return name.replaceAll(/([a-z0-9])([A-Z])/gu, "$1_$2").toLowerCase();
|
|
59
|
-
}
|
|
60
|
-
function makePascalCase(name) {
|
|
61
|
-
return name.split("_").filter((part) => part !== "").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
62
|
-
}
|
|
63
|
-
function makeValidationExtractor(annotationPrefix) {
|
|
64
|
-
const escaped = annotationPrefix.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
65
|
-
const regex = new RegExp(`${escaped}(.+?)(?:\\n|$)`, "u");
|
|
66
|
-
return function extractValidation(documentation) {
|
|
67
|
-
if (!documentation) return null;
|
|
68
|
-
return documentation.match(regex)?.[1]?.trim() ?? null;
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
const ANNOTATION_PREFIXES = [
|
|
72
|
-
"@z.",
|
|
73
|
-
"@v.",
|
|
74
|
-
"@a.",
|
|
75
|
-
"@e.",
|
|
76
|
-
"@t.",
|
|
77
|
-
"@j.",
|
|
78
|
-
"@p.",
|
|
79
|
-
"@ar.",
|
|
80
|
-
"@ecto.",
|
|
81
|
-
"@api.",
|
|
82
|
-
"@relation"
|
|
83
|
-
];
|
|
84
|
-
const ANNOTATION_EXACT = /* @__PURE__ */ new Set([
|
|
85
|
-
"@z",
|
|
86
|
-
"@v",
|
|
87
|
-
"@a",
|
|
88
|
-
"@e",
|
|
89
|
-
"@t",
|
|
90
|
-
"@j",
|
|
91
|
-
"@p",
|
|
92
|
-
"@ar",
|
|
93
|
-
"@ecto"
|
|
94
|
-
]);
|
|
95
|
-
function isAnnotationLine(line) {
|
|
96
|
-
const trimmed = line.trim();
|
|
97
|
-
return ANNOTATION_PREFIXES.some((p) => trimmed.startsWith(p)) || ANNOTATION_EXACT.has(trimmed);
|
|
98
|
-
}
|
|
99
|
-
function stripAnnotations(doc) {
|
|
100
|
-
const result = documentationLines(doc).join("\n").trim();
|
|
101
|
-
return result.length > 0 ? result : void 0;
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* The prose of a `///` comment as a JSDoc comment (also KDoc and PHPDoc) at `indent`: no lines
|
|
105
|
-
* when there is none, one line `/** … *\/` for one line of prose, and a block for more. A `*\/` in
|
|
106
|
-
* the text cannot close the comment early.
|
|
107
|
-
*
|
|
108
|
-
* @param text - the prose, as {@link stripAnnotations} returns it
|
|
109
|
-
* @param indent - the indentation of the commented line
|
|
110
|
-
* @returns the lines of the block
|
|
111
|
-
*/
|
|
112
|
-
function docBlockLines(text, indent) {
|
|
113
|
-
if (text === void 0) return [];
|
|
114
|
-
const lines = text.replaceAll("*/", "*\\/").split("\n");
|
|
115
|
-
if (lines.length === 1) return [`${indent}/** ${lines[0]} */`];
|
|
116
|
-
const body = lines.map((line) => line === "" ? `${indent} *` : `${indent} * ${line}`);
|
|
117
|
-
return [
|
|
118
|
-
`${indent}/**`,
|
|
119
|
-
...body,
|
|
120
|
-
`${indent} */`
|
|
121
|
-
];
|
|
122
|
-
}
|
|
123
|
-
/** The lines of a doc comment that are prose: annotation lines are dropped. */
|
|
124
|
-
function documentationLines(doc) {
|
|
125
|
-
return (doc ?? "").split("\n").map((line) => line.trim()).filter((line) => !isAnnotationLine(line));
|
|
126
|
-
}
|
|
127
|
-
function isLoopbackHostname(hostname) {
|
|
128
|
-
const bare = hostname.replace(/^\[(.*)\]$/u, "$1").toLowerCase();
|
|
129
|
-
return bare === "localhost" || bare.endsWith(".localhost") || bare === "127.0.0.1" || bare === "::1";
|
|
130
|
-
}
|
|
131
|
-
function extractObjectType(documentation, prefix) {
|
|
132
|
-
if (!documentation) return void 0;
|
|
133
|
-
const prefixWithoutAt = prefix.slice(1);
|
|
134
|
-
const match = documentation.split("\n").map((l) => l.trim()).find((line) => line.includes(`${prefixWithoutAt}strictObject`) || line.includes(`${prefixWithoutAt}looseObject`));
|
|
135
|
-
if (!match) return void 0;
|
|
136
|
-
if (match.includes("strictObject")) return "strict";
|
|
137
|
-
return "loose";
|
|
138
|
-
}
|
|
139
|
-
function groupByModel(validFields) {
|
|
140
|
-
const raw = Object.groupBy(validFields, (f) => f.modelName);
|
|
141
|
-
return Object.fromEntries(Object.entries(raw).filter((entry) => entry[1] !== void 0));
|
|
142
|
-
}
|
|
143
|
-
function isFields(modelFields) {
|
|
144
|
-
return modelFields.flat().filter((field) => field.validation !== null);
|
|
145
|
-
}
|
|
146
|
-
function schemaFromFields(modelFields, schemaBuilder, propertiesGenerator, objectType) {
|
|
147
|
-
return schemaBuilder(modelFields[0]?.modelName ?? "", propertiesGenerator(modelFields), objectType);
|
|
148
|
-
}
|
|
35
|
+
// src/list/index.ts
|
|
149
36
|
/** The items in runs of at most `size`, in order: a batch of rows per statement. */
|
|
150
37
|
function chunks(items, size) {
|
|
151
38
|
return Array.from({ length: Math.ceil(items.length / size) }, (_, index) => items.slice(index * size, (index + 1) * size));
|
|
@@ -154,45 +41,7 @@ function chunks(items, size) {
|
|
|
154
41
|
function isSameList(a, b) {
|
|
155
42
|
return a.length === b.length && a.every((value, i) => value === b[i]);
|
|
156
43
|
}
|
|
157
|
-
|
|
158
|
-
function lowerFirst(text) {
|
|
159
|
-
return text.charAt(0).toLowerCase() + text.slice(1);
|
|
160
|
-
}
|
|
161
|
-
/**
|
|
162
|
-
* The name Prisma Migrate gives a key, index or constraint the schema does not name: the table,
|
|
163
|
-
* the columns and a suffix, the first two cut to the database's longest identifier (63 on
|
|
164
|
-
* PostgreSQL, 64 on MySQL).
|
|
165
|
-
*
|
|
166
|
-
* @example
|
|
167
|
-
* ```sql
|
|
168
|
-
* -- @@unique([s, i]) on Scalar; a foreign key on refs.comp_a, comp_b
|
|
169
|
-
* CREATE UNIQUE INDEX "Scalar_s_i_key" ON "Scalar"("s", "i");
|
|
170
|
-
* CONSTRAINT "refs_comp_a_comp_b_fkey" FOREIGN KEY ("comp_a", "comp_b") ...
|
|
171
|
-
* ```
|
|
172
|
-
*/
|
|
173
|
-
function constraintName(table, columns, suffix, provider) {
|
|
174
|
-
const limit = provider === "sqlite" ? Infinity : provider === "mysql" ? 64 : 63;
|
|
175
|
-
return `${[table, ...columns].join("_").slice(0, limit - suffix.length - 1)}_${suffix}`;
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* The part of a column an index takes: MySQL's `@@index([identifier(length: 191)])` on a TEXT. A
|
|
179
|
-
* length the column does not reach is the whole of it, and MySQL keeps none: a String is
|
|
180
|
-
* `varchar(191)` unless its native type says otherwise.
|
|
181
|
-
*
|
|
182
|
-
* @example
|
|
183
|
-
* ```sql
|
|
184
|
-
* -- identifier String @db.Text, @@index([identifier(length: 191)])
|
|
185
|
-
* CREATE INDEX `verification_identifier_idx` ON `verification`(`identifier`(191));
|
|
186
|
-
* -- userId String, @@index([userId(length: 191)])
|
|
187
|
-
* CREATE INDEX `account_userId_idx` ON `account`(`userId`);
|
|
188
|
-
* ```
|
|
189
|
-
*/
|
|
190
|
-
function indexPrefix(model, field) {
|
|
191
|
-
const native = model.fields.find((f) => f.name === field.name)?.nativeType;
|
|
192
|
-
const size = !native ? 191 : native[0] === "VarChar" || native[0] === "Char" ? Number(native[1][0] ?? 1) : Infinity;
|
|
193
|
-
return field.length === void 0 || field.length >= size ? void 0 : field.length;
|
|
194
|
-
}
|
|
195
|
-
// src/utils/prisma-model.ts
|
|
44
|
+
// src/prisma/model.ts
|
|
196
45
|
function tableName(model) {
|
|
197
46
|
return model.dbName ?? model.name;
|
|
198
47
|
}
|
|
@@ -217,7 +66,8 @@ function primaryKeyFields(model) {
|
|
|
217
66
|
const id = model.fields.find((f) => f.isId);
|
|
218
67
|
if (id) return [id.name];
|
|
219
68
|
if (model.primaryKey) return [...model.primaryKey.fields];
|
|
220
|
-
|
|
69
|
+
const required = new Set(model.fields.filter((f) => f.isRequired).map((f) => f.name));
|
|
70
|
+
return [...model.fields.filter((f) => f.isUnique).map((f) => [f.name]), ...model.uniqueFields.map((fields) => [...fields])].find((fields) => fields.every((name) => required.has(name))) ?? [];
|
|
221
71
|
}
|
|
222
72
|
/** The length a native type's first argument gives (`@db.VarChar(255)`), or null. */
|
|
223
73
|
function lengthArg(args) {
|
|
@@ -254,6 +104,15 @@ function uuidDefaultVersion(field) {
|
|
|
254
104
|
function isUlidDefault(field) {
|
|
255
105
|
return isFunctionDefault(field.default) && field.default.name === "ulid";
|
|
256
106
|
}
|
|
107
|
+
function cuidDefaultVersion(field) {
|
|
108
|
+
if (!(isFunctionDefault(field.default) && field.default.name === "cuid")) return null;
|
|
109
|
+
return field.default.args[0] === 2 ? 2 : 1;
|
|
110
|
+
}
|
|
111
|
+
function nanoidDefault(field) {
|
|
112
|
+
if (!(isFunctionDefault(field.default) && field.default.name === "nanoid")) return null;
|
|
113
|
+
const [length] = field.default.args;
|
|
114
|
+
return { length: typeof length === "number" ? length : null };
|
|
115
|
+
}
|
|
257
116
|
function backRelation(field, owner, models) {
|
|
258
117
|
const related = models.find((m) => m.name === field.type);
|
|
259
118
|
return related?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && f.type === owner.name && !(related.name === owner.name && f.name === field.name));
|
|
@@ -305,10 +164,11 @@ function implicitJoinTables(models) {
|
|
|
305
164
|
});
|
|
306
165
|
}
|
|
307
166
|
function manyToManyRelations(models) {
|
|
167
|
+
const byName = new Map(models.map((m) => [m.name, m]));
|
|
308
168
|
return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
|
|
309
169
|
const inverse = backRelation(field, model, models);
|
|
310
|
-
const other =
|
|
311
|
-
if (
|
|
170
|
+
const other = byName.get(field.type);
|
|
171
|
+
if (other === void 0 || inverse?.isList !== true) return [];
|
|
312
172
|
if (!isJoinSideA(field, model, inverse)) return [];
|
|
313
173
|
return [{
|
|
314
174
|
relationName: field.relationName ?? `${model.name}To${other.name}`,
|
|
@@ -350,14 +210,14 @@ function formatSql(text, dialect) {
|
|
|
350
210
|
*/
|
|
351
211
|
function makeDatasourceUrl(input) {
|
|
352
212
|
const block = /datasource\s*:\s*\{([^}]*)\}/u.exec(input.configText)?.[1];
|
|
353
|
-
if (
|
|
213
|
+
if (block === void 0) return null;
|
|
354
214
|
const env = /url\s*:\s*env\(\s*["'`]([^"'`]+)["'`]\s*\)/u.exec(block)?.[1] ?? /url\s*:\s*process\.env(?:\.([A-Za-z_$][\w$]*)|\[\s*["'`]([^"'`]+)["'`]\s*\])/u.exec(block)?.slice(1).find((name) => name !== void 0);
|
|
355
|
-
if (env) return {
|
|
215
|
+
if (env !== void 0) return {
|
|
356
216
|
kind: "env",
|
|
357
217
|
name: env
|
|
358
218
|
};
|
|
359
219
|
const literal = /url\s*:\s*["'`]([^"'`]+)["'`]/u.exec(block)?.[1];
|
|
360
|
-
return literal ? {
|
|
220
|
+
return literal !== void 0 ? {
|
|
361
221
|
kind: "literal",
|
|
362
222
|
value: literal
|
|
363
223
|
} : null;
|
|
@@ -365,14 +225,14 @@ function makeDatasourceUrl(input) {
|
|
|
365
225
|
/** The `url` of the schema's `datasource` block (Prisma 6 and earlier), as `env("NAME")` or a literal. */
|
|
366
226
|
function makeSchemaDatasourceUrl(input) {
|
|
367
227
|
const block = /datasource\s+\w+\s*\{([^}]*)\}/u.exec(input.schemaText)?.[1];
|
|
368
|
-
if (
|
|
228
|
+
if (block === void 0) return null;
|
|
369
229
|
const env = /^\s*url\s*=\s*env\(\s*"([^"]+)"\s*\)/mu.exec(block)?.[1];
|
|
370
|
-
if (env) return {
|
|
230
|
+
if (env !== void 0) return {
|
|
371
231
|
kind: "env",
|
|
372
232
|
name: env
|
|
373
233
|
};
|
|
374
234
|
const literal = /^\s*url\s*=\s*"([^"]+)"/mu.exec(block)?.[1];
|
|
375
|
-
return literal ? {
|
|
235
|
+
return literal !== void 0 ? {
|
|
376
236
|
kind: "literal",
|
|
377
237
|
value: literal
|
|
378
238
|
} : null;
|
|
@@ -388,40 +248,49 @@ function makeSchemaDatasourceUrl(input) {
|
|
|
388
248
|
*/
|
|
389
249
|
function makeDatabaseUrlChoice(input) {
|
|
390
250
|
const { datasource } = input;
|
|
391
|
-
const found = input
|
|
251
|
+
const found = firstUrl(input);
|
|
252
|
+
if (found !== null) return {
|
|
253
|
+
found,
|
|
254
|
+
reason: null
|
|
255
|
+
};
|
|
256
|
+
return {
|
|
257
|
+
found: null,
|
|
258
|
+
reason: datasource?.kind === "env" ? `${input.where} reads the database URL from env("${datasource.name}"), but ${datasource.name} is not set.\n Set it in .env or the environment, or pass --url <connection string>.` : "No database URL found.\n Set `url` in hekireki.config.ts, name the variable in prisma.config.ts (`datasource: { url: env(\"DATABASE_URL\") }`) and set it in .env or the environment, or pass --url <connection string>."
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/** The first URL there is, in the order `makeDatabaseUrlChoice` names. */
|
|
262
|
+
function firstUrl(input) {
|
|
263
|
+
if (input.explicit !== null) return {
|
|
392
264
|
url: input.explicit,
|
|
393
265
|
source: "flag"
|
|
394
|
-
}
|
|
266
|
+
};
|
|
267
|
+
if (input.configUrl !== null && input.configUrl !== "") return {
|
|
395
268
|
url: input.configUrl,
|
|
396
269
|
source: "hekireki"
|
|
397
|
-
}
|
|
398
|
-
|
|
270
|
+
};
|
|
271
|
+
if (input.datasource?.kind === "literal") return {
|
|
272
|
+
url: input.datasource.value,
|
|
399
273
|
source: "prisma"
|
|
400
|
-
}
|
|
274
|
+
};
|
|
275
|
+
if (input.named !== null) return {
|
|
401
276
|
url: input.named,
|
|
402
277
|
source: "prisma"
|
|
403
|
-
}
|
|
278
|
+
};
|
|
279
|
+
if (input.fallback !== null) return {
|
|
404
280
|
url: input.fallback,
|
|
405
281
|
source: "env"
|
|
406
|
-
} : null;
|
|
407
|
-
if (found !== null) return {
|
|
408
|
-
found,
|
|
409
|
-
reason: null
|
|
410
|
-
};
|
|
411
|
-
return {
|
|
412
|
-
found: null,
|
|
413
|
-
reason: datasource?.kind === "env" ? `${input.where} reads the database URL from env("${datasource.name}"), but ${datasource.name} is not set.\n Set it in .env or the environment, or pass --url <connection string>.` : "No database URL found.\n Set `url` in hekireki.config.ts, name the variable in prisma.config.ts (`datasource: { url: env(\"DATABASE_URL\") }`) and set it in .env or the environment, or pass --url <connection string>."
|
|
414
282
|
};
|
|
283
|
+
return null;
|
|
415
284
|
}
|
|
416
|
-
const
|
|
285
|
+
const DIALECT_OF_SCHEME = new Map([
|
|
417
286
|
"postgresql",
|
|
418
287
|
"mysql",
|
|
419
288
|
"sqlite"
|
|
420
|
-
];
|
|
289
|
+
].flatMap((dialect) => DIALECT_SCHEMES[dialect].map((scheme) => [scheme, dialect])));
|
|
421
290
|
/** The dialect from the URL scheme, falling back to the schema provider. */
|
|
422
291
|
function makeDialect(input) {
|
|
423
292
|
const scheme = input.url.split(":")[0]?.toLowerCase() ?? "";
|
|
424
|
-
const named =
|
|
293
|
+
const named = DIALECT_OF_SCHEME.get(scheme);
|
|
425
294
|
if (named !== void 0) return named;
|
|
426
295
|
const provider = input.schemaProvider;
|
|
427
296
|
if (provider === "postgresql" || provider === "cockroachdb") return "postgresql";
|
|
@@ -467,7 +336,7 @@ var DatabaseUrlNotFoundError = class extends Data.TaggedError("DatabaseUrlNotFou
|
|
|
467
336
|
* One set to the empty string counts as not set.
|
|
468
337
|
*/
|
|
469
338
|
function environmentVariable(name) {
|
|
470
|
-
return Config.option(Config.String(name)).pipe(Effect.map(
|
|
339
|
+
return Config.option(Config.String(name)).pipe(Effect.map(nonEmptyOrNull), Effect.orElseSucceed(() => null));
|
|
471
340
|
}
|
|
472
341
|
/**
|
|
473
342
|
* `--url`, then `url` in hekireki.config.ts, then whatever Prisma itself connects with: the
|
|
@@ -494,6 +363,9 @@ function makeDatabaseUrl(input) {
|
|
|
494
363
|
return yield* new DatabaseUrlNotFoundError({ reason: choice.reason });
|
|
495
364
|
});
|
|
496
365
|
}
|
|
366
|
+
function nonEmptyOrNull(value) {
|
|
367
|
+
return Option.getOrNull(Option.filter(value, (text) => text !== ""));
|
|
368
|
+
}
|
|
497
369
|
// src/schema/errors.ts
|
|
498
370
|
/** The schema path is not there, names a directory with no .prisma file, or a file did not read. */
|
|
499
371
|
var SchemaFileError = class extends Data.TaggedError("SchemaFileError") {};
|
|
@@ -512,7 +384,7 @@ function readSchemaFiles(schemaPath) {
|
|
|
512
384
|
return yield* Effect.forEach(paths, (file) => readFile(file).pipe(Effect.map((content) => ({
|
|
513
385
|
path: file,
|
|
514
386
|
content
|
|
515
|
-
})), Effect.mapError((error) => new SchemaFileError({ message: error.message }))));
|
|
387
|
+
})), Effect.mapError((error) => new SchemaFileError({ message: error.message }))), { concurrency: 1 });
|
|
516
388
|
});
|
|
517
389
|
}
|
|
518
390
|
/** The schema as one text, for the `url` a datasource block may still carry. */
|
|
@@ -632,4 +504,4 @@ const DIALECTS = {
|
|
|
632
504
|
function dialectOf(provider) {
|
|
633
505
|
return provider === null ? null : DIALECTS[provider] ?? null;
|
|
634
506
|
}
|
|
635
|
-
export {
|
|
507
|
+
export { primaryKeyFields as A, isJoinSideA as C, lengthArg as D, isUlidDefault as E, uuidDefaultVersion as F, chunks as I, isSameList as L, relationEnds as M, scalarFields as N, manyToManyRelations as O, tableName as P, fmt as R, isImplicitManyToMany as S, isNowDefault as T, cuidDefaultVersion as _, schemaText as a, isAutoincrement as b, makeDatabaseUrl as c, makePostgresSchema as d, makeRedactedUrl as f, columnName as g, backRelation as h, readSchemaFiles as i, referentialActions as j, nanoidDefault as k, isLibsqlUrl as l, formatSql as m, parseSchema as n, DatabaseUrlNotFoundError as o, makeSqliteFilePath as p, readConfig as r, environmentVariable as s, dialectOf as t, makeDialect as u, fieldColumn as v, isListDefault as w, isFunctionDefault as x, implicitJoinTables as y, fmtMarkdown as z };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { s as readFile, t as exists, u as writeFile } from "./file-DOGnu_Q2.js";
|
|
2
2
|
import { b as readPrismaConfig } from "./bin/hekireki.js";
|
|
3
|
-
import {
|
|
3
|
+
import { I as chunks, c as makeDatabaseUrl, o as DatabaseUrlNotFoundError } from "./schema-CyJTUCF1.js";
|
|
4
4
|
import nodeModule from "node:module";
|
|
5
5
|
import { ConfigProvider, Data, Effect, FileSystem, Schema, SchemaIssue } from "effect";
|
|
6
6
|
import path from "node:path";
|
|
@@ -46,17 +46,24 @@ function stringLiteral(dialect, value) {
|
|
|
46
46
|
*/
|
|
47
47
|
function resolveDatabaseUrl(options) {
|
|
48
48
|
return Effect.gen(function* () {
|
|
49
|
-
const variables = yield* Effect.forEach([.../* @__PURE__ */ new Set([options.schemaDir, options.cwd])], (dir) => readFile(path.join(dir, ".env")).pipe(Effect.map(
|
|
50
|
-
const config = (yield* Effect.forEach([.../* @__PURE__ */ new Set([options.cwd, options.schemaDir])], (dir) => readPrismaConfig(dir))).find((found) => found !== null) ?? null;
|
|
49
|
+
const variables = yield* Effect.forEach([.../* @__PURE__ */ new Set([options.schemaDir, options.cwd])], (dir) => readFile(path.join(dir, ".env")).pipe(Effect.map(envEntries), Effect.orElseSucceed(() => [])), { concurrency: 1 });
|
|
50
|
+
const config = (yield* Effect.forEach([.../* @__PURE__ */ new Set([options.cwd, options.schemaDir])], (dir) => readPrismaConfig(dir), { concurrency: 1 })).find((found) => found !== null) ?? null;
|
|
51
51
|
return yield* makeDatabaseUrl({
|
|
52
52
|
explicit: options.explicitUrl,
|
|
53
53
|
configUrl: options.configUrl,
|
|
54
54
|
configText: config?.text ?? null,
|
|
55
|
-
configName: config === null ? null :
|
|
55
|
+
configName: config === null ? null : shownPath(options.cwd, config.file),
|
|
56
56
|
schemaText: options.schemaText
|
|
57
57
|
}).pipe(Effect.provide(ConfigProvider.layerAdd(ConfigProvider.fromEnvRecord(Object.fromEntries(variables.flat())))), Effect.mapError((error) => options.configError === null ? error : new DatabaseUrlNotFoundError({ reason: `hekireki.config.ts could not be read for its \`url\`: ${options.configError}` })));
|
|
58
58
|
});
|
|
59
59
|
}
|
|
60
|
+
function envEntries(text) {
|
|
61
|
+
return Object.entries(parseEnv(text)).flatMap(([name, value]) => value === void 0 ? [] : [[name, value]]);
|
|
62
|
+
}
|
|
63
|
+
function shownPath(cwd, file) {
|
|
64
|
+
const relative = path.relative(cwd, file);
|
|
65
|
+
return relative.startsWith("..") ? file : relative;
|
|
66
|
+
}
|
|
60
67
|
// src/seed/errors.ts
|
|
61
68
|
/** hekireki.config.ts is missing, cannot be loaded, or names something the seeder cannot use. */
|
|
62
69
|
var SeedConfigError = class extends Data.TaggedError("SeedConfigError") {};
|
|
@@ -293,26 +300,43 @@ function timestamp(date) {
|
|
|
293
300
|
function enumStored(column, value) {
|
|
294
301
|
return column.enumValues?.find((member) => member.name === value)?.dbName ?? value;
|
|
295
302
|
}
|
|
303
|
+
/** An array element as text, before it is quoted. */
|
|
304
|
+
function elementText(column, value) {
|
|
305
|
+
if (value instanceof Date) return `${timestamp(value)}+00`;
|
|
306
|
+
if (value instanceof Uint8Array) return `\\x${Buffer.from(value).toString("hex")}`;
|
|
307
|
+
if (typeof value === "string") return column.kind === "enum" ? enumStored(column, value) : value;
|
|
308
|
+
return JSON.stringify(value);
|
|
309
|
+
}
|
|
296
310
|
/** One element of a PostgreSQL array literal (`'{...}'`), quoted and escaped as the array parser expects. */
|
|
297
311
|
function arrayElement(column, value) {
|
|
298
312
|
if (value === null) return "NULL";
|
|
299
313
|
if (typeof value === "boolean") return value ? "t" : "f";
|
|
300
314
|
if (typeof value === "number" || typeof value === "bigint") return String(value);
|
|
301
|
-
return `"${(
|
|
315
|
+
return `"${elementText(column, value).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
|
|
316
|
+
}
|
|
317
|
+
function listLiteral(dialect, column, value) {
|
|
318
|
+
const items = isSeedList(value) ? value : [value];
|
|
319
|
+
return dialect === "postgresql" ? stringLiteral(dialect, `{${items.map((item) => arrayElement(column, item)).join(",")}}`) : stringLiteral(dialect, JSON.stringify(items.map((item) => jsonValue(item))));
|
|
320
|
+
}
|
|
321
|
+
function booleanLiteral(dialect, value) {
|
|
322
|
+
if (dialect === "sqlite") return value ? "1" : "0";
|
|
323
|
+
return value ? "TRUE" : "FALSE";
|
|
324
|
+
}
|
|
325
|
+
function dateLiteral(dialect, value) {
|
|
326
|
+
if (dialect === "postgresql") return `'${timestamp(value)}+00'`;
|
|
327
|
+
if (dialect === "mysql") return `'${timestamp(value)}'`;
|
|
328
|
+
return `'${value.toISOString().replace("Z", "+00:00")}'`;
|
|
302
329
|
}
|
|
303
330
|
/** The SQL literal for a value in the column, as the dialect reads it. */
|
|
304
331
|
function renderLiteral(dialect, column, value) {
|
|
305
332
|
if (value === null || value === void 0) return "NULL";
|
|
306
|
-
if (column.isList)
|
|
307
|
-
const items = isSeedList(value) ? value : [value];
|
|
308
|
-
return dialect === "postgresql" ? stringLiteral(dialect, `{${items.map((item) => arrayElement(column, item)).join(",")}}`) : stringLiteral(dialect, JSON.stringify(items.map((item) => jsonValue(item))));
|
|
309
|
-
}
|
|
333
|
+
if (column.isList) return listLiteral(dialect, column, value);
|
|
310
334
|
if (column.type === "Json") return stringLiteral(dialect, JSON.stringify(jsonValue(value)));
|
|
311
335
|
if (typeof value === "string") return stringLiteral(dialect, column.kind === "enum" ? enumStored(column, value) : value);
|
|
312
336
|
if (typeof value === "number") return Number.isFinite(value) ? String(value) : "NULL";
|
|
313
337
|
if (typeof value === "bigint") return value.toString();
|
|
314
|
-
if (typeof value === "boolean") return dialect
|
|
315
|
-
if (value instanceof Date) return
|
|
338
|
+
if (typeof value === "boolean") return booleanLiteral(dialect, value);
|
|
339
|
+
if (value instanceof Date) return dateLiteral(dialect, value);
|
|
316
340
|
if (value instanceof Uint8Array) {
|
|
317
341
|
const hex = Buffer.from(value).toString("hex");
|
|
318
342
|
return dialect === "postgresql" ? `'\\x${hex}'` : `X'${hex}'`;
|
|
@@ -334,7 +358,8 @@ function insertSql(dialect, entry, chunk = INSERT_CHUNK) {
|
|
|
334
358
|
const columns = columnsOf(entry.table);
|
|
335
359
|
const target = qualifiedName(dialect, entry.table);
|
|
336
360
|
const names = columns.map((c) => quoteIdentifier(dialect, c.column)).join(", ");
|
|
337
|
-
const
|
|
361
|
+
const fieldOf = new Map(entry.table.kind === "model" ? entry.table.columns.map((c) => [c.column, c.field]) : []);
|
|
362
|
+
const fields = columns.map((column) => fieldOf.get(column.column) ?? column.column);
|
|
338
363
|
return chunks(entry.rows, chunk).map((rows) => `INSERT INTO ${target} (${names}) VALUES\n${rows.map((row) => ` (${columns.map((column, at) => renderLiteral(dialect, column, row[fields[at] ?? column.column] ?? null)).join(", ")})`).join(",\n")};`);
|
|
339
364
|
}
|
|
340
365
|
/** `DELETE FROM` every seeded table, children first, so no foreign key is left dangling. */
|
|
@@ -352,13 +377,17 @@ function resetSql(dialect, tables) {
|
|
|
352
377
|
*/
|
|
353
378
|
function sequenceSql(dialect, tables) {
|
|
354
379
|
if (dialect !== "postgresql") return [];
|
|
355
|
-
return tables.flatMap((table) =>
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
380
|
+
return tables.flatMap((table) => {
|
|
381
|
+
if (table.kind !== "model") return [];
|
|
382
|
+
const byField = new Map(table.columns.map((c) => [c.field, c]));
|
|
383
|
+
return table.autoincrement.flatMap((field) => {
|
|
384
|
+
const column = byField.get(field);
|
|
385
|
+
if (column === void 0) return [];
|
|
386
|
+
const target = qualifiedName(dialect, table);
|
|
387
|
+
const name = quoteIdentifier(dialect, column.column);
|
|
388
|
+
return [`SELECT setval(pg_get_serial_sequence(${stringLiteral(dialect, target)}, ${stringLiteral(dialect, column.column)}), COALESCE((SELECT MAX(${name}) FROM ${target}), 0) + 1, false)`];
|
|
389
|
+
});
|
|
390
|
+
});
|
|
362
391
|
}
|
|
363
392
|
/** The whole seed as one SQL script: a transaction around the optional reset, the inserts and the sequence fix-ups. */
|
|
364
393
|
function makeSeedSql(input) {
|