hekireki 0.34.0 → 0.37.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/README.md +17 -17
- 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/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 +80 -20
- package/dist/bin/kysely.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-B2PLRVJb.js → bin-CVN0pzc4.js} +412 -674
- package/dist/{discover-BNQ5gbRn.js → discover-CcuFW0ZA.js} +1 -1
- package/dist/{emit-BeblTVH8.js → emit-ALVe1wlq.js} +2 -2
- package/dist/{file-Df9ykHXv.js → file-BTbZL3ea.js} +12 -6
- package/dist/index.d.ts +1 -1
- package/dist/{migrate-Icu7Se0-.js → migrate-DmUsB0Wq.js} +4 -4
- package/dist/{plan-EKATG1WY.js → plan-FKGe6CzO.js} +8 -8
- package/dist/{utils-ckthTWS0.js → prisma-model-NuNLrPtP.js} +103 -11
- package/dist/{run-C13eFGuX.js → run-qU5ejzJJ.js} +17 -19
- package/dist/{schema-RYU_i7qd.js → schema-D8vxD4Kv.js} +3 -8
- package/dist/{sql-F40UQMF6.js → sql-BWRXT82c.js} +157 -78
- package/dist/{start-HLOLxRBL.js → start-DCHq_ac3.js} +57 -98
- package/dist/studio/assets/{chip-BasDLVHw.js → chip-DzylbrFL.js} +1 -1
- package/dist/studio/assets/{client-D-BDuDx5.js → client-Dntzxukj.js} +1 -1
- package/dist/studio/assets/{code-block-Bo0pcw3d.js → code-block-9KOaLIVF.js} +1 -1
- package/dist/studio/assets/{codicon-Brq4_Ui5.ttf → codicon-DF1abBS2.ttf} +0 -0
- package/dist/studio/assets/{confirm-dialog-GIPt_m1h.js → confirm-dialog-_tJslTz8.js} +1 -1
- package/dist/studio/assets/{copy-DVfEjDPw.js → copy-BU2HaQi8.js} +1 -1
- package/dist/studio/assets/{copy-button-Di-sHQ2O.js → copy-button-0vjAmGWM.js} +1 -1
- package/dist/studio/assets/{dist-CebhqUaX.js → dist-DZceSPCo.js} +1 -1
- package/dist/studio/assets/{docs-CnzWByuq.js → docs-CaVCv7nB.js} +1 -1
- package/dist/studio/assets/editor.worker-DWPaKKV_.js +33 -0
- package/dist/studio/assets/{enums._name-I0mP3WCt.js → enums._name-z71scSmR.js} +1 -1
- package/dist/studio/assets/{hooks-B5oExX5W.js → hooks-CIyp76Ha.js} +1 -1
- package/dist/studio/assets/{index-CMmzpMBz.js → index-BplvUeah.js} +7 -7
- package/dist/studio/assets/{labels-DuphOVul.js → labels-CxkkiH5p.js} +1 -1
- package/dist/studio/assets/{lazyRouteComponent-tS2t_LrD.js → lazyRouteComponent-HlW_UM7H.js} +1 -1
- package/dist/studio/assets/{lu-cVORv6D3.js → lu-C9ww8Xn7.js} +2 -2
- package/dist/studio/assets/{marked-text-tf7-IzXm.js → marked-text-DkIbIGaf.js} +1 -1
- package/dist/studio/assets/{models._name-DsOwcKoe.js → models._name-Bf8RXxTl.js} +1 -1
- package/dist/studio/assets/{monaco-GJe6VaZ-.js → monaco-B9PsjQQo.js} +1 -1
- package/dist/studio/assets/monaco-CT2wGeIj.css +1 -0
- package/dist/studio/assets/monaco-dYT_niNG.js +943 -0
- package/dist/studio/assets/{not-found-yBWFg0rP.js → not-found-4wswYq0J.js} +1 -1
- package/dist/studio/assets/{prisma-CWAhnzN5.js → prisma-BpS-GoYm.js} +1 -1
- package/dist/studio/assets/{result-table-CGvil3pc.js → result-table-DvGl9IoJ.js} +1 -1
- package/dist/studio/assets/routes-cRDXK5Bp.js +1 -0
- package/dist/studio/assets/{schema-gate-BC3i18Tp.js → schema-gate-BvdKOqn1.js} +1 -1
- package/dist/studio/assets/{schema-view-C2X5nwuH.js → schema-view-CqNyYGB0.js} +1 -1
- package/dist/studio/assets/{sql-CMRDYX3Z.js → sql-iadv3BWl.js} +1 -1
- package/dist/studio/assets/{table-bAwthXaP.js → table-DUjzf1P8.js} +1 -1
- package/dist/studio/assets/{tabs-DfoRK_ae.js → tabs-DJr-DjH8.js} +1 -1
- package/dist/studio/assets/{useFormValidation-B7STfHY3.js → useFormValidation-BB_6NZbP.js} +1 -1
- package/dist/studio/assets/{useMatch-DMTwaRaz.js → useMatch-CLknNl5M.js} +1 -1
- package/dist/studio/assets/{useMultipleSelectionState-vASeYbQk.js → useMultipleSelectionState-BqzE75CP.js} +1 -1
- package/dist/studio/assets/{useOverlayTriggerState-BO95y8NP.js → useOverlayTriggerState-DVeiBmOc.js} +1 -1
- package/dist/studio/index.html +10 -10
- package/package.json +19 -19
- package/dist/studio/assets/editor.worker-BbVB3hfz.js +0 -33
- package/dist/studio/assets/monaco-DbPgUJqj.js +0 -880
- package/dist/studio/assets/monaco-I0M_1p4d.css +0 -1
- package/dist/studio/assets/routes-CBvE-Puz.js +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
import { n as emitMany, r as emitRaw, t as emit } from "./emit-
|
|
3
|
-
import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-
|
|
4
|
-
import { NodeFileSystem } from "@effect/platform-node";
|
|
1
|
+
import { A as makeValidationExtractor, C as isAnnotationLine, E as isSameList, M as schemaFromFields, N as stripAnnotations, O as makePascalCase, S as indexPrefix, _ as extractObjectType, a as isFunctionDefault, b as getStrings, c as isListDefault, d as manyToManyRelations, f as relationEnds, g as constraintName, i as isAutoincrement, k as makeSnakeCase, l as isNowDefault$1, m as uuidDefaultVersion, n as columnName, o as isImplicitManyToMany, p as tableName, r as implicitJoinTables, s as isJoinSideA, t as backRelation, u as isUlidDefault, v as getBool, w as isFields, x as groupByModel, y as getString } from "./prisma-model-NuNLrPtP.js";
|
|
2
|
+
import { n as emitMany, r as emitRaw, t as emit } from "./emit-ALVe1wlq.js";
|
|
3
|
+
import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-D8vxD4Kv.js";
|
|
5
4
|
import { Data, Effect } from "effect";
|
|
6
5
|
import path from "node:path";
|
|
6
|
+
import { layer } from "@effect/platform-node/NodeFileSystem";
|
|
7
7
|
import pkg from "@prisma/generator-helper";
|
|
8
8
|
import { graphlib, layout } from "@dagrejs/dagre";
|
|
9
9
|
import * as z from "zod";
|
|
@@ -920,9 +920,6 @@ function primaryKeyFields(model) {
|
|
|
920
920
|
const idField = model.fields.find((f) => f.isId);
|
|
921
921
|
return idField ? [idField.name] : model.primaryKey?.fields ?? [];
|
|
922
922
|
}
|
|
923
|
-
function isSameList$1(a, b) {
|
|
924
|
-
return a.length === b.length && a.every((value, i) => value === b[i]);
|
|
925
|
-
}
|
|
926
923
|
function rubyArray(items) {
|
|
927
924
|
if (items.length === 0) return "[]";
|
|
928
925
|
if (items.every((item) => /^:[a-z_][a-z0-9_]*$/u.test(item))) return `%i[${items.map((item) => item.slice(1)).join(" ")}]`;
|
|
@@ -1238,70 +1235,53 @@ function getAssociations$5(model, allModels) {
|
|
|
1238
1235
|
const hasMany = [];
|
|
1239
1236
|
const hasOne = [];
|
|
1240
1237
|
const habtm = [];
|
|
1241
|
-
for (const
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1238
|
+
for (const end of relationEnds(model, allModels)) {
|
|
1239
|
+
const { field } = end;
|
|
1240
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
1241
|
+
if (end.kind === "belongsTo") {
|
|
1242
|
+
const fromFields = field.relationFromFields ?? [];
|
|
1245
1243
|
const referencedField = field.relationToFields?.[0] ?? "id";
|
|
1246
1244
|
const referencedFields = field.relationToFields ?? ["id"];
|
|
1247
|
-
const inverse = targetModel?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && !(f.relationFromFields && f.relationFromFields.length > 0));
|
|
1248
1245
|
belongsTo.push({
|
|
1249
1246
|
name: field.name,
|
|
1250
1247
|
targetModel: field.type,
|
|
1251
|
-
foreignKeyColumn: fieldColumn$1(model,
|
|
1248
|
+
foreignKeyColumn: fieldColumn$1(model, fromFields[0]),
|
|
1252
1249
|
primaryKeyColumn: targetModel ? fieldColumn$1(targetModel, referencedField) : referencedField,
|
|
1253
|
-
foreignKeyColumns:
|
|
1250
|
+
foreignKeyColumns: fromFields.map((c) => fieldColumn$1(model, c)),
|
|
1254
1251
|
primaryKeyColumns: referencedFields.map((c) => targetModel ? fieldColumn$1(targetModel, c) : c),
|
|
1255
|
-
referencesPrimaryKey: isSameList
|
|
1252
|
+
referencesPrimaryKey: isSameList(referencedFields, targetModel === void 0 ? ["id"] : primaryKeyFields(targetModel)),
|
|
1256
1253
|
optional: !field.isRequired,
|
|
1257
|
-
inverse: inverse?.name ?? null,
|
|
1258
|
-
inverseIsList: inverse?.isList ?? false
|
|
1254
|
+
inverse: end.inverse?.name ?? null,
|
|
1255
|
+
inverseIsList: end.inverse?.isList ?? false
|
|
1259
1256
|
});
|
|
1260
1257
|
continue;
|
|
1261
1258
|
}
|
|
1262
|
-
const targetModel = allModels.find((m) => m.name === field.type);
|
|
1263
1259
|
if (!targetModel) continue;
|
|
1264
|
-
if (
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
continue;
|
|
1275
|
-
}
|
|
1260
|
+
if (end.kind === "manyToMany") {
|
|
1261
|
+
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
1262
|
+
habtm.push({
|
|
1263
|
+
name: field.name,
|
|
1264
|
+
targetModel: field.type,
|
|
1265
|
+
joinTable: `_${field.relationName ?? `${left}To${right}`}`,
|
|
1266
|
+
foreignKey: end.isSideA ? "A" : "B",
|
|
1267
|
+
associationForeignKey: end.isSideA ? "B" : "A"
|
|
1268
|
+
});
|
|
1269
|
+
continue;
|
|
1276
1270
|
}
|
|
1277
|
-
const fkField =
|
|
1278
|
-
const
|
|
1279
|
-
|
|
1280
|
-
const foreignKeyColumn = fieldColumn$1(targetModel, foreignKey);
|
|
1281
|
-
const foreignKeyColumns = (fkField.relationFromFields ?? [foreignKey]).map((c) => fieldColumn$1(targetModel, c));
|
|
1282
|
-
const primaryKeyColumns = (fkField.relationToFields ?? ["id"]).map((c) => fieldColumn$1(model, c));
|
|
1283
|
-
const referencesPrimaryKey = isSameList$1(fkField.relationToFields ?? ["id"], primaryKeyFields(model));
|
|
1284
|
-
const onDelete = fkField.relationOnDelete ?? (fkField.isRequired ? "Restrict" : "SetNull");
|
|
1285
|
-
if (field.isList) hasMany.push({
|
|
1286
|
-
name: field.name,
|
|
1287
|
-
targetModel: field.type,
|
|
1288
|
-
foreignKeyColumn,
|
|
1289
|
-
foreignKeyColumns,
|
|
1290
|
-
primaryKeyColumns,
|
|
1291
|
-
referencesPrimaryKey,
|
|
1292
|
-
inverse: fkField.name,
|
|
1293
|
-
onDelete
|
|
1294
|
-
});
|
|
1295
|
-
else hasOne.push({
|
|
1271
|
+
const fkField = end.inverse;
|
|
1272
|
+
const fromFields = fkField.relationFromFields ?? [];
|
|
1273
|
+
const association = {
|
|
1296
1274
|
name: field.name,
|
|
1297
1275
|
targetModel: field.type,
|
|
1298
|
-
foreignKeyColumn,
|
|
1299
|
-
foreignKeyColumns,
|
|
1300
|
-
primaryKeyColumns,
|
|
1301
|
-
referencesPrimaryKey,
|
|
1276
|
+
foreignKeyColumn: fieldColumn$1(targetModel, fromFields[0]),
|
|
1277
|
+
foreignKeyColumns: fromFields.map((c) => fieldColumn$1(targetModel, c)),
|
|
1278
|
+
primaryKeyColumns: (fkField.relationToFields ?? ["id"]).map((c) => fieldColumn$1(model, c)),
|
|
1279
|
+
referencesPrimaryKey: isSameList(fkField.relationToFields ?? ["id"], primaryKeyFields(model)),
|
|
1302
1280
|
inverse: fkField.name,
|
|
1303
|
-
onDelete
|
|
1304
|
-
}
|
|
1281
|
+
onDelete: fkField.relationOnDelete ?? (fkField.isRequired ? "Restrict" : "SetNull")
|
|
1282
|
+
};
|
|
1283
|
+
if (end.kind === "hasMany") hasMany.push(association);
|
|
1284
|
+
else hasOne.push(association);
|
|
1305
1285
|
}
|
|
1306
1286
|
return {
|
|
1307
1287
|
belongsTo,
|
|
@@ -1600,43 +1580,63 @@ function activeRecordModelFiles(models, enums, provider) {
|
|
|
1600
1580
|
/** The generator block in schema.prisma is missing or names something the generator cannot use. */
|
|
1601
1581
|
var GeneratorConfigError = class extends Data.TaggedError("GeneratorConfigError") {};
|
|
1602
1582
|
//#endregion
|
|
1583
|
+
//#region src/core/output.ts
|
|
1584
|
+
/**
|
|
1585
|
+
* The `output` the generator block names. Without one Prisma would write beside the schema, so
|
|
1586
|
+
* the generator refuses instead, naming itself as `prisma generate` shows it.
|
|
1587
|
+
*/
|
|
1588
|
+
function requireOutput(options, prettyName) {
|
|
1589
|
+
const output = options.generator.isCustomOutput ? options.generator.output?.value : void 0;
|
|
1590
|
+
return output ? Effect.succeed(output) : Effect.fail(new GeneratorConfigError({ message: `output is required for ${prettyName}. Please specify output in your generator config.` }));
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* The file `output` names, or `fileName` in it when it names a directory, with the directory to
|
|
1594
|
+
* make before writing.
|
|
1595
|
+
*/
|
|
1596
|
+
function outputFile(output, fileName) {
|
|
1597
|
+
return path.extname(output) ? {
|
|
1598
|
+
dir: path.dirname(output),
|
|
1599
|
+
file: output
|
|
1600
|
+
} : {
|
|
1601
|
+
dir: output,
|
|
1602
|
+
file: path.join(output, fileName)
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
//#endregion
|
|
1603
1606
|
//#region src/core/activerecord.ts
|
|
1604
1607
|
function activerecord(options) {
|
|
1605
1608
|
return Effect.gen(function* () {
|
|
1606
|
-
|
|
1607
|
-
const outDir = options.generator.output.value;
|
|
1609
|
+
const output = yield* requireOutput(options, "Hekireki-ActiveRecord");
|
|
1608
1610
|
const problems = activeRecordProblems(options.dmmf.datamodel.models);
|
|
1609
1611
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-ActiveRecord cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
1610
1612
|
const enums = options.dmmf.datamodel.enums;
|
|
1611
1613
|
const provider = options.datasources[0]?.activeProvider;
|
|
1612
1614
|
const files = [...prismaDateTimeFiles(options.dmmf.datamodel.models, provider), ...activeRecordModelFiles(options.dmmf.datamodel.models, enums, provider)];
|
|
1613
|
-
const withBase = path.basename(
|
|
1615
|
+
const withBase = path.basename(output) === "models" ? [applicationRecordFile(), ...files] : files;
|
|
1614
1616
|
const localeFiles = activeRecordLocaleFiles(options.dmmf.datamodel.models);
|
|
1615
1617
|
if (localeFiles.length > 0) {
|
|
1616
1618
|
const locales = getString(options.generator.config?.locales);
|
|
1617
|
-
const localesDir = locales !== void 0 && locales !== "" ? path.resolve(
|
|
1619
|
+
const localesDir = locales !== void 0 && locales !== "" ? path.resolve(output, locales) : path.basename(output) === "models" ? path.resolve(output, "..", "..", "config", "locales") : yield* new GeneratorConfigError({ message: "locales is required for Hekireki-ActiveRecord when a `@ar.` message names a locale: the directory config/locales is written to, relative to output." });
|
|
1618
1620
|
yield* Effect.forEach(localeFiles, (f) => {
|
|
1619
|
-
const
|
|
1620
|
-
return emitRaw(f.code, path.dirname(
|
|
1621
|
+
const file = path.join(localesDir, f.fileName);
|
|
1622
|
+
return emitRaw(f.code, path.dirname(file), file);
|
|
1621
1623
|
}, { discard: true });
|
|
1622
1624
|
}
|
|
1623
|
-
return yield* emitMany(withBase,
|
|
1625
|
+
return yield* emitMany(withBase, output);
|
|
1624
1626
|
});
|
|
1625
1627
|
}
|
|
1626
1628
|
//#endregion
|
|
1627
1629
|
//#region src/utils/validation-schema.ts
|
|
1628
1630
|
function makePropertiesGenerator(libraryPrefix, wrapCardinality) {
|
|
1629
|
-
return function makeProperties(modelFields
|
|
1631
|
+
return function makeProperties(modelFields) {
|
|
1630
1632
|
return modelFields.filter((field) => field.validation).map((field) => {
|
|
1631
|
-
const cleanLines = field.comment.filter((line) => !(line.includes("@relation") || line.includes("@z") || line.includes("@v") || line.includes("@a") || line.includes("@e") || line.includes("@t") || line.includes("@j") || line.includes("@p")));
|
|
1632
|
-
const docComment = includeComments ? makeCommentBlock(cleanLines, 2) : "";
|
|
1633
1633
|
const base = `${libraryPrefix}.${field.validation}`;
|
|
1634
1634
|
const wrapped = wrapCardinality ? wrapCardinality(base, field.isRequired) : base;
|
|
1635
|
-
return
|
|
1635
|
+
return ` ${field.fieldName}: ${wrapped}`;
|
|
1636
1636
|
}).join(",\n");
|
|
1637
1637
|
};
|
|
1638
1638
|
}
|
|
1639
|
-
function validationSchemas(models, type,
|
|
1639
|
+
function validationSchemas(models, type, config) {
|
|
1640
1640
|
const modelInfos = models.map((model) => ({
|
|
1641
1641
|
documentation: model.documentation ?? "",
|
|
1642
1642
|
name: model.name,
|
|
@@ -1659,7 +1659,6 @@ function validationSchemas(models, type, comment, config) {
|
|
|
1659
1659
|
documentation: model.documentation,
|
|
1660
1660
|
modelName: model.name,
|
|
1661
1661
|
fieldName: field.name,
|
|
1662
|
-
comment: config.parseDocument(field.documentation),
|
|
1663
1662
|
validation: resolveValidation(field),
|
|
1664
1663
|
isRequired: field.isRequired
|
|
1665
1664
|
})));
|
|
@@ -1678,7 +1677,7 @@ function validationSchemas(models, type, comment, config) {
|
|
|
1678
1677
|
const schemas = Object.values(groupByModel(isFields(modelFields))).map((fields) => {
|
|
1679
1678
|
const objectType = extractObjectType(fields[0].documentation, config.annotationPrefix);
|
|
1680
1679
|
return {
|
|
1681
|
-
schema: config.schemas(fields,
|
|
1680
|
+
schema: config.schemas(fields, objectType),
|
|
1682
1681
|
inferType: type ? config.inferType(fields[0].modelName) : ""
|
|
1683
1682
|
};
|
|
1684
1683
|
}).flatMap(({ schema, inferType }) => [schema, inferType].filter(Boolean)).join("\n\n");
|
|
@@ -1707,11 +1706,9 @@ const PRISMA_TO_AJV = {
|
|
|
1707
1706
|
Json: "{}",
|
|
1708
1707
|
Bytes: "{ type: 'string' as const }"
|
|
1709
1708
|
};
|
|
1710
|
-
function makeAjvSchemas(modelFields,
|
|
1709
|
+
function makeAjvSchemas(modelFields, objectType) {
|
|
1711
1710
|
const modelName = modelFields[0].modelName;
|
|
1712
|
-
const properties = modelFields.map((field) => {
|
|
1713
|
-
return `${comment ? makeCommentBlock(field.comment, 4) : ""} ${field.fieldName}: ${field.validation ?? "{ type: 'unknown' as const }"},`;
|
|
1714
|
-
}).join("\n");
|
|
1711
|
+
const properties = modelFields.map((field) => ` ${field.fieldName}: ${field.validation ?? "{ type: 'unknown' as const }"},`).join("\n");
|
|
1715
1712
|
const requiredFields = modelFields.filter((f) => f.isRequired).map((f) => f.fieldName);
|
|
1716
1713
|
return `export const ${modelName}Schema = {\n type: 'object' as const,\n properties: {\n${properties}\n },${requiredFields.length > 0 ? `\n required: [${requiredFields.map((f) => `'${f}'`).join(", ")}] as const,` : ""}\n additionalProperties: ${objectType === "loose" ? "true" : "false"},\n} as const`;
|
|
1717
1714
|
}
|
|
@@ -1722,11 +1719,10 @@ function makeAjvRelations(model, relProps, options) {
|
|
|
1722
1719
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = FromSchema<typeof ${model.name}RelationsSchema>` : "";
|
|
1723
1720
|
return `export const ${model.name}RelationsSchema = {\n type: 'object' as const,\n properties: {\n${base}\n${rels}\n },\n additionalProperties: false,\n} as const${typeLine}`;
|
|
1724
1721
|
}
|
|
1725
|
-
function ajvSchemaCode(models, type,
|
|
1726
|
-
return validationSchemas(models, type,
|
|
1722
|
+
function ajvSchemaCode(models, type, enums) {
|
|
1723
|
+
return validationSchemas(models, type, {
|
|
1727
1724
|
importStatement: type ? `import type { FromSchema } from 'json-schema-to-ts'` : "",
|
|
1728
1725
|
annotationPrefix: "@j.",
|
|
1729
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
1730
1726
|
extractValidation: makeValidationExtractor("@j."),
|
|
1731
1727
|
inferType: makeAjvInfer,
|
|
1732
1728
|
schemas: makeAjvSchemas,
|
|
@@ -1757,23 +1753,15 @@ function makeRelationsOnly(dmmf, includeType, makeRelations) {
|
|
|
1757
1753
|
}
|
|
1758
1754
|
//#endregion
|
|
1759
1755
|
//#region src/generator/ajv.ts
|
|
1760
|
-
function ajvCode(dmmf, type,
|
|
1761
|
-
return [ajvSchemaCode(dmmf.datamodel.models, type,
|
|
1756
|
+
function ajvCode(dmmf, type, relation) {
|
|
1757
|
+
return [ajvSchemaCode(dmmf.datamodel.models, type, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeAjvRelations) : ""].filter(Boolean).join("\n\n");
|
|
1762
1758
|
}
|
|
1763
1759
|
//#endregion
|
|
1764
1760
|
//#region src/core/ajv.ts
|
|
1765
1761
|
function ajv(options) {
|
|
1766
1762
|
return Effect.gen(function* () {
|
|
1767
|
-
|
|
1768
|
-
const
|
|
1769
|
-
const resolved = path.extname(output) ? {
|
|
1770
|
-
dir: path.dirname(output),
|
|
1771
|
-
file: output
|
|
1772
|
-
} : {
|
|
1773
|
-
dir: output,
|
|
1774
|
-
file: path.join(output, "index.ts")
|
|
1775
|
-
};
|
|
1776
|
-
const code = ajvCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation));
|
|
1763
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-AJV"), "index.ts");
|
|
1764
|
+
const code = ajvCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
1777
1765
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
1778
1766
|
});
|
|
1779
1767
|
}
|
|
@@ -1785,10 +1773,8 @@ function makeArktypeInfer(modelName) {
|
|
|
1785
1773
|
function makeArktypeSchema(modelName, fields, objectType) {
|
|
1786
1774
|
return `export const ${modelName}Schema = type({${objectType === "strict" ? "\n \"+\": \"reject\",\n" : objectType === "loose" ? "\n \"+\": \"ignore\",\n" : "\n"}${fields}\n})`;
|
|
1787
1775
|
}
|
|
1788
|
-
function makeArktypeProperties(fields
|
|
1789
|
-
return fields.map((field) => {
|
|
1790
|
-
return `${comment ? makeCommentBlock(field.comment, 2) : ""} ${field.fieldName}: ${field.validation ?? "\"unknown\""},`;
|
|
1791
|
-
}).join("\n");
|
|
1776
|
+
function makeArktypeProperties(fields) {
|
|
1777
|
+
return fields.map((field) => ` ${field.fieldName}: ${field.validation ?? "\"unknown\""},`).join("\n");
|
|
1792
1778
|
}
|
|
1793
1779
|
function makeArktypeEnumExpression(values) {
|
|
1794
1780
|
return `"${values.map((v) => `'${v}'`).join(" | ")}"`;
|
|
@@ -1804,8 +1790,8 @@ const PRISMA_TO_ARKTYPE = {
|
|
|
1804
1790
|
Json: "\"unknown\"",
|
|
1805
1791
|
Bytes: "\"unknown\""
|
|
1806
1792
|
};
|
|
1807
|
-
function makeArktypeSchemas(modelFields,
|
|
1808
|
-
return schemaFromFields(modelFields,
|
|
1793
|
+
function makeArktypeSchemas(modelFields, objectType) {
|
|
1794
|
+
return schemaFromFields(modelFields, makeArktypeSchema, makeArktypeProperties, objectType);
|
|
1809
1795
|
}
|
|
1810
1796
|
function makeArktypeRelations(model, relProps, options) {
|
|
1811
1797
|
if (relProps.length === 0) return null;
|
|
@@ -1814,11 +1800,10 @@ function makeArktypeRelations(model, relProps, options) {
|
|
|
1814
1800
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = typeof ${model.name}RelationsSchema.infer` : "";
|
|
1815
1801
|
return `export const ${model.name}RelationsSchema = type({${base}${rels}})${typeLine}`;
|
|
1816
1802
|
}
|
|
1817
|
-
function arktypeSchemaCode(models, type,
|
|
1818
|
-
return validationSchemas(models, type,
|
|
1803
|
+
function arktypeSchemaCode(models, type, enums) {
|
|
1804
|
+
return validationSchemas(models, type, {
|
|
1819
1805
|
importStatement: `import { type } from 'arktype'`,
|
|
1820
1806
|
annotationPrefix: "@a.",
|
|
1821
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
1822
1807
|
extractValidation: makeValidationExtractor("@a."),
|
|
1823
1808
|
inferType: makeArktypeInfer,
|
|
1824
1809
|
schemas: makeArktypeSchemas,
|
|
@@ -1829,23 +1814,15 @@ function arktypeSchemaCode(models, type, comment, enums) {
|
|
|
1829
1814
|
}
|
|
1830
1815
|
//#endregion
|
|
1831
1816
|
//#region src/generator/arktype.ts
|
|
1832
|
-
function arktypeCode(dmmf, type,
|
|
1833
|
-
return [arktypeSchemaCode(dmmf.datamodel.models, type,
|
|
1817
|
+
function arktypeCode(dmmf, type, relation) {
|
|
1818
|
+
return [arktypeSchemaCode(dmmf.datamodel.models, type, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeArktypeRelations) : ""].filter(Boolean).join("\n\n");
|
|
1834
1819
|
}
|
|
1835
1820
|
//#endregion
|
|
1836
1821
|
//#region src/core/arktype.ts
|
|
1837
1822
|
function arktype(options) {
|
|
1838
1823
|
return Effect.gen(function* () {
|
|
1839
|
-
|
|
1840
|
-
const
|
|
1841
|
-
const resolved = path.extname(output) ? {
|
|
1842
|
-
dir: path.dirname(output),
|
|
1843
|
-
file: output
|
|
1844
|
-
} : {
|
|
1845
|
-
dir: output,
|
|
1846
|
-
file: path.join(output, "index.ts")
|
|
1847
|
-
};
|
|
1848
|
-
const code = arktypeCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation));
|
|
1824
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-ArkType"), "index.ts");
|
|
1825
|
+
const code = arktypeCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
1849
1826
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
1850
1827
|
});
|
|
1851
1828
|
}
|
|
@@ -1927,9 +1904,6 @@ function tableRef$1(target, models, defaultSchema) {
|
|
|
1927
1904
|
const name = tableNameOf(target);
|
|
1928
1905
|
return duplicateTableNames(models).has(name) ? `table${refPart(schemaOf(target, defaultSchema))}${refPart(name)}` : `table${refPart(name)}`;
|
|
1929
1906
|
}
|
|
1930
|
-
function isFunctionDefault$7(def) {
|
|
1931
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
1932
|
-
}
|
|
1933
1907
|
function pgNativeType$1(name, args) {
|
|
1934
1908
|
switch (name) {
|
|
1935
1909
|
case "Uuid": return "uuid";
|
|
@@ -2173,7 +2147,7 @@ function listDefault(items, field, dialect, enums) {
|
|
|
2173
2147
|
function resolveDefault(field, dialect, enums) {
|
|
2174
2148
|
const dflt = field.default;
|
|
2175
2149
|
if (!field.hasDefaultValue || dflt === void 0 || dflt === null) return void 0;
|
|
2176
|
-
if (isFunctionDefault
|
|
2150
|
+
if (isFunctionDefault(dflt)) {
|
|
2177
2151
|
if (dflt.name === "now") return dialect === "mysql" ? sqlExpr("CURRENT_TIMESTAMP(3)") : sqlExpr("CURRENT_TIMESTAMP");
|
|
2178
2152
|
if (dflt.name === "dbgenerated") return typeof dflt.args[0] === "string" ? sqlExpr(dflt.args[0]) : void 0;
|
|
2179
2153
|
return;
|
|
@@ -2188,7 +2162,7 @@ function resolveDefault(field, dialect, enums) {
|
|
|
2188
2162
|
}
|
|
2189
2163
|
function makeAtlasColumn(field, dialect, enums) {
|
|
2190
2164
|
const name = field.dbName ?? field.name;
|
|
2191
|
-
const isAutoincrement = isFunctionDefault
|
|
2165
|
+
const isAutoincrement = isFunctionDefault(field.default) && field.default.name === "autoincrement";
|
|
2192
2166
|
const typeInfo = columnTypeInfo(field, dialect, enums, isAutoincrement);
|
|
2193
2167
|
const defaultValue = isAutoincrement ? void 0 : resolveDefault(field, dialect, enums);
|
|
2194
2168
|
const attrs = [
|
|
@@ -2285,35 +2259,6 @@ function makeAtlasTable(model, models, indexes, dialect, enums, options) {
|
|
|
2285
2259
|
"}"
|
|
2286
2260
|
].join("\n");
|
|
2287
2261
|
}
|
|
2288
|
-
function isImplicitM2M$2(field, models) {
|
|
2289
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
2290
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
2291
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
2292
|
-
}
|
|
2293
|
-
function collectM2M(models) {
|
|
2294
|
-
const pairs = models.flatMap((model) => model.fields.filter((field) => isImplicitM2M$2(field, models)).map((field) => {
|
|
2295
|
-
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2296
|
-
return {
|
|
2297
|
-
leftName,
|
|
2298
|
-
rightName,
|
|
2299
|
-
relationName: field.relationName ?? `${leftName}To${rightName}`
|
|
2300
|
-
};
|
|
2301
|
-
}));
|
|
2302
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2303
|
-
return pairs.filter((pair) => {
|
|
2304
|
-
if (seen.has(pair.relationName)) return false;
|
|
2305
|
-
seen.add(pair.relationName);
|
|
2306
|
-
return true;
|
|
2307
|
-
}).flatMap((pair) => {
|
|
2308
|
-
const left = models.find((m) => m.name === pair.leftName);
|
|
2309
|
-
const right = models.find((m) => m.name === pair.rightName);
|
|
2310
|
-
return left && right ? [{
|
|
2311
|
-
left,
|
|
2312
|
-
right,
|
|
2313
|
-
relationName: pair.relationName
|
|
2314
|
-
}] : [];
|
|
2315
|
-
});
|
|
2316
|
-
}
|
|
2317
2262
|
function m2mColumn(side, pkField, dialect, enums) {
|
|
2318
2263
|
const type = pkField ? columnTypeInfo(pkField, dialect, enums, false).type : "text";
|
|
2319
2264
|
return [
|
|
@@ -2338,7 +2283,15 @@ function m2mForeignKey(side, target, tableName, models, defaultSchema) {
|
|
|
2338
2283
|
].join("\n");
|
|
2339
2284
|
}
|
|
2340
2285
|
function makeAtlasM2MJoinTables(models, dialect, enums, defaultSchema) {
|
|
2341
|
-
return
|
|
2286
|
+
return implicitJoinTables(models).flatMap((pair) => {
|
|
2287
|
+
const left = models.find((m) => m.name === pair.left);
|
|
2288
|
+
const right = models.find((m) => m.name === pair.right);
|
|
2289
|
+
return left && right ? [{
|
|
2290
|
+
left,
|
|
2291
|
+
right,
|
|
2292
|
+
relationName: pair.relationName
|
|
2293
|
+
}] : [];
|
|
2294
|
+
}).map((pair) => {
|
|
2342
2295
|
const tableName = `_${pair.relationName}`;
|
|
2343
2296
|
const leftPk = pair.left.fields.find((f) => f.isId);
|
|
2344
2297
|
const rightPk = pair.right.fields.find((f) => f.isId);
|
|
@@ -2399,17 +2352,33 @@ function atlasSchema(datamodel, provider, config) {
|
|
|
2399
2352
|
//#region src/core/atlas.ts
|
|
2400
2353
|
function atlas(options) {
|
|
2401
2354
|
return Effect.gen(function* () {
|
|
2402
|
-
|
|
2355
|
+
const output = yield* requireOutput(options, "Hekireki-Atlas");
|
|
2403
2356
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
2404
2357
|
if (!(provider === "postgresql" || provider === "cockroachdb" || provider === "mysql" || provider === "sqlite")) return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-Atlas: ${provider}. Supported providers are postgresql, cockroachdb, mysql, and sqlite.` });
|
|
2405
|
-
const output = options.generator.output.value;
|
|
2406
2358
|
const schemaName = getString(options.generator.config?.schemaName);
|
|
2407
2359
|
const content = atlasSchema(options.dmmf.datamodel, provider, { schemaName });
|
|
2408
|
-
const
|
|
2409
|
-
return yield* emitRaw(content,
|
|
2360
|
+
const resolved = outputFile(output, "schema.hcl");
|
|
2361
|
+
return yield* emitRaw(content, resolved.dir, resolved.file);
|
|
2410
2362
|
});
|
|
2411
2363
|
}
|
|
2412
2364
|
//#endregion
|
|
2365
|
+
//#region src/utils/python.ts
|
|
2366
|
+
/** A double-quoted Python string literal. */
|
|
2367
|
+
function toPythonString(value) {
|
|
2368
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
|
|
2369
|
+
}
|
|
2370
|
+
/** A JSON value as a Python literal: `None`, `True`, a list, a dict. */
|
|
2371
|
+
function jsonToPythonLiteral(value) {
|
|
2372
|
+
if (value === null) return "None";
|
|
2373
|
+
if (value === true) return "True";
|
|
2374
|
+
if (value === false) return "False";
|
|
2375
|
+
if (typeof value === "number") return String(value);
|
|
2376
|
+
if (typeof value === "string") return toPythonString(value);
|
|
2377
|
+
if (Array.isArray(value)) return `[${value.map(jsonToPythonLiteral).join(", ")}]`;
|
|
2378
|
+
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString(k)}: ${jsonToPythonLiteral(v)}`).join(", ")}}`;
|
|
2379
|
+
return "None";
|
|
2380
|
+
}
|
|
2381
|
+
//#endregion
|
|
2413
2382
|
//#region src/helper/django.ts
|
|
2414
2383
|
const PRISMA_TO_DJANGO = {
|
|
2415
2384
|
String: "TextField",
|
|
@@ -2596,37 +2565,8 @@ function resolveDjangoField(field) {
|
|
|
2596
2565
|
default: return baseResolved;
|
|
2597
2566
|
}
|
|
2598
2567
|
}
|
|
2599
|
-
function toPythonString$1(value) {
|
|
2600
|
-
return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
|
|
2601
|
-
}
|
|
2602
|
-
function jsonToPythonLiteral$1(value) {
|
|
2603
|
-
if (value === null) return "None";
|
|
2604
|
-
if (value === true) return "True";
|
|
2605
|
-
if (value === false) return "False";
|
|
2606
|
-
if (typeof value === "number") return String(value);
|
|
2607
|
-
if (typeof value === "string") return toPythonString$1(value);
|
|
2608
|
-
if (Array.isArray(value)) return `[${value.map(jsonToPythonLiteral$1).join(", ")}]`;
|
|
2609
|
-
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString$1(k)}: ${jsonToPythonLiteral$1(v)}`).join(", ")}}`;
|
|
2610
|
-
return "None";
|
|
2611
|
-
}
|
|
2612
|
-
function isFunctionDefault$6(def) {
|
|
2613
|
-
return def !== null && typeof def === "object" && "name" in def && !Array.isArray(def);
|
|
2614
|
-
}
|
|
2615
|
-
function isAutoincrement$3(field) {
|
|
2616
|
-
return isFunctionDefault$6(field.default) && field.default.name === "autoincrement";
|
|
2617
|
-
}
|
|
2618
|
-
function uuidDefaultVersion$1(field) {
|
|
2619
|
-
if (!(isFunctionDefault$6(field.default) && field.default.name === "uuid")) return null;
|
|
2620
|
-
return field.default.args[0] === 7 ? 7 : 4;
|
|
2621
|
-
}
|
|
2622
|
-
function isUlidDefault$1(field) {
|
|
2623
|
-
return isFunctionDefault$6(field.default) && field.default.name === "ulid";
|
|
2624
|
-
}
|
|
2625
|
-
function isNowDefault$2(field) {
|
|
2626
|
-
return field.type === "DateTime" && isFunctionDefault$6(field.default) && field.default.name === "now";
|
|
2627
|
-
}
|
|
2628
2568
|
function dbGeneratedExpr(field) {
|
|
2629
|
-
return isFunctionDefault
|
|
2569
|
+
return isFunctionDefault(field.default) && field.default.name === "dbgenerated" && typeof field.default.args[0] === "string" ? field.default.args[0] : null;
|
|
2630
2570
|
}
|
|
2631
2571
|
function dateTimeKind(field) {
|
|
2632
2572
|
const { ctor } = resolveDjangoField(field);
|
|
@@ -2644,7 +2584,7 @@ function dateTimeLiteral(field, iso) {
|
|
|
2644
2584
|
at.getUTCSeconds()
|
|
2645
2585
|
], ...micro > 0 ? [micro] : []].join(", ")})`;
|
|
2646
2586
|
}
|
|
2647
|
-
return `datetime.fromisoformat(${toPythonString
|
|
2587
|
+
return `datetime.fromisoformat(${toPythonString(iso)})`;
|
|
2648
2588
|
}
|
|
2649
2589
|
function holdsUtc(field, provider) {
|
|
2650
2590
|
if (field.type !== "DateTime" || resolveDjangoField(field).ctor !== "DateTimeField") return false;
|
|
@@ -2658,10 +2598,10 @@ function scalarElementLiteral(field, value) {
|
|
|
2658
2598
|
if (type === "BigInt") return value;
|
|
2659
2599
|
if (type === "Decimal") return `Decimal("${value}")`;
|
|
2660
2600
|
if (type === "DateTime") return dateTimeLiteral(field, value);
|
|
2661
|
-
if (type === "Json") return jsonToPythonLiteral
|
|
2662
|
-
return toPythonString
|
|
2601
|
+
if (type === "Json") return jsonToPythonLiteral(JSON.parse(value));
|
|
2602
|
+
return toPythonString(value);
|
|
2663
2603
|
}
|
|
2664
|
-
return jsonToPythonLiteral
|
|
2604
|
+
return jsonToPythonLiteral(value);
|
|
2665
2605
|
}
|
|
2666
2606
|
function fieldColumnName(field) {
|
|
2667
2607
|
return field.dbName ?? field.name;
|
|
@@ -2732,9 +2672,9 @@ function fieldDefaultHelper(model, field, names, enumMap) {
|
|
|
2732
2672
|
const parsed = JSON.parse(field.default);
|
|
2733
2673
|
if (typeof parsed === "object" && parsed !== null) {
|
|
2734
2674
|
if (Array.isArray(parsed) ? parsed.length === 0 : Object.keys(parsed).length === 0) return null;
|
|
2735
|
-
return [`def ${helperName}() -> ${Array.isArray(parsed) ? "list[Any]" : "dict[str, Any]"}:`, ` return ${jsonToPythonLiteral
|
|
2675
|
+
return [`def ${helperName}() -> ${Array.isArray(parsed) ? "list[Any]" : "dict[str, Any]"}:`, ` return ${jsonToPythonLiteral(parsed)}`].join("\n");
|
|
2736
2676
|
}
|
|
2737
|
-
return [`def ${helperName}() -> ${jsonScalarReturnType(parsed)}:`, ` return ${jsonToPythonLiteral
|
|
2677
|
+
return [`def ${helperName}() -> ${jsonScalarReturnType(parsed)}:`, ` return ${jsonToPythonLiteral(parsed)}`].join("\n");
|
|
2738
2678
|
}
|
|
2739
2679
|
return null;
|
|
2740
2680
|
}
|
|
@@ -2750,11 +2690,11 @@ function jsonScalarReturnType(parsed) {
|
|
|
2750
2690
|
function collectDefaultHelpers(models, names, enums) {
|
|
2751
2691
|
const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
|
|
2752
2692
|
const uuidHelpers = [
|
|
2753
|
-
models.some((m) => m.fields.some((f) => uuidDefaultVersion
|
|
2754
|
-
models.some((m) => m.fields.some((f) => uuidDefaultVersion
|
|
2755
|
-
models.some((m) => m.fields.some((f) => isUlidDefault
|
|
2693
|
+
models.some((m) => m.fields.some((f) => uuidDefaultVersion(f) === 4 && f.nativeType?.[0] !== "Uuid")) ? ["def uuid4_str() -> str:", " return str(uuid.uuid4())"].join("\n") : null,
|
|
2694
|
+
models.some((m) => m.fields.some((f) => uuidDefaultVersion(f) === 7 && f.nativeType?.[0] !== "Uuid")) ? ["def uuid7_str() -> str:", " return str(uuid6.uuid7())"].join("\n") : null,
|
|
2695
|
+
models.some((m) => m.fields.some((f) => isUlidDefault(f))) ? ["def ulid_str() -> str:", " return str(ULID())"].join("\n") : null
|
|
2756
2696
|
].filter((h) => h !== null);
|
|
2757
|
-
const nowKinds = new Set(models.flatMap((m) => m.fields.filter((f) => isNowDefault$
|
|
2697
|
+
const nowKinds = new Set(models.flatMap((m) => m.fields.filter((f) => isNowDefault$1(f) || f.isUpdatedAt).map((f) => dateTimeKind(f))));
|
|
2758
2698
|
const nowHelpers = [nowKinds.has("date") ? ["def utc_today() -> date:", " return datetime.now(dt_timezone.utc).date()"].join("\n") : null, nowKinds.has("time") ? ["def utc_time() -> time:", " return datetime.now(dt_timezone.utc).time()"].join("\n") : null].filter((h) => h !== null);
|
|
2759
2699
|
const fieldHelpers = models.flatMap((model) => model.fields.filter((f) => f.kind !== "object").map((field) => fieldDefaultHelper(model, field, names, enumMap)).filter((h) => h !== null));
|
|
2760
2700
|
return [
|
|
@@ -2822,20 +2762,20 @@ function collectFieldClasses(models, provider) {
|
|
|
2822
2762
|
function formatDefaultArgs(model, field, isPk, names) {
|
|
2823
2763
|
if (field.isUpdatedAt) return ["auto_now=True"];
|
|
2824
2764
|
const generated = dbGeneratedExpr(field);
|
|
2825
|
-
if (generated !== null) return [`db_default=RawSQL(${toPythonString
|
|
2826
|
-
if (isNowDefault$
|
|
2765
|
+
if (generated !== null) return [`db_default=RawSQL(${toPythonString(generated)}, [])`];
|
|
2766
|
+
if (isNowDefault$1(field)) {
|
|
2827
2767
|
const kind = dateTimeKind(field);
|
|
2828
2768
|
return [kind === "date" ? "default=utc_today" : kind === "time" ? "default=utc_time" : "default=timezone.now"];
|
|
2829
2769
|
}
|
|
2830
|
-
const uuidVersion = uuidDefaultVersion
|
|
2770
|
+
const uuidVersion = uuidDefaultVersion(field);
|
|
2831
2771
|
if (uuidVersion !== null) {
|
|
2832
2772
|
if (field.nativeType?.[0] === "Uuid") return [uuidVersion === 7 ? "default=uuid6.uuid7" : "default=uuid.uuid4"];
|
|
2833
2773
|
return [uuidVersion === 7 ? "default=uuid7_str" : "default=uuid4_str"];
|
|
2834
2774
|
}
|
|
2835
|
-
if (isUlidDefault
|
|
2775
|
+
if (isUlidDefault(field)) return ["default=ulid_str"];
|
|
2836
2776
|
const def = field.default;
|
|
2837
2777
|
if (def === void 0 || def === null) return [];
|
|
2838
|
-
if (isFunctionDefault
|
|
2778
|
+
if (isFunctionDefault(def)) return [];
|
|
2839
2779
|
if (Array.isArray(def)) return def.length === 0 ? ["default=list"] : [`default=${helperNameOf(names, model, field)}`];
|
|
2840
2780
|
if (field.kind === "enum" && typeof def === "string") return [`default=${makePascalCase(field.type)}.${enumMemberName(def)}`];
|
|
2841
2781
|
if (isPk) return [];
|
|
@@ -2853,7 +2793,7 @@ function formatDefaultArgs(model, field, isPk, names) {
|
|
|
2853
2793
|
}
|
|
2854
2794
|
return [`default=${helperNameOf(names, model, field)}`];
|
|
2855
2795
|
}
|
|
2856
|
-
return [`default=${toPythonString
|
|
2796
|
+
return [`default=${toPythonString(def)}`];
|
|
2857
2797
|
}
|
|
2858
2798
|
return [];
|
|
2859
2799
|
}
|
|
@@ -2868,7 +2808,7 @@ function generateScalarField(model, field, isPk, names, provider) {
|
|
|
2868
2808
|
ctor: "TextField",
|
|
2869
2809
|
typeArgs: [`choices=${makePascalCase(field.type)}.choices`]
|
|
2870
2810
|
} : resolveDjangoField(field);
|
|
2871
|
-
const ctorResolved = isPk && isAutoincrement
|
|
2811
|
+
const ctorResolved = isPk && isAutoincrement(field) ? {
|
|
2872
2812
|
ctor: autoFieldCtor(field),
|
|
2873
2813
|
typeArgs: []
|
|
2874
2814
|
} : resolved;
|
|
@@ -2882,7 +2822,7 @@ function generateScalarField(model, field, isPk, names, provider) {
|
|
|
2882
2822
|
isPk ? "primary_key=True" : null,
|
|
2883
2823
|
!field.isList && !field.isRequired ? "null=True" : null,
|
|
2884
2824
|
field.isUnique ? "unique=True" : null,
|
|
2885
|
-
attrName !== columnName ? `db_column=${toPythonString
|
|
2825
|
+
attrName !== columnName ? `db_column=${toPythonString(columnName)}` : null,
|
|
2886
2826
|
...defaultArgs,
|
|
2887
2827
|
emptyStringPk ? "default=None" : null
|
|
2888
2828
|
].filter((a) => a !== null);
|
|
@@ -2901,27 +2841,23 @@ function onDeleteFor(field) {
|
|
|
2901
2841
|
if (field.relationOnDelete && ON_DELETE[field.relationOnDelete]) return ON_DELETE[field.relationOnDelete];
|
|
2902
2842
|
return field.isRequired ? "models.RESTRICT" : "models.SET_NULL";
|
|
2903
2843
|
}
|
|
2904
|
-
function findBackRelationField(relationField, model, allModels) {
|
|
2905
|
-
const targetModel = allModels.find((m) => m.name === relationField.type);
|
|
2906
|
-
return targetModel?.fields.find((f) => f.kind === "object" && f.type === model.name && f.relationName === relationField.relationName && !(targetModel.name === model.name && f.name === relationField.name));
|
|
2907
|
-
}
|
|
2908
2844
|
function generateForeignKeyField(model, relationField, scalarField, allModels, names) {
|
|
2909
2845
|
const attrName = attrNameOf(names, model, relationField);
|
|
2910
2846
|
const columnName = fieldColumnName(scalarField);
|
|
2911
|
-
const backField =
|
|
2847
|
+
const backField = backRelation(relationField, model, allModels);
|
|
2912
2848
|
const ctor = backField && !backField.isList ? "OneToOneField" : "ForeignKey";
|
|
2913
2849
|
const target = relationField.type === model.name ? "\"self\"" : `"${makePascalCase(relationField.type)}"`;
|
|
2914
|
-
const relatedName = backField ? toPythonString
|
|
2850
|
+
const relatedName = backField ? toPythonString(djangoAttrName(makeSnakeCase(backField.name))) : "\"+\"";
|
|
2915
2851
|
const targetModel = allModels.find((m) => m.name === relationField.type);
|
|
2916
2852
|
const referencedName = relationField.relationToFields?.[0];
|
|
2917
2853
|
const referencedField = targetModel?.fields.find((f) => f.name === referencedName);
|
|
2918
|
-
const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString
|
|
2854
|
+
const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
|
|
2919
2855
|
return ` ${attrName} = models.${ctor}(${[
|
|
2920
2856
|
target,
|
|
2921
2857
|
`on_delete=${onDeleteFor(relationField)}`,
|
|
2922
2858
|
`related_name=${relatedName}`,
|
|
2923
2859
|
toField,
|
|
2924
|
-
columnName !== `${attrName}_id` ? `db_column=${toPythonString
|
|
2860
|
+
columnName !== `${attrName}_id` ? `db_column=${toPythonString(columnName)}` : null,
|
|
2925
2861
|
!relationField.isRequired ? "null=True" : null,
|
|
2926
2862
|
ctor === "ForeignKey" ? "db_index=False" : null,
|
|
2927
2863
|
...formatDefaultArgs(model, scalarField, false, names)
|
|
@@ -2936,9 +2872,7 @@ function uniqueClassName(preferred, taken) {
|
|
|
2936
2872
|
function collectManyToManyTables$1(allModels, enums) {
|
|
2937
2873
|
const candidates = allModels.flatMap((model) => model.fields.flatMap((field) => {
|
|
2938
2874
|
if (field.kind !== "object" || !field.isList) return [];
|
|
2939
|
-
|
|
2940
|
-
if (!targetModel) return [];
|
|
2941
|
-
if (!targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object" && !(targetModel.name === model.name && f.name === field.name))?.isList) return [];
|
|
2875
|
+
if (!backRelation(field, model, allModels)?.isList) return [];
|
|
2942
2876
|
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2943
2877
|
const relationName = field.relationName ?? `${leftName}To${rightName}`;
|
|
2944
2878
|
return [{
|
|
@@ -2973,18 +2907,18 @@ function generateThroughModel(info) {
|
|
|
2973
2907
|
` b = models.ForeignKey("${makePascalCase(info.rightModel)}", on_delete=models.CASCADE, related_name="+", db_column="B", db_index=False)`,
|
|
2974
2908
|
"",
|
|
2975
2909
|
" class Meta:",
|
|
2976
|
-
` db_table = ${toPythonString
|
|
2910
|
+
` db_table = ${toPythonString(info.tableName)}`,
|
|
2977
2911
|
" indexes = [",
|
|
2978
2912
|
" models.Index(fields=[\"b\"]),",
|
|
2979
2913
|
" ]"
|
|
2980
2914
|
].join("\n");
|
|
2981
2915
|
}
|
|
2982
2916
|
function generateManyToManyField(model, field, allModels, m2mTables, names) {
|
|
2983
|
-
const backField =
|
|
2917
|
+
const backField = backRelation(field, model, allModels);
|
|
2984
2918
|
const table = m2mTables.find((t) => t.relationName === field.relationName);
|
|
2985
2919
|
if (!table) return null;
|
|
2986
2920
|
const attrName = attrNameOf(names, model, field);
|
|
2987
|
-
const relatedName = backField ? toPythonString
|
|
2921
|
+
const relatedName = backField ? toPythonString(djangoAttrName(makeSnakeCase(backField.name))) : "\"+\"";
|
|
2988
2922
|
const targetClass = makePascalCase(field.type);
|
|
2989
2923
|
const args = [
|
|
2990
2924
|
`"${targetClass}"`,
|
|
@@ -3024,21 +2958,21 @@ function generateMetaLines(model, indexes, names) {
|
|
|
3024
2958
|
};
|
|
3025
2959
|
const uniqueIndexes = indexes.filter((idx) => idx.model === model.name && idx.type === "unique" && !idx.isDefinedOnField);
|
|
3026
2960
|
const constraints = model.uniqueFields.map((fields) => {
|
|
3027
|
-
return `models.UniqueConstraint(fields=[${fields.map((f) => toPythonString
|
|
2961
|
+
return `models.UniqueConstraint(fields=[${fields.map((f) => toPythonString(fieldRef(f))).join(", ")}], name=${toPythonString(uniqueIndexes.find((idx) => idx.fields.length === fields.length && idx.fields.every((f, i) => f.name === fields[i]))?.dbName ?? `${tableName}_${fields.map((f) => columnRef(f)).join("_")}_key`)})`;
|
|
3028
2962
|
});
|
|
3029
2963
|
const indexEntries = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
|
|
3030
2964
|
const fieldNames = idx.fields.map((f) => {
|
|
3031
2965
|
const ref = fieldRef(f.name);
|
|
3032
|
-
return toPythonString
|
|
2966
|
+
return toPythonString(f.sortOrder === "desc" ? `-${ref}` : ref);
|
|
3033
2967
|
}).join(", ");
|
|
3034
|
-
const name = idx.dbName !== void 0 && idx.dbName !== null && idx.dbName.length <= 30 && /^[a-zA-Z]/u.test(idx.dbName) ? `, name=${toPythonString
|
|
2968
|
+
const name = idx.dbName !== void 0 && idx.dbName !== null && idx.dbName.length <= 30 && /^[a-zA-Z]/u.test(idx.dbName) ? `, name=${toPythonString(idx.dbName)}` : "";
|
|
3035
2969
|
const ctor = postgresIndexClass(idx.algorithm);
|
|
3036
2970
|
return ctor === null ? `models.Index(fields=[${fieldNames}]${name})` : `${ctor}(fields=[${fieldNames}]${name})`;
|
|
3037
2971
|
});
|
|
3038
2972
|
return [
|
|
3039
2973
|
"",
|
|
3040
2974
|
" class Meta:",
|
|
3041
|
-
` db_table = ${toPythonString
|
|
2975
|
+
` db_table = ${toPythonString(tableName)}`,
|
|
3042
2976
|
...constraints.length > 0 ? [
|
|
3043
2977
|
" constraints = [",
|
|
3044
2978
|
...constraints.map((c) => ` ${c},`),
|
|
@@ -3057,7 +2991,7 @@ function compositePkLine(model, names) {
|
|
|
3057
2991
|
const belongsTo = singleColumnBelongsTo(model);
|
|
3058
2992
|
return ` pk = models.CompositePrimaryKey(${pkFields.map((prismaFieldName) => {
|
|
3059
2993
|
const attr = names.attr.get(nameKey(model.name, prismaFieldName)) ?? prismaFieldName;
|
|
3060
|
-
return toPythonString
|
|
2994
|
+
return toPythonString(belongsTo.some((f) => f.relationFromFields?.[0] === prismaFieldName) ? `${attr}_id` : attr);
|
|
3061
2995
|
}).join(", ")})`;
|
|
3062
2996
|
}
|
|
3063
2997
|
function findNameConflicts(models, enums) {
|
|
@@ -3098,21 +3032,21 @@ function generateModelBody$1(model, allModels, indexes, m2mTables, names, provid
|
|
|
3098
3032
|
].join("\n");
|
|
3099
3033
|
}
|
|
3100
3034
|
function generateEnumClass(enumDef) {
|
|
3101
|
-
return [`class ${makePascalCase(enumDef.name)}(models.TextChoices):`, ...enumDef.values.map((v) => ` ${enumMemberName(v.name)} = ${toPythonString
|
|
3035
|
+
return [`class ${makePascalCase(enumDef.name)}(models.TextChoices):`, ...enumDef.values.map((v) => ` ${enumMemberName(v.name)} = ${toPythonString(v.dbName ?? v.name)}`)].join("\n");
|
|
3102
3036
|
}
|
|
3103
3037
|
function collectGlobalImports$1(models, indexes, provider) {
|
|
3104
3038
|
const scalarFields = models.flatMap((m) => m.fields.filter((f) => f.kind !== "object"));
|
|
3105
3039
|
const modelNames = new Set(models.map((m) => m.name));
|
|
3106
3040
|
const indexClasses = indexes.filter((idx) => modelNames.has(idx.model) && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => postgresIndexClass(idx.algorithm)).filter((ctor) => ctor !== null);
|
|
3107
|
-
const needsUuid = scalarFields.some((f) => uuidDefaultVersion
|
|
3108
|
-
const needsUuid6 = scalarFields.some((f) => uuidDefaultVersion
|
|
3109
|
-
const needsUlid = scalarFields.some((f) => isUlidDefault
|
|
3041
|
+
const needsUuid = scalarFields.some((f) => uuidDefaultVersion(f) === 4);
|
|
3042
|
+
const needsUuid6 = scalarFields.some((f) => uuidDefaultVersion(f) === 7);
|
|
3043
|
+
const needsUlid = scalarFields.some((f) => isUlidDefault(f));
|
|
3110
3044
|
const needsArray = scalarFields.some((f) => f.isList);
|
|
3111
3045
|
const needsRawSql = scalarFields.some((f) => dbGeneratedExpr(f) !== null);
|
|
3112
3046
|
const needsUtcField = scalarFields.some((f) => holdsUtc(f, provider));
|
|
3113
3047
|
const needsAutoNow = scalarFields.some((f) => f.isUpdatedAt);
|
|
3114
3048
|
const literalKinds = scalarFields.filter((f) => f.type === "DateTime" && (typeof f.default === "string" || Array.isArray(f.default) && f.default.some((v) => typeof v === "string"))).map((f) => dateTimeKind(f));
|
|
3115
|
-
const nowKinds = scalarFields.filter((f) => isNowDefault$
|
|
3049
|
+
const nowKinds = scalarFields.filter((f) => isNowDefault$1(f) || f.isUpdatedAt).map((f) => dateTimeKind(f));
|
|
3116
3050
|
const nowHelperKinds = nowKinds.filter((kind) => kind !== "datetime");
|
|
3117
3051
|
const kinds = /* @__PURE__ */ new Set([
|
|
3118
3052
|
...literalKinds,
|
|
@@ -3178,16 +3112,14 @@ function djangoCode(models, enums, indexes, provider = "postgresql") {
|
|
|
3178
3112
|
//#region src/core/django.ts
|
|
3179
3113
|
function django(options) {
|
|
3180
3114
|
return Effect.gen(function* () {
|
|
3181
|
-
|
|
3182
|
-
const output = options.generator.output.value;
|
|
3183
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
3115
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Django"), "models.py");
|
|
3184
3116
|
const enums = options.dmmf.datamodel.enums;
|
|
3185
3117
|
const indexes = options.dmmf.datamodel.indexes;
|
|
3186
3118
|
const conflicts = findNameConflicts(options.dmmf.datamodel.models, enums);
|
|
3187
3119
|
if (conflicts.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Django cannot represent this schema:\n${conflicts.map((c) => ` - ${c}`).join("\n")}` });
|
|
3188
3120
|
const provider = options.datasources[0]?.activeProvider;
|
|
3189
3121
|
const code = djangoCode(options.dmmf.datamodel.models, enums, indexes, provider);
|
|
3190
|
-
return yield* emitRaw(code,
|
|
3122
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
3191
3123
|
});
|
|
3192
3124
|
}
|
|
3193
3125
|
//#endregion
|
|
@@ -3220,7 +3152,7 @@ const MYSQL_SCALAR_MAP = {
|
|
|
3220
3152
|
const SQLITE_SCALAR_MAP = {
|
|
3221
3153
|
String: "text()",
|
|
3222
3154
|
Int: "integer()",
|
|
3223
|
-
BigInt: "
|
|
3155
|
+
BigInt: "bigInteger()",
|
|
3224
3156
|
Float: "real()",
|
|
3225
3157
|
Decimal: "numeric()",
|
|
3226
3158
|
Boolean: "integer({ mode: 'boolean' })",
|
|
@@ -3292,6 +3224,11 @@ function mysqlNativeType(name, args) {
|
|
|
3292
3224
|
}
|
|
3293
3225
|
}
|
|
3294
3226
|
const COLUMN_HELPERS = {
|
|
3227
|
+
bigInteger: `const bigInteger = customType<{ data: bigint; driverData: number | bigint }>({
|
|
3228
|
+
dataType: () => 'bigint',
|
|
3229
|
+
toDriver: (value) => value,
|
|
3230
|
+
fromDriver: (value) => BigInt(value),
|
|
3231
|
+
})`,
|
|
3295
3232
|
bytea: `const bytea = customType<{ data: Uint8Array }>({
|
|
3296
3233
|
dataType: () => 'bytea',
|
|
3297
3234
|
})`,
|
|
@@ -3622,7 +3559,7 @@ function makeColumn(field, model, models, provider, imports, enums) {
|
|
|
3622
3559
|
if (field.isUpdatedAt || isFieldDefault(field.default) && field.default.name === "now") imports.helpers.add("utcNow");
|
|
3623
3560
|
const chain = [
|
|
3624
3561
|
field.isList && (field.kind === "scalar" || field.kind === "enum") && provider === "postgresql" ? ".array()" : "",
|
|
3625
|
-
field.isId && !hasCompositePK ? isAutoincrement && provider === "sqlite" ? ".primaryKey({ autoIncrement: true })" : ".primaryKey()" : "",
|
|
3562
|
+
field.isId && !hasCompositePK ? isAutoincrement && provider === "sqlite" && field.type !== "BigInt" ? ".primaryKey({ autoIncrement: true })" : ".primaryKey()" : "",
|
|
3626
3563
|
field.isRequired && !field.isList && !field.isId && !(isAutoincrement && provider === "postgresql") ? ".notNull()" : "",
|
|
3627
3564
|
isAutoincrement ? provider === "mysql" ? ".autoincrement()" : "" : makeDefaultChain(field, provider, imports, enums),
|
|
3628
3565
|
field.isUpdatedAt ? ".$onUpdate(utcNow)" : ""
|
|
@@ -3672,30 +3609,9 @@ function makeTable(model, models, provider, imports, enums, indexes) {
|
|
|
3672
3609
|
const constraints = makeTableConstraints(model, models, provider, imports, indexes, tableName);
|
|
3673
3610
|
return constraints ? `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, (table) => [${constraints}])` : `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
|
|
3674
3611
|
}
|
|
3675
|
-
function isImplicitM2M$1(field, models) {
|
|
3676
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
3677
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
3678
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
3679
|
-
}
|
|
3680
3612
|
function joinVarName(relationName) {
|
|
3681
3613
|
return snakeToCamel(makeSnakeCase(relationName));
|
|
3682
3614
|
}
|
|
3683
|
-
function collectM2MJoinTables(models) {
|
|
3684
|
-
const pairs = models.flatMap((model) => model.fields.filter((field) => isImplicitM2M$1(field, models)).map((field) => {
|
|
3685
|
-
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
3686
|
-
return {
|
|
3687
|
-
left,
|
|
3688
|
-
right,
|
|
3689
|
-
relationName: field.relationName ?? `${left}To${right}`
|
|
3690
|
-
};
|
|
3691
|
-
}));
|
|
3692
|
-
const seen = /* @__PURE__ */ new Set();
|
|
3693
|
-
return pairs.filter((pair) => {
|
|
3694
|
-
if (seen.has(pair.relationName)) return false;
|
|
3695
|
-
seen.add(pair.relationName);
|
|
3696
|
-
return true;
|
|
3697
|
-
});
|
|
3698
|
-
}
|
|
3699
3615
|
function withColumnName(baseExpr, colName) {
|
|
3700
3616
|
const parenIdx = baseExpr.indexOf("(");
|
|
3701
3617
|
const fnName = baseExpr.slice(0, parenIdx);
|
|
@@ -3710,7 +3626,7 @@ function pkColumnExpr(modelName, colName, models, provider, imports) {
|
|
|
3710
3626
|
}
|
|
3711
3627
|
function makeM2MJoinTables(models, provider, imports) {
|
|
3712
3628
|
const tableFunc = provider === "postgresql" ? "pgTable" : provider === "mysql" ? "mysqlTable" : "sqliteTable";
|
|
3713
|
-
return
|
|
3629
|
+
return implicitJoinTables(models).map((pair) => {
|
|
3714
3630
|
imports.core.add(tableFunc);
|
|
3715
3631
|
imports.core.add("foreignKey");
|
|
3716
3632
|
imports.core.add("index");
|
|
@@ -3735,7 +3651,7 @@ function makeM2MJoinTables(models, provider, imports) {
|
|
|
3735
3651
|
});
|
|
3736
3652
|
}
|
|
3737
3653
|
function makeM2MJoinRelations(models, imports) {
|
|
3738
|
-
const pairs =
|
|
3654
|
+
const pairs = implicitJoinTables(models);
|
|
3739
3655
|
if (pairs.length > 0) imports.orm.add("relations");
|
|
3740
3656
|
return pairs.map((pair) => {
|
|
3741
3657
|
const varName = joinVarName(pair.relationName);
|
|
@@ -3744,8 +3660,11 @@ function makeM2MJoinRelations(models, imports) {
|
|
|
3744
3660
|
const leftPk = models.find((m) => m.name === pair.left)?.fields.find((f) => f.isId);
|
|
3745
3661
|
const rightPk = models.find((m) => m.name === pair.right)?.fields.find((f) => f.isId);
|
|
3746
3662
|
const leftKey = uncapitalizeName(pair.left);
|
|
3747
|
-
const
|
|
3748
|
-
|
|
3663
|
+
const isSelf = pair.left === pair.right;
|
|
3664
|
+
const rightKey = isSelf ? `${uncapitalizeName(pair.right)}_` : uncapitalizeName(pair.right);
|
|
3665
|
+
const aName = isSelf ? `, relationName: '${pair.relationName}_A'` : "";
|
|
3666
|
+
const bName = isSelf ? `, relationName: '${pair.relationName}_B'` : "";
|
|
3667
|
+
return `export const ${varName}Relations = relations(${varName}, ({ one }) => ({ ${leftKey}: one(${leftVar}, { fields: [${varName}.A], references: [${leftVar}.${leftPk?.name ?? "id"}]${aName} }), ${rightKey}: one(${rightVar}, { fields: [${varName}.B], references: [${rightVar}.${rightPk?.name ?? "id"}]${bName} }) }))`;
|
|
3749
3668
|
});
|
|
3750
3669
|
}
|
|
3751
3670
|
function uncapitalizeName(name) {
|
|
@@ -3767,9 +3686,15 @@ function makeRelationField(field, model, models, relFields) {
|
|
|
3767
3686
|
return `${field.name}: one(${targetVar}, { ${configParts.join(", ")} })`;
|
|
3768
3687
|
}
|
|
3769
3688
|
if (field.isList) {
|
|
3770
|
-
if (
|
|
3689
|
+
if (isImplicitManyToMany(field, model, models)) {
|
|
3771
3690
|
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
3772
|
-
|
|
3691
|
+
const relationName = field.relationName ?? `${left}To${right}`;
|
|
3692
|
+
const inverse = backRelation(field, model, models);
|
|
3693
|
+
if (model.name === field.type && inverse) {
|
|
3694
|
+
const column = isJoinSideA(field, model, inverse) ? "A" : "B";
|
|
3695
|
+
return `${field.name}: many(${joinVarName(relationName)}, { relationName: '${relationName}_${column}' })`;
|
|
3696
|
+
}
|
|
3697
|
+
return `${field.name}: many(${joinVarName(relationName)})`;
|
|
3773
3698
|
}
|
|
3774
3699
|
return needsAlias ? `${field.name}: many(${targetVar}, { relationName: '${field.relationName}' })` : `${field.name}: many(${targetVar})`;
|
|
3775
3700
|
}
|
|
@@ -3823,18 +3748,11 @@ function parsePrismaProvider(raw) {
|
|
|
3823
3748
|
//#region src/core/drizzle.ts
|
|
3824
3749
|
function drizzle(options) {
|
|
3825
3750
|
return Effect.gen(function* () {
|
|
3826
|
-
|
|
3751
|
+
const output = yield* requireOutput(options, "Hekireki-Drizzle");
|
|
3827
3752
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
3828
3753
|
const providerResult = parsePrismaProvider(provider);
|
|
3829
3754
|
if (!providerResult.ok) return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-Drizzle: ${provider}. Supported providers are postgresql, cockroachdb, mysql, and sqlite.` });
|
|
3830
|
-
const
|
|
3831
|
-
const resolved = path.extname(output) ? {
|
|
3832
|
-
dir: path.dirname(output),
|
|
3833
|
-
file: output
|
|
3834
|
-
} : {
|
|
3835
|
-
dir: output,
|
|
3836
|
-
file: path.join(output, "schema.ts")
|
|
3837
|
-
};
|
|
3755
|
+
const resolved = outputFile(output, "schema.ts");
|
|
3838
3756
|
const code = drizzleSchema(options.dmmf.datamodel, providerResult.value, options.dmmf.datamodel.indexes);
|
|
3839
3757
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
3840
3758
|
});
|
|
@@ -3862,18 +3780,6 @@ function prismaConstraintName(base, suffix, limit = IDENTIFIER_LIMIT) {
|
|
|
3862
3780
|
const chars = [...base.matchAll(/./gsu)].map(([char]) => char);
|
|
3863
3781
|
return `${chars.filter((_, index) => utf8Length(chars.slice(0, index + 1).join("")) <= room).join("")}${suffix}`;
|
|
3864
3782
|
}
|
|
3865
|
-
function tableName(model) {
|
|
3866
|
-
return model.dbName ?? model.name;
|
|
3867
|
-
}
|
|
3868
|
-
function columnName(field) {
|
|
3869
|
-
return field.dbName ?? field.name;
|
|
3870
|
-
}
|
|
3871
|
-
function isListDefault(def) {
|
|
3872
|
-
return Array.isArray(def);
|
|
3873
|
-
}
|
|
3874
|
-
function isFunctionDefault$5(def) {
|
|
3875
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
3876
|
-
}
|
|
3877
3783
|
function modelIndexes(model, indexes) {
|
|
3878
3784
|
const own = indexes.filter((index) => index.model === model.name);
|
|
3879
3785
|
if (own.length > 0) return own;
|
|
@@ -3911,29 +3817,6 @@ function indexName(model, index) {
|
|
|
3911
3817
|
return field ? columnName(field) : f.name;
|
|
3912
3818
|
})].join("_"), index.type === "unique" ? "_key" : "_idx");
|
|
3913
3819
|
}
|
|
3914
|
-
function backRelation(field, owner, models) {
|
|
3915
|
-
const related = models.find((m) => m.name === field.type);
|
|
3916
|
-
return related?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && f.type === owner.name && !(related.name === owner.name && f.name === field.name));
|
|
3917
|
-
}
|
|
3918
|
-
function manyToManyRelations(models) {
|
|
3919
|
-
return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
|
|
3920
|
-
const inverse = backRelation(field, model, models);
|
|
3921
|
-
const other = models.find((m) => m.name === field.type);
|
|
3922
|
-
if (!(other && inverse?.isList)) return [];
|
|
3923
|
-
if (!(model.name === other.name ? field.name < inverse.name : model.name < other.name)) return [];
|
|
3924
|
-
return [{
|
|
3925
|
-
relationName: field.relationName ?? `${model.name}To${other.name}`,
|
|
3926
|
-
a: {
|
|
3927
|
-
model,
|
|
3928
|
-
field
|
|
3929
|
-
},
|
|
3930
|
-
b: {
|
|
3931
|
-
model: other,
|
|
3932
|
-
field: inverse
|
|
3933
|
-
}
|
|
3934
|
-
}];
|
|
3935
|
-
}));
|
|
3936
|
-
}
|
|
3937
3820
|
/**
|
|
3938
3821
|
* Reads an RFC 3339 timestamp as it may stand in `@default("...")`.
|
|
3939
3822
|
*
|
|
@@ -4102,7 +3985,7 @@ function getPrimaryKeyConfig(field) {
|
|
|
4102
3985
|
foreignKeyType: null
|
|
4103
3986
|
};
|
|
4104
3987
|
}
|
|
4105
|
-
function isNowDefault
|
|
3988
|
+
function isNowDefault(field) {
|
|
4106
3989
|
const def = field.default;
|
|
4107
3990
|
return typeof def === "object" && def !== null && "name" in def && def.name === "now";
|
|
4108
3991
|
}
|
|
@@ -4142,7 +4025,7 @@ function makeTimestampsLines(fields, appName) {
|
|
|
4142
4025
|
"created_at",
|
|
4143
4026
|
"createdAt"
|
|
4144
4027
|
]);
|
|
4145
|
-
const inserted = fields.find((f) => isStamped(f) && insertedAliases.has(f.name) && isNowDefault
|
|
4028
|
+
const inserted = fields.find((f) => isStamped(f) && insertedAliases.has(f.name) && isNowDefault(f) && !f.isUpdatedAt);
|
|
4146
4029
|
const updated = fields.filter((f) => isStamped(f) && f.isUpdatedAt);
|
|
4147
4030
|
const exclude = /* @__PURE__ */ new Set([...inserted ? [inserted.name] : [], ...updated.map((f) => f.name)]);
|
|
4148
4031
|
const named = (field, ecto) => fields.some((f) => f !== field && makeSnakeCase(f.name) === ecto) ? makeSnakeCase(field.name) : ecto;
|
|
@@ -4210,49 +4093,45 @@ function getAssociations$4(model, allModels, appName) {
|
|
|
4210
4093
|
const hasMany = [];
|
|
4211
4094
|
const hasOne = [];
|
|
4212
4095
|
const manyToMany = [];
|
|
4213
|
-
for (const
|
|
4214
|
-
|
|
4215
|
-
|
|
4216
|
-
|
|
4096
|
+
for (const end of relationEnds(model, allModels)) {
|
|
4097
|
+
const { field } = end;
|
|
4098
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
4099
|
+
if (end.kind === "belongsTo") {
|
|
4100
|
+
const fromFields = field.relationFromFields ?? [];
|
|
4101
|
+
if (fromFields.length > 1) continue;
|
|
4217
4102
|
belongsTo.push({
|
|
4218
4103
|
name: field.name,
|
|
4219
4104
|
targetModel: field.type,
|
|
4220
|
-
foreignKey:
|
|
4105
|
+
foreignKey: fromFields[0],
|
|
4221
4106
|
fkType: getBelongsToFkType(allModels, field.type, field.relationToFields?.[0], appName),
|
|
4222
|
-
references: ectoFieldName(
|
|
4107
|
+
references: ectoFieldName(targetModel, field.relationToFields?.[0] ?? "id")
|
|
4223
4108
|
});
|
|
4224
4109
|
continue;
|
|
4225
4110
|
}
|
|
4226
|
-
const targetModel = allModels.find((m) => m.name === field.type);
|
|
4227
4111
|
if (!targetModel) continue;
|
|
4228
|
-
if (
|
|
4229
|
-
const
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
|
|
4238
|
-
|
|
4239
|
-
|
|
4240
|
-
relatedKey: ectoFieldName(targetModel, targetModel.fields.find((f) => f.isId)?.name ?? "id")
|
|
4241
|
-
});
|
|
4242
|
-
continue;
|
|
4243
|
-
}
|
|
4112
|
+
if (end.kind === "manyToMany") {
|
|
4113
|
+
const [left, right] = end.isSideA ? [model.name, field.type] : [field.type, model.name];
|
|
4114
|
+
manyToMany.push({
|
|
4115
|
+
name: field.name,
|
|
4116
|
+
targetModel: field.type,
|
|
4117
|
+
joinThrough: `_${field.relationName ?? `${left}To${right}`}`,
|
|
4118
|
+
ownJoinColumn: end.isSideA ? "A" : "B",
|
|
4119
|
+
ownKey: ectoFieldName(model, model.fields.find((f) => f.isId)?.name ?? "id"),
|
|
4120
|
+
relatedJoinColumn: end.isSideA ? "B" : "A",
|
|
4121
|
+
relatedKey: ectoFieldName(targetModel, targetModel.fields.find((f) => f.isId)?.name ?? "id")
|
|
4122
|
+
});
|
|
4123
|
+
continue;
|
|
4244
4124
|
}
|
|
4245
|
-
const fkField =
|
|
4246
|
-
const
|
|
4247
|
-
if (
|
|
4248
|
-
if ((fkField?.relationFromFields?.length ?? 0) > 1) continue;
|
|
4125
|
+
const fkField = end.inverse;
|
|
4126
|
+
const fromFields = fkField.relationFromFields ?? [];
|
|
4127
|
+
if (fromFields.length > 1) continue;
|
|
4249
4128
|
const association = {
|
|
4250
4129
|
name: field.name,
|
|
4251
4130
|
targetModel: field.type,
|
|
4252
|
-
foreignKey,
|
|
4253
|
-
references: ectoFieldName(model, fkField
|
|
4131
|
+
foreignKey: fromFields[0],
|
|
4132
|
+
references: ectoFieldName(model, fkField.relationToFields?.[0] ?? "id")
|
|
4254
4133
|
};
|
|
4255
|
-
if (
|
|
4134
|
+
if (end.kind === "hasMany") hasMany.push(association);
|
|
4256
4135
|
else hasOne.push(association);
|
|
4257
4136
|
}
|
|
4258
4137
|
return {
|
|
@@ -4270,6 +4149,7 @@ function ectoDefaultOption(f) {
|
|
|
4270
4149
|
if (def.name === "now") return "autogenerate: true";
|
|
4271
4150
|
if (def.name === "dbgenerated") return "read_after_writes: true";
|
|
4272
4151
|
if (def.name === "uuid") return def.args[0] === 7 ? "autogenerate: {Ecto.UUID, :generate, [[version: 7]]}" : "autogenerate: {Ecto.UUID, :generate, []}";
|
|
4152
|
+
if (def.name === "ulid") return "autogenerate: {Ecto.ULID, :generate, []}";
|
|
4273
4153
|
return null;
|
|
4274
4154
|
}
|
|
4275
4155
|
if (typeof def === "string") {
|
|
@@ -4366,8 +4246,8 @@ function foreignKeyOf(model, field, allModels) {
|
|
|
4366
4246
|
holder: field
|
|
4367
4247
|
};
|
|
4368
4248
|
const other = allModels.find((m) => m.name === field.type);
|
|
4369
|
-
const holder =
|
|
4370
|
-
return other && holder ? {
|
|
4249
|
+
const holder = backRelation(field, model, allModels);
|
|
4250
|
+
return other && holder && (holder.relationFromFields?.length ?? 0) > 0 ? {
|
|
4371
4251
|
side: "inverse",
|
|
4372
4252
|
owner: other,
|
|
4373
4253
|
holder
|
|
@@ -4919,8 +4799,7 @@ function relationMode(source) {
|
|
|
4919
4799
|
//#region src/core/ecto.ts
|
|
4920
4800
|
function ecto(options) {
|
|
4921
4801
|
return Effect.gen(function* () {
|
|
4922
|
-
|
|
4923
|
-
const outDir = options.generator.output.value;
|
|
4802
|
+
const output = yield* requireOutput(options, "Hekireki-Ecto");
|
|
4924
4803
|
const problems = ectoProblems(options.dmmf.datamodel.models);
|
|
4925
4804
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Ecto cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
4926
4805
|
const app = options.generator.config?.app ?? "MyApp";
|
|
@@ -4931,7 +4810,7 @@ function ecto(options) {
|
|
|
4931
4810
|
foreignKeyNames: relationMaps(options.datamodel),
|
|
4932
4811
|
relationMode: relationMode(options.datamodel)
|
|
4933
4812
|
});
|
|
4934
|
-
return yield* emitMany(files,
|
|
4813
|
+
return yield* emitMany(files, output);
|
|
4935
4814
|
});
|
|
4936
4815
|
}
|
|
4937
4816
|
//#endregion
|
|
@@ -5422,7 +5301,7 @@ function generatorKey(generator) {
|
|
|
5422
5301
|
return `Nanoid${generator.size}Generator`;
|
|
5423
5302
|
}
|
|
5424
5303
|
function valueGeneratorOf(field, clr) {
|
|
5425
|
-
if (!isFunctionDefault
|
|
5304
|
+
if (!isFunctionDefault(field.default) || field.isList) return null;
|
|
5426
5305
|
const isGuid = clr.clr === typeRef$1(CS.Guid);
|
|
5427
5306
|
const isString = clr.clr === "string";
|
|
5428
5307
|
const [arg] = field.default.args;
|
|
@@ -5517,7 +5396,7 @@ function literal$1(value, field, clr, names, enums) {
|
|
|
5517
5396
|
function defaultPlan$1(field, clr, names, enums) {
|
|
5518
5397
|
const def = field.default;
|
|
5519
5398
|
if (def === void 0 || def === null) return null;
|
|
5520
|
-
if (isFunctionDefault
|
|
5399
|
+
if (isFunctionDefault(def)) {
|
|
5521
5400
|
const [arg] = def.args;
|
|
5522
5401
|
if (def.name === "autoincrement") return { kind: "autoincrement" };
|
|
5523
5402
|
if (def.name === "dbgenerated") return typeof arg === "string" && arg.length > 0 ? {
|
|
@@ -6180,7 +6059,7 @@ function efcoreFiles(datamodel, options) {
|
|
|
6180
6059
|
//#region src/core/efcore.ts
|
|
6181
6060
|
function efcore(options) {
|
|
6182
6061
|
return Effect.gen(function* () {
|
|
6183
|
-
|
|
6062
|
+
const output = yield* requireOutput(options, "Hekireki-EFCore");
|
|
6184
6063
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
6185
6064
|
if (provider !== "postgresql" && provider !== "mysql" && provider !== "sqlite") return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-EFCore: ${provider}. Supported providers are postgresql, mysql and sqlite.` });
|
|
6186
6065
|
const namespace = getString(options.generator.config?.namespace) ?? "Models";
|
|
@@ -6192,7 +6071,7 @@ function efcore(options) {
|
|
|
6192
6071
|
context,
|
|
6193
6072
|
provider
|
|
6194
6073
|
});
|
|
6195
|
-
return yield* emitMany(files,
|
|
6074
|
+
return yield* emitMany(files, output);
|
|
6196
6075
|
});
|
|
6197
6076
|
}
|
|
6198
6077
|
//#endregion
|
|
@@ -6203,10 +6082,8 @@ function makeEffectInfer(modelName) {
|
|
|
6203
6082
|
function makeEffectSchema(modelName, fields) {
|
|
6204
6083
|
return `export const ${modelName}Schema = Schema.Struct({\n${fields}\n})`;
|
|
6205
6084
|
}
|
|
6206
|
-
function makeEffectProperties(fields
|
|
6207
|
-
return fields.map((field) => {
|
|
6208
|
-
return `${comment ? makeCommentBlock(field.comment, 2) : ""} ${field.fieldName}: ${field.validation ?? "Schema.Unknown"},`;
|
|
6209
|
-
}).join("\n");
|
|
6085
|
+
function makeEffectProperties(fields) {
|
|
6086
|
+
return fields.map((field) => ` ${field.fieldName}: ${field.validation ?? "Schema.Unknown"},`).join("\n");
|
|
6210
6087
|
}
|
|
6211
6088
|
function makeEffectEnumExpression(values) {
|
|
6212
6089
|
return `Schema.Literal(${values.map((v) => `'${v}'`).join(", ")})`;
|
|
@@ -6222,8 +6099,8 @@ const PRISMA_TO_EFFECT = {
|
|
|
6222
6099
|
Json: "Schema.Unknown",
|
|
6223
6100
|
Bytes: "Schema.Unknown"
|
|
6224
6101
|
};
|
|
6225
|
-
function makeEffectSchemas(modelFields
|
|
6226
|
-
return schemaFromFields(modelFields,
|
|
6102
|
+
function makeEffectSchemas(modelFields) {
|
|
6103
|
+
return schemaFromFields(modelFields, makeEffectSchema, makeEffectProperties);
|
|
6227
6104
|
}
|
|
6228
6105
|
function makeEffectRelations(model, relProps, options) {
|
|
6229
6106
|
if (relProps.length === 0) return null;
|
|
@@ -6232,11 +6109,10 @@ function makeEffectRelations(model, relProps, options) {
|
|
|
6232
6109
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = typeof ${model.name}RelationsSchema.Type` : "";
|
|
6233
6110
|
return `export const ${model.name}RelationsSchema = Schema.Struct({${base}${rels}})${typeLine}`;
|
|
6234
6111
|
}
|
|
6235
|
-
function effectSchemaCode(models, type,
|
|
6236
|
-
return validationSchemas(models, type,
|
|
6112
|
+
function effectSchemaCode(models, type, enums) {
|
|
6113
|
+
return validationSchemas(models, type, {
|
|
6237
6114
|
importStatement: `import { Schema } from 'effect'`,
|
|
6238
6115
|
annotationPrefix: "@e.",
|
|
6239
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
6240
6116
|
extractValidation: makeValidationExtractor("@e."),
|
|
6241
6117
|
inferType: makeEffectInfer,
|
|
6242
6118
|
schemas: makeEffectSchemas,
|
|
@@ -6247,23 +6123,15 @@ function effectSchemaCode(models, type, comment, enums) {
|
|
|
6247
6123
|
}
|
|
6248
6124
|
//#endregion
|
|
6249
6125
|
//#region src/generator/effect.ts
|
|
6250
|
-
function effectCode(dmmf, type,
|
|
6251
|
-
return [effectSchemaCode(dmmf.datamodel.models, type,
|
|
6126
|
+
function effectCode(dmmf, type, relation) {
|
|
6127
|
+
return [effectSchemaCode(dmmf.datamodel.models, type, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeEffectRelations) : ""].filter(Boolean).join("\n\n");
|
|
6252
6128
|
}
|
|
6253
6129
|
//#endregion
|
|
6254
6130
|
//#region src/core/effect.ts
|
|
6255
6131
|
function effect(options) {
|
|
6256
6132
|
return Effect.gen(function* () {
|
|
6257
|
-
|
|
6258
|
-
const
|
|
6259
|
-
const resolved = path.extname(output) ? {
|
|
6260
|
-
dir: path.dirname(output),
|
|
6261
|
-
file: output
|
|
6262
|
-
} : {
|
|
6263
|
-
dir: output,
|
|
6264
|
-
file: path.join(output, "index.ts")
|
|
6265
|
-
};
|
|
6266
|
-
const code = effectCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation));
|
|
6133
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Effect"), "index.ts");
|
|
6134
|
+
const code = effectCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
6267
6135
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
6268
6136
|
});
|
|
6269
6137
|
}
|
|
@@ -6395,47 +6263,42 @@ function getAssociations$3(model, allModels) {
|
|
|
6395
6263
|
const belongsToMany = [];
|
|
6396
6264
|
const ownKeyColumns = modelKey$1(model).columns;
|
|
6397
6265
|
const ownKey = ownKeyColumns.length === 1 ? ownKeyColumns[0] : null;
|
|
6398
|
-
for (const
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
if (
|
|
6402
|
-
const
|
|
6266
|
+
for (const end of relationEnds(model, allModels)) {
|
|
6267
|
+
const { field } = end;
|
|
6268
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
6269
|
+
if (end.kind === "belongsTo") {
|
|
6270
|
+
const fromFields = field.relationFromFields ?? [];
|
|
6271
|
+
if (fromFields.length > 1) continue;
|
|
6403
6272
|
const referencedField = field.relationToFields?.[0] ?? "id";
|
|
6404
6273
|
const ownerKeyColumn = targetModel ? fieldColumn(targetModel, referencedField) : referencedField;
|
|
6405
6274
|
const targetKey = targetModel ? modelKey$1(targetModel).columns : ["id"];
|
|
6406
6275
|
belongsTo.push({
|
|
6407
6276
|
name: field.name,
|
|
6408
6277
|
targetModel: field.type,
|
|
6409
|
-
foreignKeyColumn: fieldColumn(model,
|
|
6278
|
+
foreignKeyColumn: fieldColumn(model, fromFields[0]),
|
|
6410
6279
|
ownerKeyColumn: targetKey.length === 1 && targetKey[0] === ownerKeyColumn ? null : ownerKeyColumn
|
|
6411
6280
|
});
|
|
6412
6281
|
continue;
|
|
6413
6282
|
}
|
|
6414
|
-
const targetModel = allModels.find((m) => m.name === field.type);
|
|
6415
6283
|
if (!targetModel) continue;
|
|
6416
|
-
if (
|
|
6417
|
-
const
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
|
|
6425
|
-
|
|
6426
|
-
relatedPivotKey: ownIsA ? "B" : "A"
|
|
6427
|
-
});
|
|
6428
|
-
continue;
|
|
6429
|
-
}
|
|
6284
|
+
if (end.kind === "manyToMany") {
|
|
6285
|
+
const [left, right] = end.isSideA ? [model.name, field.type] : [field.type, model.name];
|
|
6286
|
+
belongsToMany.push({
|
|
6287
|
+
name: field.name,
|
|
6288
|
+
targetModel: field.type,
|
|
6289
|
+
joinTable: `_${field.relationName ?? `${left}To${right}`}`,
|
|
6290
|
+
foreignPivotKey: end.isSideA ? "A" : "B",
|
|
6291
|
+
relatedPivotKey: end.isSideA ? "B" : "A"
|
|
6292
|
+
});
|
|
6293
|
+
continue;
|
|
6430
6294
|
}
|
|
6431
|
-
const fkField =
|
|
6432
|
-
|
|
6433
|
-
|
|
6434
|
-
|
|
6435
|
-
const
|
|
6436
|
-
const referencedColumn = fieldColumn(model, fkField?.relationToFields?.[0] ?? "id");
|
|
6295
|
+
const fkField = end.inverse;
|
|
6296
|
+
const fromFields = fkField.relationFromFields ?? [];
|
|
6297
|
+
if (fromFields.length > 1) continue;
|
|
6298
|
+
const foreignKeyColumn = fieldColumn(targetModel, fromFields[0]);
|
|
6299
|
+
const referencedColumn = fieldColumn(model, fkField.relationToFields?.[0] ?? "id");
|
|
6437
6300
|
const localKeyColumn = referencedColumn === ownKey ? null : referencedColumn;
|
|
6438
|
-
if (
|
|
6301
|
+
if (end.kind === "hasMany") hasMany.push({
|
|
6439
6302
|
name: field.name,
|
|
6440
6303
|
targetModel: field.type,
|
|
6441
6304
|
foreignKeyColumn,
|
|
@@ -7433,14 +7296,13 @@ function eloquentModelFiles(models, namespace, enums, options = {}) {
|
|
|
7433
7296
|
//#region src/core/eloquent.ts
|
|
7434
7297
|
function eloquent(options) {
|
|
7435
7298
|
return Effect.gen(function* () {
|
|
7436
|
-
|
|
7437
|
-
const outDir = options.generator.output.value;
|
|
7299
|
+
const output = yield* requireOutput(options, "Hekireki-Eloquent");
|
|
7438
7300
|
const problems = eloquentProblems(options.dmmf.datamodel.models, options.dmmf.datamodel.enums);
|
|
7439
7301
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Eloquent cannot write this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
7440
7302
|
const namespace = options.generator.config?.namespace ?? "App\\Models";
|
|
7441
7303
|
const enums = options.dmmf.datamodel.enums;
|
|
7442
7304
|
const files = eloquentModelFiles(options.dmmf.datamodel.models, namespace, enums, { provider: options.datasources[0]?.activeProvider });
|
|
7443
|
-
return yield* emitMany(files,
|
|
7305
|
+
return yield* emitMany(files, output);
|
|
7444
7306
|
});
|
|
7445
7307
|
}
|
|
7446
7308
|
//#endregion
|
|
@@ -8810,11 +8672,8 @@ function columnOf(model, field) {
|
|
|
8810
8672
|
const found = model?.fields.find((f) => f.name === field);
|
|
8811
8673
|
return found ? dbNameOf(found) : field;
|
|
8812
8674
|
}
|
|
8813
|
-
function isFunctionDefault$4(def) {
|
|
8814
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
8815
|
-
}
|
|
8816
8675
|
function toDBMLColumn(field, enums) {
|
|
8817
|
-
const defaultName = isFunctionDefault
|
|
8676
|
+
const defaultName = isFunctionDefault(field.default) ? field.default.name : void 0;
|
|
8818
8677
|
const enumDef = field.kind === "enum" ? enums.find((e) => e.name === field.type) : void 0;
|
|
8819
8678
|
const baseType = enumDef ? dbNameOf(enumDef) : field.type;
|
|
8820
8679
|
const type = field.isList && !field.relationName ? `${baseType}[]` : baseType;
|
|
@@ -8867,7 +8726,7 @@ function makeRelations(models) {
|
|
|
8867
8726
|
return models.flatMap((model) => model.fields.filter((field) => field.relationName && field.relationToFields?.length && field.relationFromFields?.length).map((field) => {
|
|
8868
8727
|
const relationTo = field.type;
|
|
8869
8728
|
const toModel = models.find((m) => m.name === relationTo);
|
|
8870
|
-
const operator = (
|
|
8729
|
+
const operator = backRelation(field, model, models)?.isList ? ">" : "-";
|
|
8871
8730
|
const relationFromName = dbNameOf(model);
|
|
8872
8731
|
const relationToName = toModel ? dbNameOf(toModel) : relationTo;
|
|
8873
8732
|
const fromColumn = combineKeys((field.relationFromFields ?? []).map((f) => columnOf(model, f)));
|
|
@@ -9605,9 +9464,6 @@ function foreignKeys(models, keyOf, maps) {
|
|
|
9605
9464
|
function scalarFields(model) {
|
|
9606
9465
|
return model.fields.filter((f) => f.kind === "scalar" || f.kind === "enum");
|
|
9607
9466
|
}
|
|
9608
|
-
function isSameList(left, right) {
|
|
9609
|
-
return left.length === right.length && left.every((name, index) => right[index] === name);
|
|
9610
|
-
}
|
|
9611
9467
|
function conditionSql(model, condition) {
|
|
9612
9468
|
if (condition.kind === "raw") return `(${condition.sql})`;
|
|
9613
9469
|
return `(${condition.terms.map((term) => {
|
|
@@ -9625,7 +9481,7 @@ function isKeyField(schema, model, field) {
|
|
|
9625
9481
|
return keyFieldNames(schema.keyOf(model)).includes(field);
|
|
9626
9482
|
}
|
|
9627
9483
|
function isSmallserial(field) {
|
|
9628
|
-
return isFunctionDefault
|
|
9484
|
+
return isFunctionDefault(field.default) && field.default.name === "autoincrement" && field.nativeType?.[0] === "SmallInt";
|
|
9629
9485
|
}
|
|
9630
9486
|
/**
|
|
9631
9487
|
* How the DAO follows a foreign key: through its column (`referencedOn`, `referrersOn`), through
|
|
@@ -10020,7 +9876,7 @@ function defaultPlan(plan, model, field, map) {
|
|
|
10020
9876
|
expr: nowExpr(map.temporal)
|
|
10021
9877
|
} : null;
|
|
10022
9878
|
if (def === void 0 || def === null) return updatedAt;
|
|
10023
|
-
if (isFunctionDefault
|
|
9879
|
+
if (isFunctionDefault(def)) {
|
|
10024
9880
|
const [arg] = def.args;
|
|
10025
9881
|
if (def.name === "autoincrement") return field.nativeType?.[0] === "Oid" ? null : { kind: "autoincrement" };
|
|
10026
9882
|
if (def.name === "now") return {
|
|
@@ -11301,7 +11157,7 @@ function exposedFiles(datamodel, options) {
|
|
|
11301
11157
|
//#region src/core/exposed.ts
|
|
11302
11158
|
function exposed(options) {
|
|
11303
11159
|
return Effect.gen(function* () {
|
|
11304
|
-
|
|
11160
|
+
const output = yield* requireOutput(options, "Hekireki-Exposed");
|
|
11305
11161
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
11306
11162
|
if (provider !== "postgresql") return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-Exposed: ${provider}. Supported providers are postgresql.` });
|
|
11307
11163
|
const packageName = getString(options.generator.config?.package) ?? "models";
|
|
@@ -11313,7 +11169,7 @@ function exposed(options) {
|
|
|
11313
11169
|
dao: dao === "true",
|
|
11314
11170
|
source: options.datamodel
|
|
11315
11171
|
});
|
|
11316
|
-
return yield* emitMany(files,
|
|
11172
|
+
return yield* emitMany(files, output);
|
|
11317
11173
|
});
|
|
11318
11174
|
}
|
|
11319
11175
|
//#endregion
|
|
@@ -11373,61 +11229,46 @@ function getAssociations$2(model, allModels) {
|
|
|
11373
11229
|
const hasMany = [];
|
|
11374
11230
|
const hasOne = [];
|
|
11375
11231
|
const manyToMany = [];
|
|
11376
|
-
for (const
|
|
11377
|
-
|
|
11378
|
-
if (
|
|
11232
|
+
for (const end of relationEnds(model, allModels)) {
|
|
11233
|
+
const { field } = end;
|
|
11234
|
+
if (end.kind === "belongsTo") {
|
|
11235
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
11379
11236
|
belongsTo.push({
|
|
11380
11237
|
name: field.name,
|
|
11381
11238
|
targetModel: field.type,
|
|
11382
|
-
foreignKey:
|
|
11239
|
+
foreignKey: foreignKeys[0],
|
|
11383
11240
|
references: field.relationToFields?.[0] ?? "id",
|
|
11384
|
-
foreignKeys
|
|
11241
|
+
foreignKeys,
|
|
11385
11242
|
referencesList: field.relationToFields ?? ["id"],
|
|
11386
11243
|
onDelete: field.relationOnDelete,
|
|
11387
11244
|
onUpdate: field.relationOnUpdate
|
|
11388
11245
|
});
|
|
11389
11246
|
continue;
|
|
11390
11247
|
}
|
|
11391
|
-
|
|
11392
|
-
|
|
11393
|
-
|
|
11394
|
-
|
|
11395
|
-
|
|
11396
|
-
|
|
11397
|
-
|
|
11398
|
-
|
|
11399
|
-
});
|
|
11400
|
-
continue;
|
|
11401
|
-
}
|
|
11248
|
+
if (end.kind === "manyToMany") {
|
|
11249
|
+
manyToMany.push({
|
|
11250
|
+
name: field.name,
|
|
11251
|
+
targetModel: field.type,
|
|
11252
|
+
relationName: field.relationName ?? `${model.name}To${field.type}`,
|
|
11253
|
+
isSideA: end.isSideA
|
|
11254
|
+
});
|
|
11255
|
+
continue;
|
|
11402
11256
|
}
|
|
11403
|
-
const fkField =
|
|
11404
|
-
const
|
|
11405
|
-
|
|
11406
|
-
const references = fkField?.relationToFields?.[0] ?? "id";
|
|
11407
|
-
const foreignKeys = fkField?.relationFromFields ?? [foreignKey];
|
|
11408
|
-
const referencesList = fkField?.relationToFields ?? ["id"];
|
|
11409
|
-
if (field.isList) hasMany.push({
|
|
11410
|
-
name: field.name,
|
|
11411
|
-
targetModel: field.type,
|
|
11412
|
-
foreignKey,
|
|
11413
|
-
references,
|
|
11414
|
-
foreignKeys,
|
|
11415
|
-
referencesList,
|
|
11416
|
-
isList: true,
|
|
11417
|
-
onDelete: fkField?.relationOnDelete,
|
|
11418
|
-
onUpdate: fkField?.relationOnUpdate
|
|
11419
|
-
});
|
|
11420
|
-
else hasOne.push({
|
|
11257
|
+
const fkField = end.inverse;
|
|
11258
|
+
const foreignKeys = fkField.relationFromFields ?? [];
|
|
11259
|
+
const association = {
|
|
11421
11260
|
name: field.name,
|
|
11422
11261
|
targetModel: field.type,
|
|
11423
|
-
foreignKey,
|
|
11424
|
-
references,
|
|
11262
|
+
foreignKey: foreignKeys[0],
|
|
11263
|
+
references: fkField.relationToFields?.[0] ?? "id",
|
|
11425
11264
|
foreignKeys,
|
|
11426
|
-
referencesList,
|
|
11427
|
-
isList:
|
|
11428
|
-
onDelete: fkField
|
|
11429
|
-
onUpdate: fkField
|
|
11430
|
-
}
|
|
11265
|
+
referencesList: fkField.relationToFields ?? ["id"],
|
|
11266
|
+
isList: end.kind === "hasMany",
|
|
11267
|
+
onDelete: fkField.relationOnDelete,
|
|
11268
|
+
onUpdate: fkField.relationOnUpdate
|
|
11269
|
+
};
|
|
11270
|
+
if (end.kind === "hasMany") hasMany.push(association);
|
|
11271
|
+
else hasOne.push(association);
|
|
11431
11272
|
}
|
|
11432
11273
|
return {
|
|
11433
11274
|
belongsTo,
|
|
@@ -11436,12 +11277,6 @@ function getAssociations$2(model, allModels) {
|
|
|
11436
11277
|
manyToMany
|
|
11437
11278
|
};
|
|
11438
11279
|
}
|
|
11439
|
-
function isFunctionDefault$3(def) {
|
|
11440
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
11441
|
-
}
|
|
11442
|
-
function isAutoincrement$2(field) {
|
|
11443
|
-
return isFunctionDefault$3(field.default) && field.default.name === "autoincrement";
|
|
11444
|
-
}
|
|
11445
11280
|
function formatGoDefault(def, type, kind) {
|
|
11446
11281
|
if (def === void 0 || def === null) return null;
|
|
11447
11282
|
if (typeof def === "boolean") return def ? "true" : "false";
|
|
@@ -11470,12 +11305,12 @@ function dateTimeGoType(field) {
|
|
|
11470
11305
|
}
|
|
11471
11306
|
function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider) {
|
|
11472
11307
|
const columnName = field.dbName ?? field.name;
|
|
11473
|
-
const isUuidDefault = isFunctionDefault
|
|
11474
|
-
const isUlidDefault = isFunctionDefault
|
|
11475
|
-
const isNowDefault = field.type === "DateTime" && isFunctionDefault
|
|
11308
|
+
const isUuidDefault = isFunctionDefault(field.default) && field.default.name === "uuid";
|
|
11309
|
+
const isUlidDefault = isFunctionDefault(field.default) && field.default.name === "ulid";
|
|
11310
|
+
const isNowDefault = field.type === "DateTime" && isFunctionDefault(field.default) && field.default.name === "now";
|
|
11476
11311
|
const nativeType = resolveNativeType$1(field);
|
|
11477
|
-
const includeNativeType = nativeType && (!isPk || !isFunctionDefault
|
|
11478
|
-
const dbGeneratedExpr = isFunctionDefault
|
|
11312
|
+
const includeNativeType = nativeType && (!isPk || !isFunctionDefault(field.default) || field.default.name !== "uuid");
|
|
11313
|
+
const dbGeneratedExpr = isFunctionDefault(field.default) && field.default.name === "dbgenerated" && typeof field.default.args[0] === "string" ? field.default.args[0] : null;
|
|
11479
11314
|
const enumMappedDefault = (() => {
|
|
11480
11315
|
if (!(field.kind === "enum" && typeof field.default === "string")) return null;
|
|
11481
11316
|
const value = enums?.find((e) => e.name === field.type)?.values.find((v) => v.name === field.default);
|
|
@@ -11495,7 +11330,7 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, pr
|
|
|
11495
11330
|
return `\`gorm:"${[
|
|
11496
11331
|
`column:${columnName}`,
|
|
11497
11332
|
isPk ? "primaryKey" : null,
|
|
11498
|
-
isPk && isAutoincrement
|
|
11333
|
+
isPk && isAutoincrement(field) ? "autoIncrement" : null,
|
|
11499
11334
|
isPk && isUuidDefault ? "type:char(36)" : null,
|
|
11500
11335
|
isPk && isUlidDefault ? "type:char(26)" : null,
|
|
11501
11336
|
field.isUnique ? "uniqueIndex" : null,
|
|
@@ -11586,7 +11421,7 @@ function goModelName(name) {
|
|
|
11586
11421
|
return splitGoWords(name).join("");
|
|
11587
11422
|
}
|
|
11588
11423
|
function generatedIdExpr$1(field) {
|
|
11589
|
-
if (!isFunctionDefault
|
|
11424
|
+
if (!isFunctionDefault(field.default)) return null;
|
|
11590
11425
|
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid.Must(uuid.NewV7()).String()" : "uuid.NewString()";
|
|
11591
11426
|
if (field.default.name === "ulid") return "ulid.MustNew(ulid.Now(), rand.Reader).String()";
|
|
11592
11427
|
if (field.default.name === "cuid") return field.default.args[0] === 2 ? "cuid2.Generate()" : "cuid.New()";
|
|
@@ -11608,7 +11443,7 @@ function generatedIdFields(model) {
|
|
|
11608
11443
|
*/
|
|
11609
11444
|
function createdTimeExpr(field) {
|
|
11610
11445
|
if (!isDateTimeScalar(field)) return null;
|
|
11611
|
-
if (field.isUpdatedAt || isFunctionDefault
|
|
11446
|
+
if (field.isUpdatedAt || isFunctionDefault(field.default) && field.default.name === "now") return "now";
|
|
11612
11447
|
if (typeof field.default !== "string") return null;
|
|
11613
11448
|
const at = new Date(field.default);
|
|
11614
11449
|
return `time.Date(${at.getUTCFullYear()}, ${at.getUTCMonth() + 1}, ${at.getUTCDate()}, ${at.getUTCHours()}, ${at.getUTCMinutes()}, ${at.getUTCSeconds()}, ${at.getUTCMilliseconds() * 1e6}, time.UTC)`;
|
|
@@ -11747,7 +11582,7 @@ function generateRelationFields(model, associations) {
|
|
|
11747
11582
|
});
|
|
11748
11583
|
const manyToManyLines = associations.manyToMany.map((assoc) => {
|
|
11749
11584
|
const joinTable = `_${assoc.relationName}`;
|
|
11750
|
-
const [own, related] =
|
|
11585
|
+
const [own, related] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
|
|
11751
11586
|
return [
|
|
11752
11587
|
goFieldName(assoc.name),
|
|
11753
11588
|
`[]${goModelName(assoc.targetModel)}`,
|
|
@@ -12081,7 +11916,7 @@ function collectImports(models) {
|
|
|
12081
11916
|
const lists = types.some((name) => name.endsWith("List"));
|
|
12082
11917
|
const fillsTimes = models.some((m) => m.fields.some((f) => createdTimeExpr(f) !== null || isDateTimeScalar(f) && f.isUpdatedAt));
|
|
12083
11918
|
const needsDatatypes = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "Json"));
|
|
12084
|
-
const generators = new Set(models.flatMap((m) => generatedIdFields(m).flatMap((f) => isFunctionDefault
|
|
11919
|
+
const generators = new Set(models.flatMap((m) => generatedIdFields(m).flatMap((f) => isFunctionDefault(f.default) ? [f.default.name === "cuid" && f.default.args[0] === 2 ? "cuid2" : f.default.name] : [])));
|
|
12085
11920
|
const standard = [
|
|
12086
11921
|
generators.has("ulid") ? "\"crypto/rand\"" : null,
|
|
12087
11922
|
lists ? "\"database/sql\"" : null,
|
|
@@ -12133,16 +11968,15 @@ function generateGormModels(models, enums, indexes, packageName = "model", provi
|
|
|
12133
11968
|
//#region src/core/gorm.ts
|
|
12134
11969
|
function gorm(options) {
|
|
12135
11970
|
return Effect.gen(function* () {
|
|
12136
|
-
|
|
11971
|
+
const output = yield* requireOutput(options, "Hekireki-GORM");
|
|
12137
11972
|
const problems = gormProblems(options.dmmf.datamodel.models);
|
|
12138
11973
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-GORM cannot write this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
12139
|
-
const
|
|
12140
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.go");
|
|
11974
|
+
const resolved = outputFile(output, "models.go");
|
|
12141
11975
|
const packageName = getString(options.generator.config.package) ?? "model";
|
|
12142
11976
|
const enums = options.dmmf.datamodel.enums;
|
|
12143
11977
|
const indexes = options.dmmf.datamodel.indexes;
|
|
12144
11978
|
const code = generateGormModels(options.dmmf.datamodel.models, enums, indexes, packageName, options.datasources[0]?.activeProvider);
|
|
12145
|
-
return yield* emitRaw(code,
|
|
11979
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
12146
11980
|
});
|
|
12147
11981
|
}
|
|
12148
11982
|
//#endregion
|
|
@@ -12173,11 +12007,8 @@ const CLIENT_SIDE_DEFAULTS = /* @__PURE__ */ new Set([
|
|
|
12173
12007
|
"nanoid",
|
|
12174
12008
|
"auto"
|
|
12175
12009
|
]);
|
|
12176
|
-
function isFunctionDefault$2(def) {
|
|
12177
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
12178
|
-
}
|
|
12179
12010
|
function isDbGenerated(field, provider = "postgresql") {
|
|
12180
|
-
return field.hasDefaultValue && !(isFunctionDefault
|
|
12011
|
+
return field.hasDefaultValue && !(isFunctionDefault(field.default) && CLIENT_SIDE_DEFAULTS.has(field.default.name)) && !(provider === "sqlite" && field.type === "DateTime");
|
|
12181
12012
|
}
|
|
12182
12013
|
function makeStringLiteral(value) {
|
|
12183
12014
|
return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
|
@@ -12200,30 +12031,12 @@ function makeEnumDeclarations(models, enums) {
|
|
|
12200
12031
|
const usedEnumNames = new Set(models.flatMap((m) => m.fields.filter((f) => f.kind === "enum").map((f) => f.type)));
|
|
12201
12032
|
return enums.filter((e) => usedEnumNames.has(e.name)).map((e) => `export type ${e.name} = ${e.values.map((v) => makeStringLiteral(v.dbName ?? v.name)).join(" | ")}`);
|
|
12202
12033
|
}
|
|
12203
|
-
function isImplicitM2M(field, models) {
|
|
12204
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
12205
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
12206
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
12207
|
-
}
|
|
12208
12034
|
function pkTsType(modelName, models, scalarTypes) {
|
|
12209
12035
|
const pkField = models.find((m) => m.name === modelName)?.fields.find((f) => f.isId);
|
|
12210
12036
|
return pkField ? scalarTypes[pkField.type] ?? "unknown" : "string";
|
|
12211
12037
|
}
|
|
12212
12038
|
function collectM2MJoinEntries(models, scalarTypes) {
|
|
12213
|
-
|
|
12214
|
-
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
12215
|
-
return {
|
|
12216
|
-
left,
|
|
12217
|
-
right,
|
|
12218
|
-
relationName: field.relationName ?? `${left}To${right}`
|
|
12219
|
-
};
|
|
12220
|
-
}));
|
|
12221
|
-
const seen = /* @__PURE__ */ new Set();
|
|
12222
|
-
return pairs.filter((pair) => {
|
|
12223
|
-
if (seen.has(pair.relationName)) return false;
|
|
12224
|
-
seen.add(pair.relationName);
|
|
12225
|
-
return true;
|
|
12226
|
-
}).map((pair) => ({
|
|
12039
|
+
return implicitJoinTables(models).map((pair) => ({
|
|
12227
12040
|
interfaceName: makePascalCase(makeSnakeCase(pair.relationName)),
|
|
12228
12041
|
tableName: `_${pair.relationName}`,
|
|
12229
12042
|
aType: pkTsType(pair.left, models, scalarTypes),
|
|
@@ -12269,15 +12082,7 @@ function kyselySchema(datamodel, provider = "postgresql") {
|
|
|
12269
12082
|
//#region src/core/kysely.ts
|
|
12270
12083
|
function kysely(options) {
|
|
12271
12084
|
return Effect.gen(function* () {
|
|
12272
|
-
|
|
12273
|
-
const output = options.generator.output.value;
|
|
12274
|
-
const resolved = path.extname(output) ? {
|
|
12275
|
-
dir: path.dirname(output),
|
|
12276
|
-
file: output
|
|
12277
|
-
} : {
|
|
12278
|
-
dir: output,
|
|
12279
|
-
file: path.join(output, "types.ts")
|
|
12280
|
-
};
|
|
12085
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Kysely"), "types.ts");
|
|
12281
12086
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
12282
12087
|
return yield* emit(kyselySchema(options.dmmf.datamodel, provider), resolved.dir, resolved.file);
|
|
12283
12088
|
});
|
|
@@ -12492,11 +12297,9 @@ function pydanticCode(models, enums, relation = false) {
|
|
|
12492
12297
|
//#region src/core/pydantic.ts
|
|
12493
12298
|
function pydantic(options) {
|
|
12494
12299
|
return Effect.gen(function* () {
|
|
12495
|
-
|
|
12496
|
-
const output = options.generator.output.value;
|
|
12497
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
12300
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Pydantic"), "models.py");
|
|
12498
12301
|
const code = pydanticCode(options.dmmf.datamodel.models, options.dmmf.datamodel.enums, getBool(options.generator.config?.relation));
|
|
12499
|
-
return yield* emitRaw(code,
|
|
12302
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
12500
12303
|
});
|
|
12501
12304
|
}
|
|
12502
12305
|
//#endregion
|
|
@@ -12654,14 +12457,8 @@ function resolveSeaOrmColumnType(field) {
|
|
|
12654
12457
|
default: return null;
|
|
12655
12458
|
}
|
|
12656
12459
|
}
|
|
12657
|
-
function isFunctionDefault$1(def) {
|
|
12658
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
12659
|
-
}
|
|
12660
|
-
function isAutoincrement$1(field) {
|
|
12661
|
-
return isFunctionDefault$1(field.default) && field.default.name === "autoincrement";
|
|
12662
|
-
}
|
|
12663
12460
|
function generatedIdExpr(field) {
|
|
12664
|
-
if (!isFunctionDefault
|
|
12461
|
+
if (!isFunctionDefault(field.default)) return null;
|
|
12665
12462
|
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid::Uuid::now_v7().to_string()" : "uuid::Uuid::new_v4().to_string()";
|
|
12666
12463
|
if (field.default.name === "ulid") return "ulid::Ulid::generate().to_string()";
|
|
12667
12464
|
return null;
|
|
@@ -12737,7 +12534,7 @@ function buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums)
|
|
|
12737
12534
|
const attrs = [];
|
|
12738
12535
|
if (isPk) {
|
|
12739
12536
|
const parts = ["primary_key"];
|
|
12740
|
-
if (!isAutoincrement
|
|
12537
|
+
if (!isAutoincrement(field)) parts.push("auto_increment = false");
|
|
12741
12538
|
attrs.push(seaOrmAttribute(" ", parts));
|
|
12742
12539
|
}
|
|
12743
12540
|
if (field.isUnique) attrs.push(" #[sea_orm(unique)]");
|
|
@@ -12758,51 +12555,40 @@ function getAssociations$1(model, allModels) {
|
|
|
12758
12555
|
const hasMany = [];
|
|
12759
12556
|
const hasOne = [];
|
|
12760
12557
|
const manyToMany = [];
|
|
12761
|
-
for (const
|
|
12762
|
-
|
|
12763
|
-
if (
|
|
12558
|
+
for (const end of relationEnds(model, allModels)) {
|
|
12559
|
+
const { field } = end;
|
|
12560
|
+
if (end.kind === "belongsTo") {
|
|
12561
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
12764
12562
|
belongsTo.push({
|
|
12765
12563
|
name: field.name,
|
|
12766
12564
|
targetModel: field.type,
|
|
12767
|
-
foreignKey:
|
|
12565
|
+
foreignKey: foreignKeys[0],
|
|
12768
12566
|
references: field.relationToFields?.[0] ?? "id",
|
|
12769
|
-
foreignKeys
|
|
12567
|
+
foreignKeys,
|
|
12770
12568
|
referencesList: field.relationToFields ?? ["id"],
|
|
12771
12569
|
onDelete: field.relationOnDelete,
|
|
12772
12570
|
onUpdate: field.relationOnUpdate
|
|
12773
12571
|
});
|
|
12774
12572
|
continue;
|
|
12775
12573
|
}
|
|
12776
|
-
|
|
12777
|
-
|
|
12778
|
-
|
|
12779
|
-
|
|
12780
|
-
|
|
12781
|
-
|
|
12782
|
-
|
|
12783
|
-
|
|
12784
|
-
});
|
|
12785
|
-
continue;
|
|
12786
|
-
}
|
|
12574
|
+
if (end.kind === "manyToMany") {
|
|
12575
|
+
manyToMany.push({
|
|
12576
|
+
name: field.name,
|
|
12577
|
+
targetModel: field.type,
|
|
12578
|
+
relationName: field.relationName ?? `${model.name}To${field.type}`,
|
|
12579
|
+
isSideA: end.isSideA
|
|
12580
|
+
});
|
|
12581
|
+
continue;
|
|
12787
12582
|
}
|
|
12788
|
-
const
|
|
12789
|
-
const foreignKey = fkField?.relationFromFields?.[0];
|
|
12790
|
-
if (!foreignKey) continue;
|
|
12791
|
-
const references = fkField?.relationToFields?.[0] ?? "id";
|
|
12792
|
-
if (field.isList) hasMany.push({
|
|
12793
|
-
name: field.name,
|
|
12794
|
-
targetModel: field.type,
|
|
12795
|
-
foreignKey,
|
|
12796
|
-
references,
|
|
12797
|
-
isList: true
|
|
12798
|
-
});
|
|
12799
|
-
else hasOne.push({
|
|
12583
|
+
const association = {
|
|
12800
12584
|
name: field.name,
|
|
12801
12585
|
targetModel: field.type,
|
|
12802
|
-
foreignKey,
|
|
12803
|
-
references,
|
|
12804
|
-
isList:
|
|
12805
|
-
}
|
|
12586
|
+
foreignKey: (end.inverse.relationFromFields ?? [])[0],
|
|
12587
|
+
references: end.inverse.relationToFields?.[0] ?? "id",
|
|
12588
|
+
isList: end.kind === "hasMany"
|
|
12589
|
+
};
|
|
12590
|
+
if (end.kind === "hasMany") hasMany.push(association);
|
|
12591
|
+
else hasOne.push(association);
|
|
12806
12592
|
}
|
|
12807
12593
|
return {
|
|
12808
12594
|
belongsTo,
|
|
@@ -12925,6 +12711,26 @@ function generateRelatedImpls(model, associations) {
|
|
|
12925
12711
|
].join("\n"));
|
|
12926
12712
|
}
|
|
12927
12713
|
for (const assoc of associations.manyToMany) {
|
|
12714
|
+
if (assoc.targetModel === model.name) {
|
|
12715
|
+
const junctionModule = makeSnakeCase(assoc.relationName);
|
|
12716
|
+
const [own, other] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
|
|
12717
|
+
impls.push([
|
|
12718
|
+
`pub struct ${toPascalCase(assoc.name)}Link;`,
|
|
12719
|
+
"",
|
|
12720
|
+
`impl Linked for ${toPascalCase(assoc.name)}Link {`,
|
|
12721
|
+
" type FromEntity = Entity;",
|
|
12722
|
+
" type ToEntity = Entity;",
|
|
12723
|
+
"",
|
|
12724
|
+
" fn link(&self) -> Vec<RelationDef> {",
|
|
12725
|
+
" vec![",
|
|
12726
|
+
` super::${junctionModule}::Relation::${own}.def().rev(),`,
|
|
12727
|
+
` super::${junctionModule}::Relation::${other}.def(),`,
|
|
12728
|
+
" ]",
|
|
12729
|
+
" }",
|
|
12730
|
+
"}"
|
|
12731
|
+
].join("\n"));
|
|
12732
|
+
continue;
|
|
12733
|
+
}
|
|
12928
12734
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
12929
12735
|
emittedTargets.add(assoc.targetModel);
|
|
12930
12736
|
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
@@ -12967,7 +12773,7 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
|
|
|
12967
12773
|
fieldLines.push(...attrs, rustField(fieldName, rustType));
|
|
12968
12774
|
if (field.type !== "DateTime" || field.isList) continue;
|
|
12969
12775
|
const form = DATE_TIME_FORMS[elemType] ?? DATE_TIME_FORMS.DateTime;
|
|
12970
|
-
const value = field.isUpdatedAt || isFunctionDefault
|
|
12776
|
+
const value = field.isUpdatedAt || isFunctionDefault(field.default) && field.default.name === "now" ? `now${form.fromUtc}` : typeof field.default === "string" ? `"${new Date(field.default).toISOString().slice(...form.text)}".parse().unwrap()` : null;
|
|
12971
12777
|
if (value === null) continue;
|
|
12972
12778
|
stampsNow ||= value.startsWith("now");
|
|
12973
12779
|
stampsOnInsert ||= !field.isUpdatedAt;
|
|
@@ -13060,12 +12866,17 @@ function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde
|
|
|
13060
12866
|
const tableName = `_${relationName}`;
|
|
13061
12867
|
const leftModule = makeSnakeCase(sortedLeft);
|
|
13062
12868
|
const rightModule = makeSnakeCase(sortedRight);
|
|
13063
|
-
const
|
|
13064
|
-
const
|
|
13065
|
-
const
|
|
13066
|
-
const
|
|
12869
|
+
const isSelf = sortedLeft === sortedRight;
|
|
12870
|
+
const leftFk = isSelf ? "a" : `${makeSnakeCase(sortedLeft)}_id`;
|
|
12871
|
+
const rightFk = isSelf ? "b" : `${makeSnakeCase(sortedRight)}_id`;
|
|
12872
|
+
const leftCol = isSelf ? "A" : toPascalCase(`${makeSnakeCase(sortedLeft)}Id`);
|
|
12873
|
+
const rightCol = isSelf ? "B" : toPascalCase(`${makeSnakeCase(sortedRight)}Id`);
|
|
12874
|
+
const leftVariant = isSelf ? "A" : sortedLeft;
|
|
12875
|
+
const rightVariant = isSelf ? "B" : sortedRight;
|
|
13067
12876
|
const leftType = pkRustType(sortedLeft, allModels);
|
|
13068
12877
|
const rightType = pkRustType(sortedRight, allModels);
|
|
12878
|
+
const leftKey = toPascalCase(allModels.find((m) => m.name === sortedLeft)?.fields.find((f) => f.isId)?.name ?? "id");
|
|
12879
|
+
const rightKey = toPascalCase(allModels.find((m) => m.name === sortedRight)?.fields.find((f) => f.isId)?.name ?? "id");
|
|
13069
12880
|
const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
|
|
13070
12881
|
const deriveModel = "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]";
|
|
13071
12882
|
const serdeAttrs = buildSerdeAttributes(serde);
|
|
@@ -13087,15 +12898,15 @@ function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde
|
|
|
13087
12898
|
" #[sea_orm(",
|
|
13088
12899
|
` belongs_to = "super::${leftModule}::Entity",`,
|
|
13089
12900
|
` from = "Column::${leftCol}",`,
|
|
13090
|
-
` to = "super::${leftModule}::Column
|
|
12901
|
+
` to = "super::${leftModule}::Column::${leftKey}"`,
|
|
13091
12902
|
" )]",
|
|
13092
|
-
` ${
|
|
12903
|
+
` ${leftVariant},`,
|
|
13093
12904
|
" #[sea_orm(",
|
|
13094
12905
|
` belongs_to = "super::${rightModule}::Entity",`,
|
|
13095
12906
|
` from = "Column::${rightCol}",`,
|
|
13096
|
-
` to = "super::${rightModule}::Column
|
|
12907
|
+
` to = "super::${rightModule}::Column::${rightKey}"`,
|
|
13097
12908
|
" )]",
|
|
13098
|
-
` ${
|
|
12909
|
+
` ${rightVariant},`,
|
|
13099
12910
|
"}",
|
|
13100
12911
|
"",
|
|
13101
12912
|
"impl ActiveModelBehavior for ActiveModel {}",
|
|
@@ -13263,8 +13074,7 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
|
|
|
13263
13074
|
//#region src/core/sea-orm.ts
|
|
13264
13075
|
function seaOrm(options) {
|
|
13265
13076
|
return Effect.gen(function* () {
|
|
13266
|
-
|
|
13267
|
-
const outDir = options.generator.output.value;
|
|
13077
|
+
const output = yield* requireOutput(options, "Hekireki-SeaORM");
|
|
13268
13078
|
const serde = { renameAll: getString(options.generator.config?.renameAll) };
|
|
13269
13079
|
const enums = options.dmmf.datamodel.enums;
|
|
13270
13080
|
const models = options.dmmf.datamodel.models;
|
|
@@ -13272,7 +13082,7 @@ function seaOrm(options) {
|
|
|
13272
13082
|
if (timetz.length > 0) return yield* new GeneratorConfigError({ message: `@db.Timetz is not supported by Hekireki-SeaORM (sqlx cannot read TIMETZ into a Rust type): ${timetz.join(", ")}. Use @db.Time or @db.Timestamptz instead.` });
|
|
13273
13083
|
const provider = options.datasources[0]?.activeProvider;
|
|
13274
13084
|
const files = seaOrmFiles(models, enums, serde, provider);
|
|
13275
|
-
return yield* emitMany(files,
|
|
13085
|
+
return yield* emitMany(files, output);
|
|
13276
13086
|
});
|
|
13277
13087
|
}
|
|
13278
13088
|
//#endregion
|
|
@@ -13333,15 +13143,7 @@ export const schema = defineSchema({
|
|
|
13333
13143
|
*/
|
|
13334
13144
|
function seed(options) {
|
|
13335
13145
|
return Effect.gen(function* () {
|
|
13336
|
-
|
|
13337
|
-
const output = options.generator.output.value;
|
|
13338
|
-
const resolved = path.extname(output) ? {
|
|
13339
|
-
dir: path.dirname(output),
|
|
13340
|
-
file: output
|
|
13341
|
-
} : {
|
|
13342
|
-
dir: output,
|
|
13343
|
-
file: path.join(output, "schema.ts")
|
|
13344
|
-
};
|
|
13146
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Seed"), "schema.ts");
|
|
13345
13147
|
return yield* emit(seedSchemaCode(options.dmmf.datamodel), resolved.dir, resolved.file);
|
|
13346
13148
|
});
|
|
13347
13149
|
}
|
|
@@ -13566,15 +13368,16 @@ function getAssociations(model, allModels) {
|
|
|
13566
13368
|
const hasMany = [];
|
|
13567
13369
|
const hasOne = [];
|
|
13568
13370
|
const manyToMany = [];
|
|
13569
|
-
for (const
|
|
13570
|
-
|
|
13571
|
-
if (
|
|
13371
|
+
for (const end of relationEnds(model, allModels)) {
|
|
13372
|
+
const { field } = end;
|
|
13373
|
+
if (end.kind === "belongsTo") {
|
|
13374
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
13572
13375
|
belongsTo.push({
|
|
13573
13376
|
name: field.name,
|
|
13574
13377
|
targetModel: field.type,
|
|
13575
|
-
foreignKey:
|
|
13378
|
+
foreignKey: foreignKeys[0],
|
|
13576
13379
|
references: field.relationToFields?.[0] ?? "id",
|
|
13577
|
-
foreignKeys
|
|
13380
|
+
foreignKeys,
|
|
13578
13381
|
referencesList: field.relationToFields ?? ["id"],
|
|
13579
13382
|
optional: !field.isRequired,
|
|
13580
13383
|
onDelete: field.relationOnDelete ?? (field.isRequired ? "Restrict" : "SetNull"),
|
|
@@ -13582,23 +13385,18 @@ function getAssociations(model, allModels) {
|
|
|
13582
13385
|
});
|
|
13583
13386
|
continue;
|
|
13584
13387
|
}
|
|
13585
|
-
|
|
13586
|
-
|
|
13587
|
-
|
|
13588
|
-
|
|
13589
|
-
|
|
13590
|
-
|
|
13591
|
-
|
|
13592
|
-
relationName: field.relationName ?? `${model.name}To${field.type}`
|
|
13593
|
-
});
|
|
13594
|
-
continue;
|
|
13595
|
-
}
|
|
13388
|
+
if (end.kind === "manyToMany") {
|
|
13389
|
+
manyToMany.push({
|
|
13390
|
+
name: field.name,
|
|
13391
|
+
targetModel: field.type,
|
|
13392
|
+
relationName: field.relationName ?? `${model.name}To${field.type}`
|
|
13393
|
+
});
|
|
13394
|
+
continue;
|
|
13596
13395
|
}
|
|
13597
|
-
const fkField =
|
|
13598
|
-
const foreignKey = fkField
|
|
13599
|
-
if (!(fkField && foreignKey)) continue;
|
|
13396
|
+
const fkField = end.inverse;
|
|
13397
|
+
const foreignKey = (fkField.relationFromFields ?? [])[0];
|
|
13600
13398
|
const onDelete = fkField.relationOnDelete ?? (fkField.isRequired ? "Restrict" : "SetNull");
|
|
13601
|
-
if (
|
|
13399
|
+
if (end.kind === "hasMany") hasMany.push({
|
|
13602
13400
|
name: field.name,
|
|
13603
13401
|
targetModel: field.type,
|
|
13604
13402
|
foreignKey,
|
|
@@ -13624,9 +13422,8 @@ function getAssociations(model, allModels) {
|
|
|
13624
13422
|
function collectManyToManyTables(allModels) {
|
|
13625
13423
|
const candidates = allModels.flatMap((model) => model.fields.flatMap((field) => {
|
|
13626
13424
|
if (field.kind !== "object" || !field.isList) return [];
|
|
13627
|
-
|
|
13628
|
-
if (!
|
|
13629
|
-
if (!targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object")?.isList) return [];
|
|
13425
|
+
if (!allModels.find((m) => m.name === field.type)) return [];
|
|
13426
|
+
if (!backRelation(field, model, allModels)?.isList) return [];
|
|
13630
13427
|
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
13631
13428
|
const leftModelObj = allModels.find((m) => m.name === leftName);
|
|
13632
13429
|
const rightModelObj = allModels.find((m) => m.name === rightName);
|
|
@@ -13673,19 +13470,6 @@ function generateAssociationTable(info, provider) {
|
|
|
13673
13470
|
")"
|
|
13674
13471
|
].join("\n");
|
|
13675
13472
|
}
|
|
13676
|
-
function toPythonString(value) {
|
|
13677
|
-
return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
|
|
13678
|
-
}
|
|
13679
|
-
function jsonToPythonLiteral(value) {
|
|
13680
|
-
if (value === null) return "None";
|
|
13681
|
-
if (value === true) return "True";
|
|
13682
|
-
if (value === false) return "False";
|
|
13683
|
-
if (typeof value === "number") return String(value);
|
|
13684
|
-
if (typeof value === "string") return toPythonString(value);
|
|
13685
|
-
if (Array.isArray(value)) return `[${value.map(jsonToPythonLiteral).join(", ")}]`;
|
|
13686
|
-
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString(k)}: ${jsonToPythonLiteral(v)}`).join(", ")}}`;
|
|
13687
|
-
return "None";
|
|
13688
|
-
}
|
|
13689
13473
|
const SQL_ACTION = {
|
|
13690
13474
|
Cascade: "CASCADE",
|
|
13691
13475
|
SetNull: "SET NULL",
|
|
@@ -13779,12 +13563,6 @@ function serverDefault(field, enumDef, provider) {
|
|
|
13779
13563
|
const cast = field.kind === "enum" || items.length === 0 ? `::${element}[]` : "";
|
|
13780
13564
|
return `ARRAY[${items.join(", ")}]${cast}`;
|
|
13781
13565
|
}
|
|
13782
|
-
function isFunctionDefault(def) {
|
|
13783
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
13784
|
-
}
|
|
13785
|
-
function isNowDefault(field) {
|
|
13786
|
-
return field.type === "DateTime" && isFunctionDefault(field.default) && field.default.name === "now";
|
|
13787
|
-
}
|
|
13788
13566
|
function usesNativeType(models, names) {
|
|
13789
13567
|
return models.some((m) => m.fields.some((f) => names.includes(f.nativeType?.[0] ?? "")));
|
|
13790
13568
|
}
|
|
@@ -13795,16 +13573,6 @@ function usesUtcDateTime(models) {
|
|
|
13795
13573
|
"DateTime"
|
|
13796
13574
|
].includes(f.nativeType?.[0] ?? "")));
|
|
13797
13575
|
}
|
|
13798
|
-
function isAutoincrement(field) {
|
|
13799
|
-
return isFunctionDefault(field.default) && field.default.name === "autoincrement";
|
|
13800
|
-
}
|
|
13801
|
-
function uuidDefaultVersion(field) {
|
|
13802
|
-
if (!(isFunctionDefault(field.default) && field.default.name === "uuid")) return null;
|
|
13803
|
-
return field.default.args[0] === 7 ? 7 : 4;
|
|
13804
|
-
}
|
|
13805
|
-
function isUlidDefault(field) {
|
|
13806
|
-
return isFunctionDefault(field.default) && field.default.name === "ulid";
|
|
13807
|
-
}
|
|
13808
13576
|
function needsForeignKeysParam(targetModel, assocs) {
|
|
13809
13577
|
return assocs.filter((a) => a.targetModel === targetModel).length > 1;
|
|
13810
13578
|
}
|
|
@@ -13859,7 +13627,7 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, pro
|
|
|
13859
13627
|
if (isPk && isAutoincrement(field)) colArgs.push("autoincrement=True");
|
|
13860
13628
|
if (provider !== "sqlite" && field.isId && ["Int", "BigInt"].includes(field.type) && !isAutoincrement(field)) colArgs.push("autoincrement=False");
|
|
13861
13629
|
if (field.isList) colArgs.push("nullable=True");
|
|
13862
|
-
const hasNowDefault = isNowDefault(field);
|
|
13630
|
+
const hasNowDefault = isNowDefault$1(field);
|
|
13863
13631
|
const nativeName = field.nativeType?.[0];
|
|
13864
13632
|
const utcNow = nativeName === "Date" ? "lambda: utc_now().date()" : nativeName === "Time" ? "lambda: utc_now().time()" : nativeName === "Timetz" ? "lambda: utc_now().timetz()" : "utc_now";
|
|
13865
13633
|
const fsp = field.nativeType ? field.nativeType[1][0] : "3";
|
|
@@ -14011,7 +13779,7 @@ function collectGlobalImports(models, _enums, indexes, m2mTables, provider) {
|
|
|
14011
13779
|
const needsUtcDateTime = usesUtcDateTime(models);
|
|
14012
13780
|
const needsUtcTimestamp = provider === "mysql" && usesNativeType(models, ["Timestamp"]);
|
|
14013
13781
|
const needsUtcType = needsUtcDateTime || provider !== "mysql" && usesNativeType(models, ["Timestamptz"]);
|
|
14014
|
-
const needsUtcNow = models.some((m) => m.fields.some((f) => isNowDefault(f) || f.isUpdatedAt));
|
|
13782
|
+
const needsUtcNow = models.some((m) => m.fields.some((f) => isNowDefault$1(f) || f.isUpdatedAt));
|
|
14015
13783
|
const needsDatetime = needsUtcNow || models.some((m) => m.fields.some((f) => f.type === "DateTime" && ![
|
|
14016
13784
|
"Date",
|
|
14017
13785
|
"Time",
|
|
@@ -14215,7 +13983,7 @@ function generateBase(models, provider) {
|
|
|
14215
13983
|
"",
|
|
14216
13984
|
""
|
|
14217
13985
|
] : [];
|
|
14218
|
-
const utcNow = models.some((m) => m.fields.some((f) => isNowDefault(f) || f.isUpdatedAt)) ? [
|
|
13986
|
+
const utcNow = models.some((m) => m.fields.some((f) => isNowDefault$1(f) || f.isUpdatedAt)) ? [
|
|
14219
13987
|
"def utc_now() -> datetime:",
|
|
14220
13988
|
" return datetime.now(timezone.utc)",
|
|
14221
13989
|
"",
|
|
@@ -14258,13 +14026,11 @@ function generateSingleFile(models, enums, indexes, provider = "postgresql") {
|
|
|
14258
14026
|
//#region src/core/sqlalchemy.ts
|
|
14259
14027
|
function sqlalchemy(options) {
|
|
14260
14028
|
return Effect.gen(function* () {
|
|
14261
|
-
|
|
14262
|
-
const output = options.generator.output.value;
|
|
14263
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
14029
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-SQLAlchemy"), "models.py");
|
|
14264
14030
|
const enums = options.dmmf.datamodel.enums;
|
|
14265
14031
|
const indexes = options.dmmf.datamodel.indexes;
|
|
14266
14032
|
const code = generateSingleFile(options.dmmf.datamodel.models, enums, indexes, options.datasources[0]?.activeProvider);
|
|
14267
|
-
return yield* emitRaw(code,
|
|
14033
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
14268
14034
|
});
|
|
14269
14035
|
}
|
|
14270
14036
|
//#endregion
|
|
@@ -14276,12 +14042,11 @@ function makeTypeBoxSchema(modelName, fields, objectType) {
|
|
|
14276
14042
|
const obj = `Type.Object({\n${fields}\n})`;
|
|
14277
14043
|
return objectType === "strict" ? `export const ${modelName}Schema = Type.Strict(${obj})` : `export const ${modelName}Schema = ${obj}`;
|
|
14278
14044
|
}
|
|
14279
|
-
function makeTypeBoxProperties(fields
|
|
14045
|
+
function makeTypeBoxProperties(fields) {
|
|
14280
14046
|
return fields.map((field) => {
|
|
14281
|
-
const commentBlock = comment ? makeCommentBlock(field.comment, 2) : "";
|
|
14282
14047
|
const expr = field.validation ?? "Type.Unknown()";
|
|
14283
14048
|
const wrapped = field.isRequired ? expr : `Type.Optional(${expr})`;
|
|
14284
|
-
return
|
|
14049
|
+
return ` ${field.fieldName}: ${wrapped},`;
|
|
14285
14050
|
}).join("\n");
|
|
14286
14051
|
}
|
|
14287
14052
|
function makeTypeBoxEnumExpression(values) {
|
|
@@ -14298,8 +14063,8 @@ const PRISMA_TO_TYPEBOX = {
|
|
|
14298
14063
|
Json: "Type.Unknown()",
|
|
14299
14064
|
Bytes: "Type.Any()"
|
|
14300
14065
|
};
|
|
14301
|
-
function makeTypeBoxSchemas(modelFields,
|
|
14302
|
-
return schemaFromFields(modelFields,
|
|
14066
|
+
function makeTypeBoxSchemas(modelFields, objectType) {
|
|
14067
|
+
return schemaFromFields(modelFields, makeTypeBoxSchema, makeTypeBoxProperties, objectType);
|
|
14303
14068
|
}
|
|
14304
14069
|
function makeTypeBoxRelations(model, relProps, options) {
|
|
14305
14070
|
if (relProps.length === 0) return null;
|
|
@@ -14308,11 +14073,10 @@ function makeTypeBoxRelations(model, relProps, options) {
|
|
|
14308
14073
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = Static<typeof ${model.name}RelationsSchema>` : "";
|
|
14309
14074
|
return `export const ${model.name}RelationsSchema = Type.Object({\n${base}\n${rels}\n})${typeLine}`;
|
|
14310
14075
|
}
|
|
14311
|
-
function typeboxSchemaCode(models, type,
|
|
14312
|
-
return validationSchemas(models, type,
|
|
14076
|
+
function typeboxSchemaCode(models, type, enums) {
|
|
14077
|
+
return validationSchemas(models, type, {
|
|
14313
14078
|
importStatement: type ? `import { type Static, Type } from '@sinclair/typebox'` : `import { Type } from '@sinclair/typebox'`,
|
|
14314
14079
|
annotationPrefix: "@t.",
|
|
14315
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
14316
14080
|
extractValidation: makeValidationExtractor("@t."),
|
|
14317
14081
|
inferType: makeTypeBoxInfer,
|
|
14318
14082
|
schemas: makeTypeBoxSchemas,
|
|
@@ -14323,23 +14087,15 @@ function typeboxSchemaCode(models, type, comment, enums) {
|
|
|
14323
14087
|
}
|
|
14324
14088
|
//#endregion
|
|
14325
14089
|
//#region src/generator/typebox.ts
|
|
14326
|
-
function typeboxCode(dmmf, type,
|
|
14327
|
-
return [typeboxSchemaCode(dmmf.datamodel.models, type,
|
|
14090
|
+
function typeboxCode(dmmf, type, relation) {
|
|
14091
|
+
return [typeboxSchemaCode(dmmf.datamodel.models, type, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeTypeBoxRelations) : ""].filter(Boolean).join("\n\n");
|
|
14328
14092
|
}
|
|
14329
14093
|
//#endregion
|
|
14330
14094
|
//#region src/core/typebox.ts
|
|
14331
14095
|
function typebox(options) {
|
|
14332
14096
|
return Effect.gen(function* () {
|
|
14333
|
-
|
|
14334
|
-
const
|
|
14335
|
-
const resolved = path.extname(output) ? {
|
|
14336
|
-
dir: path.dirname(output),
|
|
14337
|
-
file: output
|
|
14338
|
-
} : {
|
|
14339
|
-
dir: output,
|
|
14340
|
-
file: path.join(output, "index.ts")
|
|
14341
|
-
};
|
|
14342
|
-
const code = typeboxCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation));
|
|
14097
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-TypeBox"), "index.ts");
|
|
14098
|
+
const code = typeboxCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
14343
14099
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14344
14100
|
});
|
|
14345
14101
|
}
|
|
@@ -14365,8 +14121,8 @@ const PRISMA_TO_VALIBOT = {
|
|
|
14365
14121
|
Json: "unknown()",
|
|
14366
14122
|
Bytes: "any()"
|
|
14367
14123
|
};
|
|
14368
|
-
function makeValibotSchemas(modelFields,
|
|
14369
|
-
return schemaFromFields(modelFields,
|
|
14124
|
+
function makeValibotSchemas(modelFields, objectType) {
|
|
14125
|
+
return schemaFromFields(modelFields, makeValibotSchema, makePropertiesGenerator("v", (expr, isRequired) => isRequired ? expr : `v.exactOptional(${expr})`), objectType);
|
|
14370
14126
|
}
|
|
14371
14127
|
function makeValibotRelations(model, relProps, options) {
|
|
14372
14128
|
if (relProps.length === 0) return null;
|
|
@@ -14375,11 +14131,10 @@ function makeValibotRelations(model, relProps, options) {
|
|
|
14375
14131
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = v.InferOutput<typeof ${model.name}RelationsSchema>` : "";
|
|
14376
14132
|
return `export const ${model.name}RelationsSchema = v.object({\n${base}\n${rels}\n})${typeLine}`;
|
|
14377
14133
|
}
|
|
14378
|
-
function valibotSchemaCode(models, type,
|
|
14379
|
-
return validationSchemas(models, type,
|
|
14134
|
+
function valibotSchemaCode(models, type, enums) {
|
|
14135
|
+
return validationSchemas(models, type, {
|
|
14380
14136
|
importStatement: `import * as v from 'valibot'`,
|
|
14381
14137
|
annotationPrefix: "@v.",
|
|
14382
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
14383
14138
|
extractValidation: makeValidationExtractor("@v."),
|
|
14384
14139
|
inferType: makeValibotInfer,
|
|
14385
14140
|
schemas: makeValibotSchemas,
|
|
@@ -14390,23 +14145,15 @@ function valibotSchemaCode(models, type, comment, enums) {
|
|
|
14390
14145
|
}
|
|
14391
14146
|
//#endregion
|
|
14392
14147
|
//#region src/generator/valibot.ts
|
|
14393
|
-
function valibotCode(dmmf, type,
|
|
14394
|
-
return [valibotSchemaCode(dmmf.datamodel.models, type,
|
|
14148
|
+
function valibotCode(dmmf, type, relation) {
|
|
14149
|
+
return [valibotSchemaCode(dmmf.datamodel.models, type, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeValibotRelations) : ""].filter(Boolean).join("\n\n");
|
|
14395
14150
|
}
|
|
14396
14151
|
//#endregion
|
|
14397
14152
|
//#region src/core/valibot.ts
|
|
14398
14153
|
function valibot(options) {
|
|
14399
14154
|
return Effect.gen(function* () {
|
|
14400
|
-
|
|
14401
|
-
const
|
|
14402
|
-
const resolved = path.extname(output) ? {
|
|
14403
|
-
dir: path.dirname(output),
|
|
14404
|
-
file: output
|
|
14405
|
-
} : {
|
|
14406
|
-
dir: output,
|
|
14407
|
-
file: path.join(output, "index.ts")
|
|
14408
|
-
};
|
|
14409
|
-
const code = valibotCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation));
|
|
14155
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Valibot"), "index.ts");
|
|
14156
|
+
const code = valibotCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
14410
14157
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14411
14158
|
});
|
|
14412
14159
|
}
|
|
@@ -14432,8 +14179,8 @@ const PRISMA_TO_ZOD = {
|
|
|
14432
14179
|
Json: "unknown()",
|
|
14433
14180
|
Bytes: "any()"
|
|
14434
14181
|
};
|
|
14435
|
-
function makeZodSchemas(modelFields,
|
|
14436
|
-
return schemaFromFields(modelFields,
|
|
14182
|
+
function makeZodSchemas(modelFields, objectType) {
|
|
14183
|
+
return schemaFromFields(modelFields, makeZodSchema, makePropertiesGenerator("z", (expr, isRequired) => isRequired ? expr : `${expr}.exactOptional()`), objectType);
|
|
14437
14184
|
}
|
|
14438
14185
|
function makeZodRelations(model, relProps, options) {
|
|
14439
14186
|
if (relProps.length === 0) return null;
|
|
@@ -14442,11 +14189,10 @@ function makeZodRelations(model, relProps, options) {
|
|
|
14442
14189
|
const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = z.infer<typeof ${model.name}RelationsSchema>` : "";
|
|
14443
14190
|
return `export const ${model.name}RelationsSchema = z.object({\n${base}\n${rels}\n})${typeLine}`;
|
|
14444
14191
|
}
|
|
14445
|
-
function zodSchemaCode(models, type,
|
|
14446
|
-
return validationSchemas(models, type,
|
|
14192
|
+
function zodSchemaCode(models, type, zodVersion, enums) {
|
|
14193
|
+
return validationSchemas(models, type, {
|
|
14447
14194
|
importStatement: zodVersion === "mini" ? `import * as z from 'zod/mini'` : zodVersion === "@hono/zod-openapi" ? `import { z } from '@hono/zod-openapi'` : `import * as z from 'zod'`,
|
|
14448
14195
|
annotationPrefix: "@z.",
|
|
14449
|
-
parseDocument: parseDocumentWithoutAnnotations,
|
|
14450
14196
|
extractValidation: makeValidationExtractor("@z."),
|
|
14451
14197
|
inferType: makeZodInfer,
|
|
14452
14198
|
schemas: makeZodSchemas,
|
|
@@ -14457,23 +14203,15 @@ function zodSchemaCode(models, type, comment, zodVersion, enums) {
|
|
|
14457
14203
|
}
|
|
14458
14204
|
//#endregion
|
|
14459
14205
|
//#region src/generator/zod.ts
|
|
14460
|
-
function zodCode(dmmf, type,
|
|
14461
|
-
return [zodSchemaCode(dmmf.datamodel.models, type,
|
|
14206
|
+
function zodCode(dmmf, type, relation, version) {
|
|
14207
|
+
return [zodSchemaCode(dmmf.datamodel.models, type, version, dmmf.datamodel.enums), relation ? makeRelationsOnly(dmmf, type, makeZodRelations) : ""].filter(Boolean).join("\n\n");
|
|
14462
14208
|
}
|
|
14463
14209
|
//#endregion
|
|
14464
14210
|
//#region src/core/zod.ts
|
|
14465
14211
|
function zod(options) {
|
|
14466
14212
|
return Effect.gen(function* () {
|
|
14467
|
-
|
|
14468
|
-
const
|
|
14469
|
-
const resolved = path.extname(output) ? {
|
|
14470
|
-
dir: path.dirname(output),
|
|
14471
|
-
file: output
|
|
14472
|
-
} : {
|
|
14473
|
-
dir: output,
|
|
14474
|
-
file: path.join(output, "index.ts")
|
|
14475
|
-
};
|
|
14476
|
-
const code = zodCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation), getString(options.generator.config?.zod) ?? "v4");
|
|
14213
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Zod"), "index.ts");
|
|
14214
|
+
const code = zodCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation), getString(options.generator.config?.zod) ?? "v4");
|
|
14477
14215
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14478
14216
|
});
|
|
14479
14217
|
}
|
|
@@ -14575,7 +14313,7 @@ function registerGenerator(name) {
|
|
|
14575
14313
|
};
|
|
14576
14314
|
},
|
|
14577
14315
|
onGenerate(options) {
|
|
14578
|
-
return Effect.runPromise(handler(options).pipe(Effect.mapError((error) => new Error(error.message)), Effect.provide(
|
|
14316
|
+
return Effect.runPromise(handler(options).pipe(Effect.mapError((error) => new Error(error.message)), Effect.provide(layer)));
|
|
14579
14317
|
}
|
|
14580
14318
|
});
|
|
14581
14319
|
}
|