hekireki 0.35.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 +1 -1
- 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-C0Ai2A-I.js → bin-CVN0pzc4.js} +360 -606
- package/dist/{discover--iPWKb4M.js → discover-CcuFW0ZA.js} +1 -1
- package/dist/{emit-J65acfDW.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-Cg4iEPuL.js → migrate-DmUsB0Wq.js} +4 -4
- package/dist/{plan-C7eaA9eW.js → plan-FKGe6CzO.js} +8 -8
- package/dist/{utils-BkyzXzxi.js → prisma-model-NuNLrPtP.js} +101 -1
- package/dist/{run-DBSsSPvv.js → run-qU5ejzJJ.js} +17 -19
- package/dist/{schema-DIEoug_s.js → schema-D8vxD4Kv.js} +3 -8
- package/dist/{sql-D_F3Jcnx.js → sql-BWRXT82c.js} +157 -78
- package/dist/{start-BnxrNq5D.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 {
|
|
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,27 +1580,49 @@ 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
|
|
@@ -1758,15 +1760,7 @@ function ajvCode(dmmf, type, relation) {
|
|
|
1758
1760
|
//#region src/core/ajv.ts
|
|
1759
1761
|
function ajv(options) {
|
|
1760
1762
|
return Effect.gen(function* () {
|
|
1761
|
-
|
|
1762
|
-
const output = options.generator.output.value;
|
|
1763
|
-
const resolved = path.extname(output) ? {
|
|
1764
|
-
dir: path.dirname(output),
|
|
1765
|
-
file: output
|
|
1766
|
-
} : {
|
|
1767
|
-
dir: output,
|
|
1768
|
-
file: path.join(output, "index.ts")
|
|
1769
|
-
};
|
|
1763
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-AJV"), "index.ts");
|
|
1770
1764
|
const code = ajvCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
1771
1765
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
1772
1766
|
});
|
|
@@ -1827,15 +1821,7 @@ function arktypeCode(dmmf, type, relation) {
|
|
|
1827
1821
|
//#region src/core/arktype.ts
|
|
1828
1822
|
function arktype(options) {
|
|
1829
1823
|
return Effect.gen(function* () {
|
|
1830
|
-
|
|
1831
|
-
const output = options.generator.output.value;
|
|
1832
|
-
const resolved = path.extname(output) ? {
|
|
1833
|
-
dir: path.dirname(output),
|
|
1834
|
-
file: output
|
|
1835
|
-
} : {
|
|
1836
|
-
dir: output,
|
|
1837
|
-
file: path.join(output, "index.ts")
|
|
1838
|
-
};
|
|
1824
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-ArkType"), "index.ts");
|
|
1839
1825
|
const code = arktypeCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
1840
1826
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
1841
1827
|
});
|
|
@@ -1918,9 +1904,6 @@ function tableRef$1(target, models, defaultSchema) {
|
|
|
1918
1904
|
const name = tableNameOf(target);
|
|
1919
1905
|
return duplicateTableNames(models).has(name) ? `table${refPart(schemaOf(target, defaultSchema))}${refPart(name)}` : `table${refPart(name)}`;
|
|
1920
1906
|
}
|
|
1921
|
-
function isFunctionDefault$7(def) {
|
|
1922
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
1923
|
-
}
|
|
1924
1907
|
function pgNativeType$1(name, args) {
|
|
1925
1908
|
switch (name) {
|
|
1926
1909
|
case "Uuid": return "uuid";
|
|
@@ -2164,7 +2147,7 @@ function listDefault(items, field, dialect, enums) {
|
|
|
2164
2147
|
function resolveDefault(field, dialect, enums) {
|
|
2165
2148
|
const dflt = field.default;
|
|
2166
2149
|
if (!field.hasDefaultValue || dflt === void 0 || dflt === null) return void 0;
|
|
2167
|
-
if (isFunctionDefault
|
|
2150
|
+
if (isFunctionDefault(dflt)) {
|
|
2168
2151
|
if (dflt.name === "now") return dialect === "mysql" ? sqlExpr("CURRENT_TIMESTAMP(3)") : sqlExpr("CURRENT_TIMESTAMP");
|
|
2169
2152
|
if (dflt.name === "dbgenerated") return typeof dflt.args[0] === "string" ? sqlExpr(dflt.args[0]) : void 0;
|
|
2170
2153
|
return;
|
|
@@ -2179,7 +2162,7 @@ function resolveDefault(field, dialect, enums) {
|
|
|
2179
2162
|
}
|
|
2180
2163
|
function makeAtlasColumn(field, dialect, enums) {
|
|
2181
2164
|
const name = field.dbName ?? field.name;
|
|
2182
|
-
const isAutoincrement = isFunctionDefault
|
|
2165
|
+
const isAutoincrement = isFunctionDefault(field.default) && field.default.name === "autoincrement";
|
|
2183
2166
|
const typeInfo = columnTypeInfo(field, dialect, enums, isAutoincrement);
|
|
2184
2167
|
const defaultValue = isAutoincrement ? void 0 : resolveDefault(field, dialect, enums);
|
|
2185
2168
|
const attrs = [
|
|
@@ -2276,35 +2259,6 @@ function makeAtlasTable(model, models, indexes, dialect, enums, options) {
|
|
|
2276
2259
|
"}"
|
|
2277
2260
|
].join("\n");
|
|
2278
2261
|
}
|
|
2279
|
-
function isImplicitM2M$2(field, models) {
|
|
2280
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
2281
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
2282
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
2283
|
-
}
|
|
2284
|
-
function collectM2M(models) {
|
|
2285
|
-
const pairs = models.flatMap((model) => model.fields.filter((field) => isImplicitM2M$2(field, models)).map((field) => {
|
|
2286
|
-
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2287
|
-
return {
|
|
2288
|
-
leftName,
|
|
2289
|
-
rightName,
|
|
2290
|
-
relationName: field.relationName ?? `${leftName}To${rightName}`
|
|
2291
|
-
};
|
|
2292
|
-
}));
|
|
2293
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2294
|
-
return pairs.filter((pair) => {
|
|
2295
|
-
if (seen.has(pair.relationName)) return false;
|
|
2296
|
-
seen.add(pair.relationName);
|
|
2297
|
-
return true;
|
|
2298
|
-
}).flatMap((pair) => {
|
|
2299
|
-
const left = models.find((m) => m.name === pair.leftName);
|
|
2300
|
-
const right = models.find((m) => m.name === pair.rightName);
|
|
2301
|
-
return left && right ? [{
|
|
2302
|
-
left,
|
|
2303
|
-
right,
|
|
2304
|
-
relationName: pair.relationName
|
|
2305
|
-
}] : [];
|
|
2306
|
-
});
|
|
2307
|
-
}
|
|
2308
2262
|
function m2mColumn(side, pkField, dialect, enums) {
|
|
2309
2263
|
const type = pkField ? columnTypeInfo(pkField, dialect, enums, false).type : "text";
|
|
2310
2264
|
return [
|
|
@@ -2329,7 +2283,15 @@ function m2mForeignKey(side, target, tableName, models, defaultSchema) {
|
|
|
2329
2283
|
].join("\n");
|
|
2330
2284
|
}
|
|
2331
2285
|
function makeAtlasM2MJoinTables(models, dialect, enums, defaultSchema) {
|
|
2332
|
-
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) => {
|
|
2333
2295
|
const tableName = `_${pair.relationName}`;
|
|
2334
2296
|
const leftPk = pair.left.fields.find((f) => f.isId);
|
|
2335
2297
|
const rightPk = pair.right.fields.find((f) => f.isId);
|
|
@@ -2390,17 +2352,33 @@ function atlasSchema(datamodel, provider, config) {
|
|
|
2390
2352
|
//#region src/core/atlas.ts
|
|
2391
2353
|
function atlas(options) {
|
|
2392
2354
|
return Effect.gen(function* () {
|
|
2393
|
-
|
|
2355
|
+
const output = yield* requireOutput(options, "Hekireki-Atlas");
|
|
2394
2356
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
2395
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.` });
|
|
2396
|
-
const output = options.generator.output.value;
|
|
2397
2358
|
const schemaName = getString(options.generator.config?.schemaName);
|
|
2398
2359
|
const content = atlasSchema(options.dmmf.datamodel, provider, { schemaName });
|
|
2399
|
-
const
|
|
2400
|
-
return yield* emitRaw(content,
|
|
2360
|
+
const resolved = outputFile(output, "schema.hcl");
|
|
2361
|
+
return yield* emitRaw(content, resolved.dir, resolved.file);
|
|
2401
2362
|
});
|
|
2402
2363
|
}
|
|
2403
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
|
|
2404
2382
|
//#region src/helper/django.ts
|
|
2405
2383
|
const PRISMA_TO_DJANGO = {
|
|
2406
2384
|
String: "TextField",
|
|
@@ -2587,37 +2565,8 @@ function resolveDjangoField(field) {
|
|
|
2587
2565
|
default: return baseResolved;
|
|
2588
2566
|
}
|
|
2589
2567
|
}
|
|
2590
|
-
function toPythonString$1(value) {
|
|
2591
|
-
return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
|
|
2592
|
-
}
|
|
2593
|
-
function jsonToPythonLiteral$1(value) {
|
|
2594
|
-
if (value === null) return "None";
|
|
2595
|
-
if (value === true) return "True";
|
|
2596
|
-
if (value === false) return "False";
|
|
2597
|
-
if (typeof value === "number") return String(value);
|
|
2598
|
-
if (typeof value === "string") return toPythonString$1(value);
|
|
2599
|
-
if (Array.isArray(value)) return `[${value.map(jsonToPythonLiteral$1).join(", ")}]`;
|
|
2600
|
-
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString$1(k)}: ${jsonToPythonLiteral$1(v)}`).join(", ")}}`;
|
|
2601
|
-
return "None";
|
|
2602
|
-
}
|
|
2603
|
-
function isFunctionDefault$6(def) {
|
|
2604
|
-
return def !== null && typeof def === "object" && "name" in def && !Array.isArray(def);
|
|
2605
|
-
}
|
|
2606
|
-
function isAutoincrement$3(field) {
|
|
2607
|
-
return isFunctionDefault$6(field.default) && field.default.name === "autoincrement";
|
|
2608
|
-
}
|
|
2609
|
-
function uuidDefaultVersion$1(field) {
|
|
2610
|
-
if (!(isFunctionDefault$6(field.default) && field.default.name === "uuid")) return null;
|
|
2611
|
-
return field.default.args[0] === 7 ? 7 : 4;
|
|
2612
|
-
}
|
|
2613
|
-
function isUlidDefault$1(field) {
|
|
2614
|
-
return isFunctionDefault$6(field.default) && field.default.name === "ulid";
|
|
2615
|
-
}
|
|
2616
|
-
function isNowDefault$2(field) {
|
|
2617
|
-
return field.type === "DateTime" && isFunctionDefault$6(field.default) && field.default.name === "now";
|
|
2618
|
-
}
|
|
2619
2568
|
function dbGeneratedExpr(field) {
|
|
2620
|
-
return isFunctionDefault
|
|
2569
|
+
return isFunctionDefault(field.default) && field.default.name === "dbgenerated" && typeof field.default.args[0] === "string" ? field.default.args[0] : null;
|
|
2621
2570
|
}
|
|
2622
2571
|
function dateTimeKind(field) {
|
|
2623
2572
|
const { ctor } = resolveDjangoField(field);
|
|
@@ -2635,7 +2584,7 @@ function dateTimeLiteral(field, iso) {
|
|
|
2635
2584
|
at.getUTCSeconds()
|
|
2636
2585
|
], ...micro > 0 ? [micro] : []].join(", ")})`;
|
|
2637
2586
|
}
|
|
2638
|
-
return `datetime.fromisoformat(${toPythonString
|
|
2587
|
+
return `datetime.fromisoformat(${toPythonString(iso)})`;
|
|
2639
2588
|
}
|
|
2640
2589
|
function holdsUtc(field, provider) {
|
|
2641
2590
|
if (field.type !== "DateTime" || resolveDjangoField(field).ctor !== "DateTimeField") return false;
|
|
@@ -2649,10 +2598,10 @@ function scalarElementLiteral(field, value) {
|
|
|
2649
2598
|
if (type === "BigInt") return value;
|
|
2650
2599
|
if (type === "Decimal") return `Decimal("${value}")`;
|
|
2651
2600
|
if (type === "DateTime") return dateTimeLiteral(field, value);
|
|
2652
|
-
if (type === "Json") return jsonToPythonLiteral
|
|
2653
|
-
return toPythonString
|
|
2601
|
+
if (type === "Json") return jsonToPythonLiteral(JSON.parse(value));
|
|
2602
|
+
return toPythonString(value);
|
|
2654
2603
|
}
|
|
2655
|
-
return jsonToPythonLiteral
|
|
2604
|
+
return jsonToPythonLiteral(value);
|
|
2656
2605
|
}
|
|
2657
2606
|
function fieldColumnName(field) {
|
|
2658
2607
|
return field.dbName ?? field.name;
|
|
@@ -2723,9 +2672,9 @@ function fieldDefaultHelper(model, field, names, enumMap) {
|
|
|
2723
2672
|
const parsed = JSON.parse(field.default);
|
|
2724
2673
|
if (typeof parsed === "object" && parsed !== null) {
|
|
2725
2674
|
if (Array.isArray(parsed) ? parsed.length === 0 : Object.keys(parsed).length === 0) return null;
|
|
2726
|
-
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");
|
|
2727
2676
|
}
|
|
2728
|
-
return [`def ${helperName}() -> ${jsonScalarReturnType(parsed)}:`, ` return ${jsonToPythonLiteral
|
|
2677
|
+
return [`def ${helperName}() -> ${jsonScalarReturnType(parsed)}:`, ` return ${jsonToPythonLiteral(parsed)}`].join("\n");
|
|
2729
2678
|
}
|
|
2730
2679
|
return null;
|
|
2731
2680
|
}
|
|
@@ -2741,11 +2690,11 @@ function jsonScalarReturnType(parsed) {
|
|
|
2741
2690
|
function collectDefaultHelpers(models, names, enums) {
|
|
2742
2691
|
const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
|
|
2743
2692
|
const uuidHelpers = [
|
|
2744
|
-
models.some((m) => m.fields.some((f) => uuidDefaultVersion
|
|
2745
|
-
models.some((m) => m.fields.some((f) => uuidDefaultVersion
|
|
2746
|
-
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
|
|
2747
2696
|
].filter((h) => h !== null);
|
|
2748
|
-
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))));
|
|
2749
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);
|
|
2750
2699
|
const fieldHelpers = models.flatMap((model) => model.fields.filter((f) => f.kind !== "object").map((field) => fieldDefaultHelper(model, field, names, enumMap)).filter((h) => h !== null));
|
|
2751
2700
|
return [
|
|
@@ -2813,20 +2762,20 @@ function collectFieldClasses(models, provider) {
|
|
|
2813
2762
|
function formatDefaultArgs(model, field, isPk, names) {
|
|
2814
2763
|
if (field.isUpdatedAt) return ["auto_now=True"];
|
|
2815
2764
|
const generated = dbGeneratedExpr(field);
|
|
2816
|
-
if (generated !== null) return [`db_default=RawSQL(${toPythonString
|
|
2817
|
-
if (isNowDefault$
|
|
2765
|
+
if (generated !== null) return [`db_default=RawSQL(${toPythonString(generated)}, [])`];
|
|
2766
|
+
if (isNowDefault$1(field)) {
|
|
2818
2767
|
const kind = dateTimeKind(field);
|
|
2819
2768
|
return [kind === "date" ? "default=utc_today" : kind === "time" ? "default=utc_time" : "default=timezone.now"];
|
|
2820
2769
|
}
|
|
2821
|
-
const uuidVersion = uuidDefaultVersion
|
|
2770
|
+
const uuidVersion = uuidDefaultVersion(field);
|
|
2822
2771
|
if (uuidVersion !== null) {
|
|
2823
2772
|
if (field.nativeType?.[0] === "Uuid") return [uuidVersion === 7 ? "default=uuid6.uuid7" : "default=uuid.uuid4"];
|
|
2824
2773
|
return [uuidVersion === 7 ? "default=uuid7_str" : "default=uuid4_str"];
|
|
2825
2774
|
}
|
|
2826
|
-
if (isUlidDefault
|
|
2775
|
+
if (isUlidDefault(field)) return ["default=ulid_str"];
|
|
2827
2776
|
const def = field.default;
|
|
2828
2777
|
if (def === void 0 || def === null) return [];
|
|
2829
|
-
if (isFunctionDefault
|
|
2778
|
+
if (isFunctionDefault(def)) return [];
|
|
2830
2779
|
if (Array.isArray(def)) return def.length === 0 ? ["default=list"] : [`default=${helperNameOf(names, model, field)}`];
|
|
2831
2780
|
if (field.kind === "enum" && typeof def === "string") return [`default=${makePascalCase(field.type)}.${enumMemberName(def)}`];
|
|
2832
2781
|
if (isPk) return [];
|
|
@@ -2844,7 +2793,7 @@ function formatDefaultArgs(model, field, isPk, names) {
|
|
|
2844
2793
|
}
|
|
2845
2794
|
return [`default=${helperNameOf(names, model, field)}`];
|
|
2846
2795
|
}
|
|
2847
|
-
return [`default=${toPythonString
|
|
2796
|
+
return [`default=${toPythonString(def)}`];
|
|
2848
2797
|
}
|
|
2849
2798
|
return [];
|
|
2850
2799
|
}
|
|
@@ -2859,7 +2808,7 @@ function generateScalarField(model, field, isPk, names, provider) {
|
|
|
2859
2808
|
ctor: "TextField",
|
|
2860
2809
|
typeArgs: [`choices=${makePascalCase(field.type)}.choices`]
|
|
2861
2810
|
} : resolveDjangoField(field);
|
|
2862
|
-
const ctorResolved = isPk && isAutoincrement
|
|
2811
|
+
const ctorResolved = isPk && isAutoincrement(field) ? {
|
|
2863
2812
|
ctor: autoFieldCtor(field),
|
|
2864
2813
|
typeArgs: []
|
|
2865
2814
|
} : resolved;
|
|
@@ -2873,7 +2822,7 @@ function generateScalarField(model, field, isPk, names, provider) {
|
|
|
2873
2822
|
isPk ? "primary_key=True" : null,
|
|
2874
2823
|
!field.isList && !field.isRequired ? "null=True" : null,
|
|
2875
2824
|
field.isUnique ? "unique=True" : null,
|
|
2876
|
-
attrName !== columnName ? `db_column=${toPythonString
|
|
2825
|
+
attrName !== columnName ? `db_column=${toPythonString(columnName)}` : null,
|
|
2877
2826
|
...defaultArgs,
|
|
2878
2827
|
emptyStringPk ? "default=None" : null
|
|
2879
2828
|
].filter((a) => a !== null);
|
|
@@ -2892,27 +2841,23 @@ function onDeleteFor(field) {
|
|
|
2892
2841
|
if (field.relationOnDelete && ON_DELETE[field.relationOnDelete]) return ON_DELETE[field.relationOnDelete];
|
|
2893
2842
|
return field.isRequired ? "models.RESTRICT" : "models.SET_NULL";
|
|
2894
2843
|
}
|
|
2895
|
-
function findBackRelationField(relationField, model, allModels) {
|
|
2896
|
-
const targetModel = allModels.find((m) => m.name === relationField.type);
|
|
2897
|
-
return targetModel?.fields.find((f) => f.kind === "object" && f.type === model.name && f.relationName === relationField.relationName && !(targetModel.name === model.name && f.name === relationField.name));
|
|
2898
|
-
}
|
|
2899
2844
|
function generateForeignKeyField(model, relationField, scalarField, allModels, names) {
|
|
2900
2845
|
const attrName = attrNameOf(names, model, relationField);
|
|
2901
2846
|
const columnName = fieldColumnName(scalarField);
|
|
2902
|
-
const backField =
|
|
2847
|
+
const backField = backRelation(relationField, model, allModels);
|
|
2903
2848
|
const ctor = backField && !backField.isList ? "OneToOneField" : "ForeignKey";
|
|
2904
2849
|
const target = relationField.type === model.name ? "\"self\"" : `"${makePascalCase(relationField.type)}"`;
|
|
2905
|
-
const relatedName = backField ? toPythonString
|
|
2850
|
+
const relatedName = backField ? toPythonString(djangoAttrName(makeSnakeCase(backField.name))) : "\"+\"";
|
|
2906
2851
|
const targetModel = allModels.find((m) => m.name === relationField.type);
|
|
2907
2852
|
const referencedName = relationField.relationToFields?.[0];
|
|
2908
2853
|
const referencedField = targetModel?.fields.find((f) => f.name === referencedName);
|
|
2909
|
-
const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString
|
|
2854
|
+
const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
|
|
2910
2855
|
return ` ${attrName} = models.${ctor}(${[
|
|
2911
2856
|
target,
|
|
2912
2857
|
`on_delete=${onDeleteFor(relationField)}`,
|
|
2913
2858
|
`related_name=${relatedName}`,
|
|
2914
2859
|
toField,
|
|
2915
|
-
columnName !== `${attrName}_id` ? `db_column=${toPythonString
|
|
2860
|
+
columnName !== `${attrName}_id` ? `db_column=${toPythonString(columnName)}` : null,
|
|
2916
2861
|
!relationField.isRequired ? "null=True" : null,
|
|
2917
2862
|
ctor === "ForeignKey" ? "db_index=False" : null,
|
|
2918
2863
|
...formatDefaultArgs(model, scalarField, false, names)
|
|
@@ -2927,9 +2872,7 @@ function uniqueClassName(preferred, taken) {
|
|
|
2927
2872
|
function collectManyToManyTables$1(allModels, enums) {
|
|
2928
2873
|
const candidates = allModels.flatMap((model) => model.fields.flatMap((field) => {
|
|
2929
2874
|
if (field.kind !== "object" || !field.isList) return [];
|
|
2930
|
-
|
|
2931
|
-
if (!targetModel) return [];
|
|
2932
|
-
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 [];
|
|
2933
2876
|
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2934
2877
|
const relationName = field.relationName ?? `${leftName}To${rightName}`;
|
|
2935
2878
|
return [{
|
|
@@ -2964,18 +2907,18 @@ function generateThroughModel(info) {
|
|
|
2964
2907
|
` b = models.ForeignKey("${makePascalCase(info.rightModel)}", on_delete=models.CASCADE, related_name="+", db_column="B", db_index=False)`,
|
|
2965
2908
|
"",
|
|
2966
2909
|
" class Meta:",
|
|
2967
|
-
` db_table = ${toPythonString
|
|
2910
|
+
` db_table = ${toPythonString(info.tableName)}`,
|
|
2968
2911
|
" indexes = [",
|
|
2969
2912
|
" models.Index(fields=[\"b\"]),",
|
|
2970
2913
|
" ]"
|
|
2971
2914
|
].join("\n");
|
|
2972
2915
|
}
|
|
2973
2916
|
function generateManyToManyField(model, field, allModels, m2mTables, names) {
|
|
2974
|
-
const backField =
|
|
2917
|
+
const backField = backRelation(field, model, allModels);
|
|
2975
2918
|
const table = m2mTables.find((t) => t.relationName === field.relationName);
|
|
2976
2919
|
if (!table) return null;
|
|
2977
2920
|
const attrName = attrNameOf(names, model, field);
|
|
2978
|
-
const relatedName = backField ? toPythonString
|
|
2921
|
+
const relatedName = backField ? toPythonString(djangoAttrName(makeSnakeCase(backField.name))) : "\"+\"";
|
|
2979
2922
|
const targetClass = makePascalCase(field.type);
|
|
2980
2923
|
const args = [
|
|
2981
2924
|
`"${targetClass}"`,
|
|
@@ -3015,21 +2958,21 @@ function generateMetaLines(model, indexes, names) {
|
|
|
3015
2958
|
};
|
|
3016
2959
|
const uniqueIndexes = indexes.filter((idx) => idx.model === model.name && idx.type === "unique" && !idx.isDefinedOnField);
|
|
3017
2960
|
const constraints = model.uniqueFields.map((fields) => {
|
|
3018
|
-
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`)})`;
|
|
3019
2962
|
});
|
|
3020
2963
|
const indexEntries = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
|
|
3021
2964
|
const fieldNames = idx.fields.map((f) => {
|
|
3022
2965
|
const ref = fieldRef(f.name);
|
|
3023
|
-
return toPythonString
|
|
2966
|
+
return toPythonString(f.sortOrder === "desc" ? `-${ref}` : ref);
|
|
3024
2967
|
}).join(", ");
|
|
3025
|
-
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)}` : "";
|
|
3026
2969
|
const ctor = postgresIndexClass(idx.algorithm);
|
|
3027
2970
|
return ctor === null ? `models.Index(fields=[${fieldNames}]${name})` : `${ctor}(fields=[${fieldNames}]${name})`;
|
|
3028
2971
|
});
|
|
3029
2972
|
return [
|
|
3030
2973
|
"",
|
|
3031
2974
|
" class Meta:",
|
|
3032
|
-
` db_table = ${toPythonString
|
|
2975
|
+
` db_table = ${toPythonString(tableName)}`,
|
|
3033
2976
|
...constraints.length > 0 ? [
|
|
3034
2977
|
" constraints = [",
|
|
3035
2978
|
...constraints.map((c) => ` ${c},`),
|
|
@@ -3048,7 +2991,7 @@ function compositePkLine(model, names) {
|
|
|
3048
2991
|
const belongsTo = singleColumnBelongsTo(model);
|
|
3049
2992
|
return ` pk = models.CompositePrimaryKey(${pkFields.map((prismaFieldName) => {
|
|
3050
2993
|
const attr = names.attr.get(nameKey(model.name, prismaFieldName)) ?? prismaFieldName;
|
|
3051
|
-
return toPythonString
|
|
2994
|
+
return toPythonString(belongsTo.some((f) => f.relationFromFields?.[0] === prismaFieldName) ? `${attr}_id` : attr);
|
|
3052
2995
|
}).join(", ")})`;
|
|
3053
2996
|
}
|
|
3054
2997
|
function findNameConflicts(models, enums) {
|
|
@@ -3089,21 +3032,21 @@ function generateModelBody$1(model, allModels, indexes, m2mTables, names, provid
|
|
|
3089
3032
|
].join("\n");
|
|
3090
3033
|
}
|
|
3091
3034
|
function generateEnumClass(enumDef) {
|
|
3092
|
-
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");
|
|
3093
3036
|
}
|
|
3094
3037
|
function collectGlobalImports$1(models, indexes, provider) {
|
|
3095
3038
|
const scalarFields = models.flatMap((m) => m.fields.filter((f) => f.kind !== "object"));
|
|
3096
3039
|
const modelNames = new Set(models.map((m) => m.name));
|
|
3097
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);
|
|
3098
|
-
const needsUuid = scalarFields.some((f) => uuidDefaultVersion
|
|
3099
|
-
const needsUuid6 = scalarFields.some((f) => uuidDefaultVersion
|
|
3100
|
-
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));
|
|
3101
3044
|
const needsArray = scalarFields.some((f) => f.isList);
|
|
3102
3045
|
const needsRawSql = scalarFields.some((f) => dbGeneratedExpr(f) !== null);
|
|
3103
3046
|
const needsUtcField = scalarFields.some((f) => holdsUtc(f, provider));
|
|
3104
3047
|
const needsAutoNow = scalarFields.some((f) => f.isUpdatedAt);
|
|
3105
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));
|
|
3106
|
-
const nowKinds = scalarFields.filter((f) => isNowDefault$
|
|
3049
|
+
const nowKinds = scalarFields.filter((f) => isNowDefault$1(f) || f.isUpdatedAt).map((f) => dateTimeKind(f));
|
|
3107
3050
|
const nowHelperKinds = nowKinds.filter((kind) => kind !== "datetime");
|
|
3108
3051
|
const kinds = /* @__PURE__ */ new Set([
|
|
3109
3052
|
...literalKinds,
|
|
@@ -3169,16 +3112,14 @@ function djangoCode(models, enums, indexes, provider = "postgresql") {
|
|
|
3169
3112
|
//#region src/core/django.ts
|
|
3170
3113
|
function django(options) {
|
|
3171
3114
|
return Effect.gen(function* () {
|
|
3172
|
-
|
|
3173
|
-
const output = options.generator.output.value;
|
|
3174
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
3115
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Django"), "models.py");
|
|
3175
3116
|
const enums = options.dmmf.datamodel.enums;
|
|
3176
3117
|
const indexes = options.dmmf.datamodel.indexes;
|
|
3177
3118
|
const conflicts = findNameConflicts(options.dmmf.datamodel.models, enums);
|
|
3178
3119
|
if (conflicts.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Django cannot represent this schema:\n${conflicts.map((c) => ` - ${c}`).join("\n")}` });
|
|
3179
3120
|
const provider = options.datasources[0]?.activeProvider;
|
|
3180
3121
|
const code = djangoCode(options.dmmf.datamodel.models, enums, indexes, provider);
|
|
3181
|
-
return yield* emitRaw(code,
|
|
3122
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
3182
3123
|
});
|
|
3183
3124
|
}
|
|
3184
3125
|
//#endregion
|
|
@@ -3211,7 +3152,7 @@ const MYSQL_SCALAR_MAP = {
|
|
|
3211
3152
|
const SQLITE_SCALAR_MAP = {
|
|
3212
3153
|
String: "text()",
|
|
3213
3154
|
Int: "integer()",
|
|
3214
|
-
BigInt: "
|
|
3155
|
+
BigInt: "bigInteger()",
|
|
3215
3156
|
Float: "real()",
|
|
3216
3157
|
Decimal: "numeric()",
|
|
3217
3158
|
Boolean: "integer({ mode: 'boolean' })",
|
|
@@ -3283,6 +3224,11 @@ function mysqlNativeType(name, args) {
|
|
|
3283
3224
|
}
|
|
3284
3225
|
}
|
|
3285
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
|
+
})`,
|
|
3286
3232
|
bytea: `const bytea = customType<{ data: Uint8Array }>({
|
|
3287
3233
|
dataType: () => 'bytea',
|
|
3288
3234
|
})`,
|
|
@@ -3613,7 +3559,7 @@ function makeColumn(field, model, models, provider, imports, enums) {
|
|
|
3613
3559
|
if (field.isUpdatedAt || isFieldDefault(field.default) && field.default.name === "now") imports.helpers.add("utcNow");
|
|
3614
3560
|
const chain = [
|
|
3615
3561
|
field.isList && (field.kind === "scalar" || field.kind === "enum") && provider === "postgresql" ? ".array()" : "",
|
|
3616
|
-
field.isId && !hasCompositePK ? isAutoincrement && provider === "sqlite" ? ".primaryKey({ autoIncrement: true })" : ".primaryKey()" : "",
|
|
3562
|
+
field.isId && !hasCompositePK ? isAutoincrement && provider === "sqlite" && field.type !== "BigInt" ? ".primaryKey({ autoIncrement: true })" : ".primaryKey()" : "",
|
|
3617
3563
|
field.isRequired && !field.isList && !field.isId && !(isAutoincrement && provider === "postgresql") ? ".notNull()" : "",
|
|
3618
3564
|
isAutoincrement ? provider === "mysql" ? ".autoincrement()" : "" : makeDefaultChain(field, provider, imports, enums),
|
|
3619
3565
|
field.isUpdatedAt ? ".$onUpdate(utcNow)" : ""
|
|
@@ -3663,30 +3609,9 @@ function makeTable(model, models, provider, imports, enums, indexes) {
|
|
|
3663
3609
|
const constraints = makeTableConstraints(model, models, provider, imports, indexes, tableName);
|
|
3664
3610
|
return constraints ? `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, (table) => [${constraints}])` : `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
|
|
3665
3611
|
}
|
|
3666
|
-
function isImplicitM2M$1(field, models) {
|
|
3667
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
3668
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
3669
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
3670
|
-
}
|
|
3671
3612
|
function joinVarName(relationName) {
|
|
3672
3613
|
return snakeToCamel(makeSnakeCase(relationName));
|
|
3673
3614
|
}
|
|
3674
|
-
function collectM2MJoinTables(models) {
|
|
3675
|
-
const pairs = models.flatMap((model) => model.fields.filter((field) => isImplicitM2M$1(field, models)).map((field) => {
|
|
3676
|
-
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
3677
|
-
return {
|
|
3678
|
-
left,
|
|
3679
|
-
right,
|
|
3680
|
-
relationName: field.relationName ?? `${left}To${right}`
|
|
3681
|
-
};
|
|
3682
|
-
}));
|
|
3683
|
-
const seen = /* @__PURE__ */ new Set();
|
|
3684
|
-
return pairs.filter((pair) => {
|
|
3685
|
-
if (seen.has(pair.relationName)) return false;
|
|
3686
|
-
seen.add(pair.relationName);
|
|
3687
|
-
return true;
|
|
3688
|
-
});
|
|
3689
|
-
}
|
|
3690
3615
|
function withColumnName(baseExpr, colName) {
|
|
3691
3616
|
const parenIdx = baseExpr.indexOf("(");
|
|
3692
3617
|
const fnName = baseExpr.slice(0, parenIdx);
|
|
@@ -3701,7 +3626,7 @@ function pkColumnExpr(modelName, colName, models, provider, imports) {
|
|
|
3701
3626
|
}
|
|
3702
3627
|
function makeM2MJoinTables(models, provider, imports) {
|
|
3703
3628
|
const tableFunc = provider === "postgresql" ? "pgTable" : provider === "mysql" ? "mysqlTable" : "sqliteTable";
|
|
3704
|
-
return
|
|
3629
|
+
return implicitJoinTables(models).map((pair) => {
|
|
3705
3630
|
imports.core.add(tableFunc);
|
|
3706
3631
|
imports.core.add("foreignKey");
|
|
3707
3632
|
imports.core.add("index");
|
|
@@ -3726,7 +3651,7 @@ function makeM2MJoinTables(models, provider, imports) {
|
|
|
3726
3651
|
});
|
|
3727
3652
|
}
|
|
3728
3653
|
function makeM2MJoinRelations(models, imports) {
|
|
3729
|
-
const pairs =
|
|
3654
|
+
const pairs = implicitJoinTables(models);
|
|
3730
3655
|
if (pairs.length > 0) imports.orm.add("relations");
|
|
3731
3656
|
return pairs.map((pair) => {
|
|
3732
3657
|
const varName = joinVarName(pair.relationName);
|
|
@@ -3735,8 +3660,11 @@ function makeM2MJoinRelations(models, imports) {
|
|
|
3735
3660
|
const leftPk = models.find((m) => m.name === pair.left)?.fields.find((f) => f.isId);
|
|
3736
3661
|
const rightPk = models.find((m) => m.name === pair.right)?.fields.find((f) => f.isId);
|
|
3737
3662
|
const leftKey = uncapitalizeName(pair.left);
|
|
3738
|
-
const
|
|
3739
|
-
|
|
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} }) }))`;
|
|
3740
3668
|
});
|
|
3741
3669
|
}
|
|
3742
3670
|
function uncapitalizeName(name) {
|
|
@@ -3758,9 +3686,15 @@ function makeRelationField(field, model, models, relFields) {
|
|
|
3758
3686
|
return `${field.name}: one(${targetVar}, { ${configParts.join(", ")} })`;
|
|
3759
3687
|
}
|
|
3760
3688
|
if (field.isList) {
|
|
3761
|
-
if (
|
|
3689
|
+
if (isImplicitManyToMany(field, model, models)) {
|
|
3762
3690
|
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
3763
|
-
|
|
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)})`;
|
|
3764
3698
|
}
|
|
3765
3699
|
return needsAlias ? `${field.name}: many(${targetVar}, { relationName: '${field.relationName}' })` : `${field.name}: many(${targetVar})`;
|
|
3766
3700
|
}
|
|
@@ -3814,18 +3748,11 @@ function parsePrismaProvider(raw) {
|
|
|
3814
3748
|
//#region src/core/drizzle.ts
|
|
3815
3749
|
function drizzle(options) {
|
|
3816
3750
|
return Effect.gen(function* () {
|
|
3817
|
-
|
|
3751
|
+
const output = yield* requireOutput(options, "Hekireki-Drizzle");
|
|
3818
3752
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
3819
3753
|
const providerResult = parsePrismaProvider(provider);
|
|
3820
3754
|
if (!providerResult.ok) return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-Drizzle: ${provider}. Supported providers are postgresql, cockroachdb, mysql, and sqlite.` });
|
|
3821
|
-
const
|
|
3822
|
-
const resolved = path.extname(output) ? {
|
|
3823
|
-
dir: path.dirname(output),
|
|
3824
|
-
file: output
|
|
3825
|
-
} : {
|
|
3826
|
-
dir: output,
|
|
3827
|
-
file: path.join(output, "schema.ts")
|
|
3828
|
-
};
|
|
3755
|
+
const resolved = outputFile(output, "schema.ts");
|
|
3829
3756
|
const code = drizzleSchema(options.dmmf.datamodel, providerResult.value, options.dmmf.datamodel.indexes);
|
|
3830
3757
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
3831
3758
|
});
|
|
@@ -3853,18 +3780,6 @@ function prismaConstraintName(base, suffix, limit = IDENTIFIER_LIMIT) {
|
|
|
3853
3780
|
const chars = [...base.matchAll(/./gsu)].map(([char]) => char);
|
|
3854
3781
|
return `${chars.filter((_, index) => utf8Length(chars.slice(0, index + 1).join("")) <= room).join("")}${suffix}`;
|
|
3855
3782
|
}
|
|
3856
|
-
function tableName(model) {
|
|
3857
|
-
return model.dbName ?? model.name;
|
|
3858
|
-
}
|
|
3859
|
-
function columnName(field) {
|
|
3860
|
-
return field.dbName ?? field.name;
|
|
3861
|
-
}
|
|
3862
|
-
function isListDefault(def) {
|
|
3863
|
-
return Array.isArray(def);
|
|
3864
|
-
}
|
|
3865
|
-
function isFunctionDefault$5(def) {
|
|
3866
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
3867
|
-
}
|
|
3868
3783
|
function modelIndexes(model, indexes) {
|
|
3869
3784
|
const own = indexes.filter((index) => index.model === model.name);
|
|
3870
3785
|
if (own.length > 0) return own;
|
|
@@ -3902,29 +3817,6 @@ function indexName(model, index) {
|
|
|
3902
3817
|
return field ? columnName(field) : f.name;
|
|
3903
3818
|
})].join("_"), index.type === "unique" ? "_key" : "_idx");
|
|
3904
3819
|
}
|
|
3905
|
-
function backRelation(field, owner, models) {
|
|
3906
|
-
const related = models.find((m) => m.name === field.type);
|
|
3907
|
-
return related?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && f.type === owner.name && !(related.name === owner.name && f.name === field.name));
|
|
3908
|
-
}
|
|
3909
|
-
function manyToManyRelations(models) {
|
|
3910
|
-
return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
|
|
3911
|
-
const inverse = backRelation(field, model, models);
|
|
3912
|
-
const other = models.find((m) => m.name === field.type);
|
|
3913
|
-
if (!(other && inverse?.isList)) return [];
|
|
3914
|
-
if (!(model.name === other.name ? field.name < inverse.name : model.name < other.name)) return [];
|
|
3915
|
-
return [{
|
|
3916
|
-
relationName: field.relationName ?? `${model.name}To${other.name}`,
|
|
3917
|
-
a: {
|
|
3918
|
-
model,
|
|
3919
|
-
field
|
|
3920
|
-
},
|
|
3921
|
-
b: {
|
|
3922
|
-
model: other,
|
|
3923
|
-
field: inverse
|
|
3924
|
-
}
|
|
3925
|
-
}];
|
|
3926
|
-
}));
|
|
3927
|
-
}
|
|
3928
3820
|
/**
|
|
3929
3821
|
* Reads an RFC 3339 timestamp as it may stand in `@default("...")`.
|
|
3930
3822
|
*
|
|
@@ -4093,7 +3985,7 @@ function getPrimaryKeyConfig(field) {
|
|
|
4093
3985
|
foreignKeyType: null
|
|
4094
3986
|
};
|
|
4095
3987
|
}
|
|
4096
|
-
function isNowDefault
|
|
3988
|
+
function isNowDefault(field) {
|
|
4097
3989
|
const def = field.default;
|
|
4098
3990
|
return typeof def === "object" && def !== null && "name" in def && def.name === "now";
|
|
4099
3991
|
}
|
|
@@ -4133,7 +4025,7 @@ function makeTimestampsLines(fields, appName) {
|
|
|
4133
4025
|
"created_at",
|
|
4134
4026
|
"createdAt"
|
|
4135
4027
|
]);
|
|
4136
|
-
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);
|
|
4137
4029
|
const updated = fields.filter((f) => isStamped(f) && f.isUpdatedAt);
|
|
4138
4030
|
const exclude = /* @__PURE__ */ new Set([...inserted ? [inserted.name] : [], ...updated.map((f) => f.name)]);
|
|
4139
4031
|
const named = (field, ecto) => fields.some((f) => f !== field && makeSnakeCase(f.name) === ecto) ? makeSnakeCase(field.name) : ecto;
|
|
@@ -4201,49 +4093,45 @@ function getAssociations$4(model, allModels, appName) {
|
|
|
4201
4093
|
const hasMany = [];
|
|
4202
4094
|
const hasOne = [];
|
|
4203
4095
|
const manyToMany = [];
|
|
4204
|
-
for (const
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
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;
|
|
4208
4102
|
belongsTo.push({
|
|
4209
4103
|
name: field.name,
|
|
4210
4104
|
targetModel: field.type,
|
|
4211
|
-
foreignKey:
|
|
4105
|
+
foreignKey: fromFields[0],
|
|
4212
4106
|
fkType: getBelongsToFkType(allModels, field.type, field.relationToFields?.[0], appName),
|
|
4213
|
-
references: ectoFieldName(
|
|
4107
|
+
references: ectoFieldName(targetModel, field.relationToFields?.[0] ?? "id")
|
|
4214
4108
|
});
|
|
4215
4109
|
continue;
|
|
4216
4110
|
}
|
|
4217
|
-
const targetModel = allModels.find((m) => m.name === field.type);
|
|
4218
4111
|
if (!targetModel) continue;
|
|
4219
|
-
if (
|
|
4220
|
-
const
|
|
4221
|
-
|
|
4222
|
-
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
relatedKey: ectoFieldName(targetModel, targetModel.fields.find((f) => f.isId)?.name ?? "id")
|
|
4232
|
-
});
|
|
4233
|
-
continue;
|
|
4234
|
-
}
|
|
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;
|
|
4235
4124
|
}
|
|
4236
|
-
const fkField =
|
|
4237
|
-
const
|
|
4238
|
-
if (
|
|
4239
|
-
if ((fkField?.relationFromFields?.length ?? 0) > 1) continue;
|
|
4125
|
+
const fkField = end.inverse;
|
|
4126
|
+
const fromFields = fkField.relationFromFields ?? [];
|
|
4127
|
+
if (fromFields.length > 1) continue;
|
|
4240
4128
|
const association = {
|
|
4241
4129
|
name: field.name,
|
|
4242
4130
|
targetModel: field.type,
|
|
4243
|
-
foreignKey,
|
|
4244
|
-
references: ectoFieldName(model, fkField
|
|
4131
|
+
foreignKey: fromFields[0],
|
|
4132
|
+
references: ectoFieldName(model, fkField.relationToFields?.[0] ?? "id")
|
|
4245
4133
|
};
|
|
4246
|
-
if (
|
|
4134
|
+
if (end.kind === "hasMany") hasMany.push(association);
|
|
4247
4135
|
else hasOne.push(association);
|
|
4248
4136
|
}
|
|
4249
4137
|
return {
|
|
@@ -4261,6 +4149,7 @@ function ectoDefaultOption(f) {
|
|
|
4261
4149
|
if (def.name === "now") return "autogenerate: true";
|
|
4262
4150
|
if (def.name === "dbgenerated") return "read_after_writes: true";
|
|
4263
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, []}";
|
|
4264
4153
|
return null;
|
|
4265
4154
|
}
|
|
4266
4155
|
if (typeof def === "string") {
|
|
@@ -4357,8 +4246,8 @@ function foreignKeyOf(model, field, allModels) {
|
|
|
4357
4246
|
holder: field
|
|
4358
4247
|
};
|
|
4359
4248
|
const other = allModels.find((m) => m.name === field.type);
|
|
4360
|
-
const holder =
|
|
4361
|
-
return other && holder ? {
|
|
4249
|
+
const holder = backRelation(field, model, allModels);
|
|
4250
|
+
return other && holder && (holder.relationFromFields?.length ?? 0) > 0 ? {
|
|
4362
4251
|
side: "inverse",
|
|
4363
4252
|
owner: other,
|
|
4364
4253
|
holder
|
|
@@ -4910,8 +4799,7 @@ function relationMode(source) {
|
|
|
4910
4799
|
//#region src/core/ecto.ts
|
|
4911
4800
|
function ecto(options) {
|
|
4912
4801
|
return Effect.gen(function* () {
|
|
4913
|
-
|
|
4914
|
-
const outDir = options.generator.output.value;
|
|
4802
|
+
const output = yield* requireOutput(options, "Hekireki-Ecto");
|
|
4915
4803
|
const problems = ectoProblems(options.dmmf.datamodel.models);
|
|
4916
4804
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Ecto cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
4917
4805
|
const app = options.generator.config?.app ?? "MyApp";
|
|
@@ -4922,7 +4810,7 @@ function ecto(options) {
|
|
|
4922
4810
|
foreignKeyNames: relationMaps(options.datamodel),
|
|
4923
4811
|
relationMode: relationMode(options.datamodel)
|
|
4924
4812
|
});
|
|
4925
|
-
return yield* emitMany(files,
|
|
4813
|
+
return yield* emitMany(files, output);
|
|
4926
4814
|
});
|
|
4927
4815
|
}
|
|
4928
4816
|
//#endregion
|
|
@@ -5413,7 +5301,7 @@ function generatorKey(generator) {
|
|
|
5413
5301
|
return `Nanoid${generator.size}Generator`;
|
|
5414
5302
|
}
|
|
5415
5303
|
function valueGeneratorOf(field, clr) {
|
|
5416
|
-
if (!isFunctionDefault
|
|
5304
|
+
if (!isFunctionDefault(field.default) || field.isList) return null;
|
|
5417
5305
|
const isGuid = clr.clr === typeRef$1(CS.Guid);
|
|
5418
5306
|
const isString = clr.clr === "string";
|
|
5419
5307
|
const [arg] = field.default.args;
|
|
@@ -5508,7 +5396,7 @@ function literal$1(value, field, clr, names, enums) {
|
|
|
5508
5396
|
function defaultPlan$1(field, clr, names, enums) {
|
|
5509
5397
|
const def = field.default;
|
|
5510
5398
|
if (def === void 0 || def === null) return null;
|
|
5511
|
-
if (isFunctionDefault
|
|
5399
|
+
if (isFunctionDefault(def)) {
|
|
5512
5400
|
const [arg] = def.args;
|
|
5513
5401
|
if (def.name === "autoincrement") return { kind: "autoincrement" };
|
|
5514
5402
|
if (def.name === "dbgenerated") return typeof arg === "string" && arg.length > 0 ? {
|
|
@@ -6171,7 +6059,7 @@ function efcoreFiles(datamodel, options) {
|
|
|
6171
6059
|
//#region src/core/efcore.ts
|
|
6172
6060
|
function efcore(options) {
|
|
6173
6061
|
return Effect.gen(function* () {
|
|
6174
|
-
|
|
6062
|
+
const output = yield* requireOutput(options, "Hekireki-EFCore");
|
|
6175
6063
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
6176
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.` });
|
|
6177
6065
|
const namespace = getString(options.generator.config?.namespace) ?? "Models";
|
|
@@ -6183,7 +6071,7 @@ function efcore(options) {
|
|
|
6183
6071
|
context,
|
|
6184
6072
|
provider
|
|
6185
6073
|
});
|
|
6186
|
-
return yield* emitMany(files,
|
|
6074
|
+
return yield* emitMany(files, output);
|
|
6187
6075
|
});
|
|
6188
6076
|
}
|
|
6189
6077
|
//#endregion
|
|
@@ -6242,15 +6130,7 @@ function effectCode(dmmf, type, relation) {
|
|
|
6242
6130
|
//#region src/core/effect.ts
|
|
6243
6131
|
function effect(options) {
|
|
6244
6132
|
return Effect.gen(function* () {
|
|
6245
|
-
|
|
6246
|
-
const output = options.generator.output.value;
|
|
6247
|
-
const resolved = path.extname(output) ? {
|
|
6248
|
-
dir: path.dirname(output),
|
|
6249
|
-
file: output
|
|
6250
|
-
} : {
|
|
6251
|
-
dir: output,
|
|
6252
|
-
file: path.join(output, "index.ts")
|
|
6253
|
-
};
|
|
6133
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Effect"), "index.ts");
|
|
6254
6134
|
const code = effectCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
6255
6135
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
6256
6136
|
});
|
|
@@ -6383,47 +6263,42 @@ function getAssociations$3(model, allModels) {
|
|
|
6383
6263
|
const belongsToMany = [];
|
|
6384
6264
|
const ownKeyColumns = modelKey$1(model).columns;
|
|
6385
6265
|
const ownKey = ownKeyColumns.length === 1 ? ownKeyColumns[0] : null;
|
|
6386
|
-
for (const
|
|
6387
|
-
|
|
6388
|
-
|
|
6389
|
-
if (
|
|
6390
|
-
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;
|
|
6391
6272
|
const referencedField = field.relationToFields?.[0] ?? "id";
|
|
6392
6273
|
const ownerKeyColumn = targetModel ? fieldColumn(targetModel, referencedField) : referencedField;
|
|
6393
6274
|
const targetKey = targetModel ? modelKey$1(targetModel).columns : ["id"];
|
|
6394
6275
|
belongsTo.push({
|
|
6395
6276
|
name: field.name,
|
|
6396
6277
|
targetModel: field.type,
|
|
6397
|
-
foreignKeyColumn: fieldColumn(model,
|
|
6278
|
+
foreignKeyColumn: fieldColumn(model, fromFields[0]),
|
|
6398
6279
|
ownerKeyColumn: targetKey.length === 1 && targetKey[0] === ownerKeyColumn ? null : ownerKeyColumn
|
|
6399
6280
|
});
|
|
6400
6281
|
continue;
|
|
6401
6282
|
}
|
|
6402
|
-
const targetModel = allModels.find((m) => m.name === field.type);
|
|
6403
6283
|
if (!targetModel) continue;
|
|
6404
|
-
if (
|
|
6405
|
-
const
|
|
6406
|
-
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
relatedPivotKey: ownIsA ? "B" : "A"
|
|
6415
|
-
});
|
|
6416
|
-
continue;
|
|
6417
|
-
}
|
|
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;
|
|
6418
6294
|
}
|
|
6419
|
-
const fkField =
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
const
|
|
6424
|
-
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");
|
|
6425
6300
|
const localKeyColumn = referencedColumn === ownKey ? null : referencedColumn;
|
|
6426
|
-
if (
|
|
6301
|
+
if (end.kind === "hasMany") hasMany.push({
|
|
6427
6302
|
name: field.name,
|
|
6428
6303
|
targetModel: field.type,
|
|
6429
6304
|
foreignKeyColumn,
|
|
@@ -7421,14 +7296,13 @@ function eloquentModelFiles(models, namespace, enums, options = {}) {
|
|
|
7421
7296
|
//#region src/core/eloquent.ts
|
|
7422
7297
|
function eloquent(options) {
|
|
7423
7298
|
return Effect.gen(function* () {
|
|
7424
|
-
|
|
7425
|
-
const outDir = options.generator.output.value;
|
|
7299
|
+
const output = yield* requireOutput(options, "Hekireki-Eloquent");
|
|
7426
7300
|
const problems = eloquentProblems(options.dmmf.datamodel.models, options.dmmf.datamodel.enums);
|
|
7427
7301
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Eloquent cannot write this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
7428
7302
|
const namespace = options.generator.config?.namespace ?? "App\\Models";
|
|
7429
7303
|
const enums = options.dmmf.datamodel.enums;
|
|
7430
7304
|
const files = eloquentModelFiles(options.dmmf.datamodel.models, namespace, enums, { provider: options.datasources[0]?.activeProvider });
|
|
7431
|
-
return yield* emitMany(files,
|
|
7305
|
+
return yield* emitMany(files, output);
|
|
7432
7306
|
});
|
|
7433
7307
|
}
|
|
7434
7308
|
//#endregion
|
|
@@ -8798,11 +8672,8 @@ function columnOf(model, field) {
|
|
|
8798
8672
|
const found = model?.fields.find((f) => f.name === field);
|
|
8799
8673
|
return found ? dbNameOf(found) : field;
|
|
8800
8674
|
}
|
|
8801
|
-
function isFunctionDefault$4(def) {
|
|
8802
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
8803
|
-
}
|
|
8804
8675
|
function toDBMLColumn(field, enums) {
|
|
8805
|
-
const defaultName = isFunctionDefault
|
|
8676
|
+
const defaultName = isFunctionDefault(field.default) ? field.default.name : void 0;
|
|
8806
8677
|
const enumDef = field.kind === "enum" ? enums.find((e) => e.name === field.type) : void 0;
|
|
8807
8678
|
const baseType = enumDef ? dbNameOf(enumDef) : field.type;
|
|
8808
8679
|
const type = field.isList && !field.relationName ? `${baseType}[]` : baseType;
|
|
@@ -8855,7 +8726,7 @@ function makeRelations(models) {
|
|
|
8855
8726
|
return models.flatMap((model) => model.fields.filter((field) => field.relationName && field.relationToFields?.length && field.relationFromFields?.length).map((field) => {
|
|
8856
8727
|
const relationTo = field.type;
|
|
8857
8728
|
const toModel = models.find((m) => m.name === relationTo);
|
|
8858
|
-
const operator = (
|
|
8729
|
+
const operator = backRelation(field, model, models)?.isList ? ">" : "-";
|
|
8859
8730
|
const relationFromName = dbNameOf(model);
|
|
8860
8731
|
const relationToName = toModel ? dbNameOf(toModel) : relationTo;
|
|
8861
8732
|
const fromColumn = combineKeys((field.relationFromFields ?? []).map((f) => columnOf(model, f)));
|
|
@@ -9593,9 +9464,6 @@ function foreignKeys(models, keyOf, maps) {
|
|
|
9593
9464
|
function scalarFields(model) {
|
|
9594
9465
|
return model.fields.filter((f) => f.kind === "scalar" || f.kind === "enum");
|
|
9595
9466
|
}
|
|
9596
|
-
function isSameList(left, right) {
|
|
9597
|
-
return left.length === right.length && left.every((name, index) => right[index] === name);
|
|
9598
|
-
}
|
|
9599
9467
|
function conditionSql(model, condition) {
|
|
9600
9468
|
if (condition.kind === "raw") return `(${condition.sql})`;
|
|
9601
9469
|
return `(${condition.terms.map((term) => {
|
|
@@ -9613,7 +9481,7 @@ function isKeyField(schema, model, field) {
|
|
|
9613
9481
|
return keyFieldNames(schema.keyOf(model)).includes(field);
|
|
9614
9482
|
}
|
|
9615
9483
|
function isSmallserial(field) {
|
|
9616
|
-
return isFunctionDefault
|
|
9484
|
+
return isFunctionDefault(field.default) && field.default.name === "autoincrement" && field.nativeType?.[0] === "SmallInt";
|
|
9617
9485
|
}
|
|
9618
9486
|
/**
|
|
9619
9487
|
* How the DAO follows a foreign key: through its column (`referencedOn`, `referrersOn`), through
|
|
@@ -10008,7 +9876,7 @@ function defaultPlan(plan, model, field, map) {
|
|
|
10008
9876
|
expr: nowExpr(map.temporal)
|
|
10009
9877
|
} : null;
|
|
10010
9878
|
if (def === void 0 || def === null) return updatedAt;
|
|
10011
|
-
if (isFunctionDefault
|
|
9879
|
+
if (isFunctionDefault(def)) {
|
|
10012
9880
|
const [arg] = def.args;
|
|
10013
9881
|
if (def.name === "autoincrement") return field.nativeType?.[0] === "Oid" ? null : { kind: "autoincrement" };
|
|
10014
9882
|
if (def.name === "now") return {
|
|
@@ -11289,7 +11157,7 @@ function exposedFiles(datamodel, options) {
|
|
|
11289
11157
|
//#region src/core/exposed.ts
|
|
11290
11158
|
function exposed(options) {
|
|
11291
11159
|
return Effect.gen(function* () {
|
|
11292
|
-
|
|
11160
|
+
const output = yield* requireOutput(options, "Hekireki-Exposed");
|
|
11293
11161
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
11294
11162
|
if (provider !== "postgresql") return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-Exposed: ${provider}. Supported providers are postgresql.` });
|
|
11295
11163
|
const packageName = getString(options.generator.config?.package) ?? "models";
|
|
@@ -11301,7 +11169,7 @@ function exposed(options) {
|
|
|
11301
11169
|
dao: dao === "true",
|
|
11302
11170
|
source: options.datamodel
|
|
11303
11171
|
});
|
|
11304
|
-
return yield* emitMany(files,
|
|
11172
|
+
return yield* emitMany(files, output);
|
|
11305
11173
|
});
|
|
11306
11174
|
}
|
|
11307
11175
|
//#endregion
|
|
@@ -11361,61 +11229,46 @@ function getAssociations$2(model, allModels) {
|
|
|
11361
11229
|
const hasMany = [];
|
|
11362
11230
|
const hasOne = [];
|
|
11363
11231
|
const manyToMany = [];
|
|
11364
|
-
for (const
|
|
11365
|
-
|
|
11366
|
-
if (
|
|
11232
|
+
for (const end of relationEnds(model, allModels)) {
|
|
11233
|
+
const { field } = end;
|
|
11234
|
+
if (end.kind === "belongsTo") {
|
|
11235
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
11367
11236
|
belongsTo.push({
|
|
11368
11237
|
name: field.name,
|
|
11369
11238
|
targetModel: field.type,
|
|
11370
|
-
foreignKey:
|
|
11239
|
+
foreignKey: foreignKeys[0],
|
|
11371
11240
|
references: field.relationToFields?.[0] ?? "id",
|
|
11372
|
-
foreignKeys
|
|
11241
|
+
foreignKeys,
|
|
11373
11242
|
referencesList: field.relationToFields ?? ["id"],
|
|
11374
11243
|
onDelete: field.relationOnDelete,
|
|
11375
11244
|
onUpdate: field.relationOnUpdate
|
|
11376
11245
|
});
|
|
11377
11246
|
continue;
|
|
11378
11247
|
}
|
|
11379
|
-
|
|
11380
|
-
|
|
11381
|
-
|
|
11382
|
-
|
|
11383
|
-
|
|
11384
|
-
|
|
11385
|
-
|
|
11386
|
-
|
|
11387
|
-
});
|
|
11388
|
-
continue;
|
|
11389
|
-
}
|
|
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;
|
|
11390
11256
|
}
|
|
11391
|
-
const fkField =
|
|
11392
|
-
const
|
|
11393
|
-
|
|
11394
|
-
const references = fkField?.relationToFields?.[0] ?? "id";
|
|
11395
|
-
const foreignKeys = fkField?.relationFromFields ?? [foreignKey];
|
|
11396
|
-
const referencesList = fkField?.relationToFields ?? ["id"];
|
|
11397
|
-
if (field.isList) hasMany.push({
|
|
11257
|
+
const fkField = end.inverse;
|
|
11258
|
+
const foreignKeys = fkField.relationFromFields ?? [];
|
|
11259
|
+
const association = {
|
|
11398
11260
|
name: field.name,
|
|
11399
11261
|
targetModel: field.type,
|
|
11400
|
-
foreignKey,
|
|
11401
|
-
references,
|
|
11262
|
+
foreignKey: foreignKeys[0],
|
|
11263
|
+
references: fkField.relationToFields?.[0] ?? "id",
|
|
11402
11264
|
foreignKeys,
|
|
11403
|
-
referencesList,
|
|
11404
|
-
isList:
|
|
11405
|
-
onDelete: fkField
|
|
11406
|
-
onUpdate: fkField
|
|
11407
|
-
}
|
|
11408
|
-
|
|
11409
|
-
|
|
11410
|
-
targetModel: field.type,
|
|
11411
|
-
foreignKey,
|
|
11412
|
-
references,
|
|
11413
|
-
foreignKeys,
|
|
11414
|
-
referencesList,
|
|
11415
|
-
isList: false,
|
|
11416
|
-
onDelete: fkField?.relationOnDelete,
|
|
11417
|
-
onUpdate: fkField?.relationOnUpdate
|
|
11418
|
-
});
|
|
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);
|
|
11419
11272
|
}
|
|
11420
11273
|
return {
|
|
11421
11274
|
belongsTo,
|
|
@@ -11424,12 +11277,6 @@ function getAssociations$2(model, allModels) {
|
|
|
11424
11277
|
manyToMany
|
|
11425
11278
|
};
|
|
11426
11279
|
}
|
|
11427
|
-
function isFunctionDefault$3(def) {
|
|
11428
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
11429
|
-
}
|
|
11430
|
-
function isAutoincrement$2(field) {
|
|
11431
|
-
return isFunctionDefault$3(field.default) && field.default.name === "autoincrement";
|
|
11432
|
-
}
|
|
11433
11280
|
function formatGoDefault(def, type, kind) {
|
|
11434
11281
|
if (def === void 0 || def === null) return null;
|
|
11435
11282
|
if (typeof def === "boolean") return def ? "true" : "false";
|
|
@@ -11458,12 +11305,12 @@ function dateTimeGoType(field) {
|
|
|
11458
11305
|
}
|
|
11459
11306
|
function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider) {
|
|
11460
11307
|
const columnName = field.dbName ?? field.name;
|
|
11461
|
-
const isUuidDefault = isFunctionDefault
|
|
11462
|
-
const isUlidDefault = isFunctionDefault
|
|
11463
|
-
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";
|
|
11464
11311
|
const nativeType = resolveNativeType$1(field);
|
|
11465
|
-
const includeNativeType = nativeType && (!isPk || !isFunctionDefault
|
|
11466
|
-
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;
|
|
11467
11314
|
const enumMappedDefault = (() => {
|
|
11468
11315
|
if (!(field.kind === "enum" && typeof field.default === "string")) return null;
|
|
11469
11316
|
const value = enums?.find((e) => e.name === field.type)?.values.find((v) => v.name === field.default);
|
|
@@ -11483,7 +11330,7 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, pr
|
|
|
11483
11330
|
return `\`gorm:"${[
|
|
11484
11331
|
`column:${columnName}`,
|
|
11485
11332
|
isPk ? "primaryKey" : null,
|
|
11486
|
-
isPk && isAutoincrement
|
|
11333
|
+
isPk && isAutoincrement(field) ? "autoIncrement" : null,
|
|
11487
11334
|
isPk && isUuidDefault ? "type:char(36)" : null,
|
|
11488
11335
|
isPk && isUlidDefault ? "type:char(26)" : null,
|
|
11489
11336
|
field.isUnique ? "uniqueIndex" : null,
|
|
@@ -11574,7 +11421,7 @@ function goModelName(name) {
|
|
|
11574
11421
|
return splitGoWords(name).join("");
|
|
11575
11422
|
}
|
|
11576
11423
|
function generatedIdExpr$1(field) {
|
|
11577
|
-
if (!isFunctionDefault
|
|
11424
|
+
if (!isFunctionDefault(field.default)) return null;
|
|
11578
11425
|
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid.Must(uuid.NewV7()).String()" : "uuid.NewString()";
|
|
11579
11426
|
if (field.default.name === "ulid") return "ulid.MustNew(ulid.Now(), rand.Reader).String()";
|
|
11580
11427
|
if (field.default.name === "cuid") return field.default.args[0] === 2 ? "cuid2.Generate()" : "cuid.New()";
|
|
@@ -11596,7 +11443,7 @@ function generatedIdFields(model) {
|
|
|
11596
11443
|
*/
|
|
11597
11444
|
function createdTimeExpr(field) {
|
|
11598
11445
|
if (!isDateTimeScalar(field)) return null;
|
|
11599
|
-
if (field.isUpdatedAt || isFunctionDefault
|
|
11446
|
+
if (field.isUpdatedAt || isFunctionDefault(field.default) && field.default.name === "now") return "now";
|
|
11600
11447
|
if (typeof field.default !== "string") return null;
|
|
11601
11448
|
const at = new Date(field.default);
|
|
11602
11449
|
return `time.Date(${at.getUTCFullYear()}, ${at.getUTCMonth() + 1}, ${at.getUTCDate()}, ${at.getUTCHours()}, ${at.getUTCMinutes()}, ${at.getUTCSeconds()}, ${at.getUTCMilliseconds() * 1e6}, time.UTC)`;
|
|
@@ -11735,7 +11582,7 @@ function generateRelationFields(model, associations) {
|
|
|
11735
11582
|
});
|
|
11736
11583
|
const manyToManyLines = associations.manyToMany.map((assoc) => {
|
|
11737
11584
|
const joinTable = `_${assoc.relationName}`;
|
|
11738
|
-
const [own, related] =
|
|
11585
|
+
const [own, related] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
|
|
11739
11586
|
return [
|
|
11740
11587
|
goFieldName(assoc.name),
|
|
11741
11588
|
`[]${goModelName(assoc.targetModel)}`,
|
|
@@ -12069,7 +11916,7 @@ function collectImports(models) {
|
|
|
12069
11916
|
const lists = types.some((name) => name.endsWith("List"));
|
|
12070
11917
|
const fillsTimes = models.some((m) => m.fields.some((f) => createdTimeExpr(f) !== null || isDateTimeScalar(f) && f.isUpdatedAt));
|
|
12071
11918
|
const needsDatatypes = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "Json"));
|
|
12072
|
-
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] : [])));
|
|
12073
11920
|
const standard = [
|
|
12074
11921
|
generators.has("ulid") ? "\"crypto/rand\"" : null,
|
|
12075
11922
|
lists ? "\"database/sql\"" : null,
|
|
@@ -12121,16 +11968,15 @@ function generateGormModels(models, enums, indexes, packageName = "model", provi
|
|
|
12121
11968
|
//#region src/core/gorm.ts
|
|
12122
11969
|
function gorm(options) {
|
|
12123
11970
|
return Effect.gen(function* () {
|
|
12124
|
-
|
|
11971
|
+
const output = yield* requireOutput(options, "Hekireki-GORM");
|
|
12125
11972
|
const problems = gormProblems(options.dmmf.datamodel.models);
|
|
12126
11973
|
if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-GORM cannot write this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
|
|
12127
|
-
const
|
|
12128
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.go");
|
|
11974
|
+
const resolved = outputFile(output, "models.go");
|
|
12129
11975
|
const packageName = getString(options.generator.config.package) ?? "model";
|
|
12130
11976
|
const enums = options.dmmf.datamodel.enums;
|
|
12131
11977
|
const indexes = options.dmmf.datamodel.indexes;
|
|
12132
11978
|
const code = generateGormModels(options.dmmf.datamodel.models, enums, indexes, packageName, options.datasources[0]?.activeProvider);
|
|
12133
|
-
return yield* emitRaw(code,
|
|
11979
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
12134
11980
|
});
|
|
12135
11981
|
}
|
|
12136
11982
|
//#endregion
|
|
@@ -12161,11 +12007,8 @@ const CLIENT_SIDE_DEFAULTS = /* @__PURE__ */ new Set([
|
|
|
12161
12007
|
"nanoid",
|
|
12162
12008
|
"auto"
|
|
12163
12009
|
]);
|
|
12164
|
-
function isFunctionDefault$2(def) {
|
|
12165
|
-
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
12166
|
-
}
|
|
12167
12010
|
function isDbGenerated(field, provider = "postgresql") {
|
|
12168
|
-
return field.hasDefaultValue && !(isFunctionDefault
|
|
12011
|
+
return field.hasDefaultValue && !(isFunctionDefault(field.default) && CLIENT_SIDE_DEFAULTS.has(field.default.name)) && !(provider === "sqlite" && field.type === "DateTime");
|
|
12169
12012
|
}
|
|
12170
12013
|
function makeStringLiteral(value) {
|
|
12171
12014
|
return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
|
@@ -12188,30 +12031,12 @@ function makeEnumDeclarations(models, enums) {
|
|
|
12188
12031
|
const usedEnumNames = new Set(models.flatMap((m) => m.fields.filter((f) => f.kind === "enum").map((f) => f.type)));
|
|
12189
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(" | ")}`);
|
|
12190
12033
|
}
|
|
12191
|
-
function isImplicitM2M(field, models) {
|
|
12192
|
-
if (field.kind !== "object" || !field.isList) return false;
|
|
12193
|
-
if (field.relationFromFields && field.relationFromFields.length > 0) return false;
|
|
12194
|
-
return (models.find((m) => m.name === field.type)?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName))?.isList === true;
|
|
12195
|
-
}
|
|
12196
12034
|
function pkTsType(modelName, models, scalarTypes) {
|
|
12197
12035
|
const pkField = models.find((m) => m.name === modelName)?.fields.find((f) => f.isId);
|
|
12198
12036
|
return pkField ? scalarTypes[pkField.type] ?? "unknown" : "string";
|
|
12199
12037
|
}
|
|
12200
12038
|
function collectM2MJoinEntries(models, scalarTypes) {
|
|
12201
|
-
|
|
12202
|
-
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
12203
|
-
return {
|
|
12204
|
-
left,
|
|
12205
|
-
right,
|
|
12206
|
-
relationName: field.relationName ?? `${left}To${right}`
|
|
12207
|
-
};
|
|
12208
|
-
}));
|
|
12209
|
-
const seen = /* @__PURE__ */ new Set();
|
|
12210
|
-
return pairs.filter((pair) => {
|
|
12211
|
-
if (seen.has(pair.relationName)) return false;
|
|
12212
|
-
seen.add(pair.relationName);
|
|
12213
|
-
return true;
|
|
12214
|
-
}).map((pair) => ({
|
|
12039
|
+
return implicitJoinTables(models).map((pair) => ({
|
|
12215
12040
|
interfaceName: makePascalCase(makeSnakeCase(pair.relationName)),
|
|
12216
12041
|
tableName: `_${pair.relationName}`,
|
|
12217
12042
|
aType: pkTsType(pair.left, models, scalarTypes),
|
|
@@ -12257,15 +12082,7 @@ function kyselySchema(datamodel, provider = "postgresql") {
|
|
|
12257
12082
|
//#region src/core/kysely.ts
|
|
12258
12083
|
function kysely(options) {
|
|
12259
12084
|
return Effect.gen(function* () {
|
|
12260
|
-
|
|
12261
|
-
const output = options.generator.output.value;
|
|
12262
|
-
const resolved = path.extname(output) ? {
|
|
12263
|
-
dir: path.dirname(output),
|
|
12264
|
-
file: output
|
|
12265
|
-
} : {
|
|
12266
|
-
dir: output,
|
|
12267
|
-
file: path.join(output, "types.ts")
|
|
12268
|
-
};
|
|
12085
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Kysely"), "types.ts");
|
|
12269
12086
|
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
12270
12087
|
return yield* emit(kyselySchema(options.dmmf.datamodel, provider), resolved.dir, resolved.file);
|
|
12271
12088
|
});
|
|
@@ -12480,11 +12297,9 @@ function pydanticCode(models, enums, relation = false) {
|
|
|
12480
12297
|
//#region src/core/pydantic.ts
|
|
12481
12298
|
function pydantic(options) {
|
|
12482
12299
|
return Effect.gen(function* () {
|
|
12483
|
-
|
|
12484
|
-
const output = options.generator.output.value;
|
|
12485
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
12300
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Pydantic"), "models.py");
|
|
12486
12301
|
const code = pydanticCode(options.dmmf.datamodel.models, options.dmmf.datamodel.enums, getBool(options.generator.config?.relation));
|
|
12487
|
-
return yield* emitRaw(code,
|
|
12302
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
12488
12303
|
});
|
|
12489
12304
|
}
|
|
12490
12305
|
//#endregion
|
|
@@ -12642,14 +12457,8 @@ function resolveSeaOrmColumnType(field) {
|
|
|
12642
12457
|
default: return null;
|
|
12643
12458
|
}
|
|
12644
12459
|
}
|
|
12645
|
-
function isFunctionDefault$1(def) {
|
|
12646
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
12647
|
-
}
|
|
12648
|
-
function isAutoincrement$1(field) {
|
|
12649
|
-
return isFunctionDefault$1(field.default) && field.default.name === "autoincrement";
|
|
12650
|
-
}
|
|
12651
12460
|
function generatedIdExpr(field) {
|
|
12652
|
-
if (!isFunctionDefault
|
|
12461
|
+
if (!isFunctionDefault(field.default)) return null;
|
|
12653
12462
|
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid::Uuid::now_v7().to_string()" : "uuid::Uuid::new_v4().to_string()";
|
|
12654
12463
|
if (field.default.name === "ulid") return "ulid::Ulid::generate().to_string()";
|
|
12655
12464
|
return null;
|
|
@@ -12725,7 +12534,7 @@ function buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums)
|
|
|
12725
12534
|
const attrs = [];
|
|
12726
12535
|
if (isPk) {
|
|
12727
12536
|
const parts = ["primary_key"];
|
|
12728
|
-
if (!isAutoincrement
|
|
12537
|
+
if (!isAutoincrement(field)) parts.push("auto_increment = false");
|
|
12729
12538
|
attrs.push(seaOrmAttribute(" ", parts));
|
|
12730
12539
|
}
|
|
12731
12540
|
if (field.isUnique) attrs.push(" #[sea_orm(unique)]");
|
|
@@ -12746,51 +12555,40 @@ function getAssociations$1(model, allModels) {
|
|
|
12746
12555
|
const hasMany = [];
|
|
12747
12556
|
const hasOne = [];
|
|
12748
12557
|
const manyToMany = [];
|
|
12749
|
-
for (const
|
|
12750
|
-
|
|
12751
|
-
if (
|
|
12558
|
+
for (const end of relationEnds(model, allModels)) {
|
|
12559
|
+
const { field } = end;
|
|
12560
|
+
if (end.kind === "belongsTo") {
|
|
12561
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
12752
12562
|
belongsTo.push({
|
|
12753
12563
|
name: field.name,
|
|
12754
12564
|
targetModel: field.type,
|
|
12755
|
-
foreignKey:
|
|
12565
|
+
foreignKey: foreignKeys[0],
|
|
12756
12566
|
references: field.relationToFields?.[0] ?? "id",
|
|
12757
|
-
foreignKeys
|
|
12567
|
+
foreignKeys,
|
|
12758
12568
|
referencesList: field.relationToFields ?? ["id"],
|
|
12759
12569
|
onDelete: field.relationOnDelete,
|
|
12760
12570
|
onUpdate: field.relationOnUpdate
|
|
12761
12571
|
});
|
|
12762
12572
|
continue;
|
|
12763
12573
|
}
|
|
12764
|
-
|
|
12765
|
-
|
|
12766
|
-
|
|
12767
|
-
|
|
12768
|
-
|
|
12769
|
-
|
|
12770
|
-
|
|
12771
|
-
|
|
12772
|
-
});
|
|
12773
|
-
continue;
|
|
12774
|
-
}
|
|
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;
|
|
12775
12582
|
}
|
|
12776
|
-
const
|
|
12777
|
-
const foreignKey = fkField?.relationFromFields?.[0];
|
|
12778
|
-
if (!foreignKey) continue;
|
|
12779
|
-
const references = fkField?.relationToFields?.[0] ?? "id";
|
|
12780
|
-
if (field.isList) hasMany.push({
|
|
12781
|
-
name: field.name,
|
|
12782
|
-
targetModel: field.type,
|
|
12783
|
-
foreignKey,
|
|
12784
|
-
references,
|
|
12785
|
-
isList: true
|
|
12786
|
-
});
|
|
12787
|
-
else hasOne.push({
|
|
12583
|
+
const association = {
|
|
12788
12584
|
name: field.name,
|
|
12789
12585
|
targetModel: field.type,
|
|
12790
|
-
foreignKey,
|
|
12791
|
-
references,
|
|
12792
|
-
isList:
|
|
12793
|
-
}
|
|
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);
|
|
12794
12592
|
}
|
|
12795
12593
|
return {
|
|
12796
12594
|
belongsTo,
|
|
@@ -12913,6 +12711,26 @@ function generateRelatedImpls(model, associations) {
|
|
|
12913
12711
|
].join("\n"));
|
|
12914
12712
|
}
|
|
12915
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
|
+
}
|
|
12916
12734
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
12917
12735
|
emittedTargets.add(assoc.targetModel);
|
|
12918
12736
|
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
@@ -12955,7 +12773,7 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
|
|
|
12955
12773
|
fieldLines.push(...attrs, rustField(fieldName, rustType));
|
|
12956
12774
|
if (field.type !== "DateTime" || field.isList) continue;
|
|
12957
12775
|
const form = DATE_TIME_FORMS[elemType] ?? DATE_TIME_FORMS.DateTime;
|
|
12958
|
-
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;
|
|
12959
12777
|
if (value === null) continue;
|
|
12960
12778
|
stampsNow ||= value.startsWith("now");
|
|
12961
12779
|
stampsOnInsert ||= !field.isUpdatedAt;
|
|
@@ -13048,12 +12866,17 @@ function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde
|
|
|
13048
12866
|
const tableName = `_${relationName}`;
|
|
13049
12867
|
const leftModule = makeSnakeCase(sortedLeft);
|
|
13050
12868
|
const rightModule = makeSnakeCase(sortedRight);
|
|
13051
|
-
const
|
|
13052
|
-
const
|
|
13053
|
-
const
|
|
13054
|
-
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;
|
|
13055
12876
|
const leftType = pkRustType(sortedLeft, allModels);
|
|
13056
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");
|
|
13057
12880
|
const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
|
|
13058
12881
|
const deriveModel = "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]";
|
|
13059
12882
|
const serdeAttrs = buildSerdeAttributes(serde);
|
|
@@ -13075,15 +12898,15 @@ function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde
|
|
|
13075
12898
|
" #[sea_orm(",
|
|
13076
12899
|
` belongs_to = "super::${leftModule}::Entity",`,
|
|
13077
12900
|
` from = "Column::${leftCol}",`,
|
|
13078
|
-
` to = "super::${leftModule}::Column
|
|
12901
|
+
` to = "super::${leftModule}::Column::${leftKey}"`,
|
|
13079
12902
|
" )]",
|
|
13080
|
-
` ${
|
|
12903
|
+
` ${leftVariant},`,
|
|
13081
12904
|
" #[sea_orm(",
|
|
13082
12905
|
` belongs_to = "super::${rightModule}::Entity",`,
|
|
13083
12906
|
` from = "Column::${rightCol}",`,
|
|
13084
|
-
` to = "super::${rightModule}::Column
|
|
12907
|
+
` to = "super::${rightModule}::Column::${rightKey}"`,
|
|
13085
12908
|
" )]",
|
|
13086
|
-
` ${
|
|
12909
|
+
` ${rightVariant},`,
|
|
13087
12910
|
"}",
|
|
13088
12911
|
"",
|
|
13089
12912
|
"impl ActiveModelBehavior for ActiveModel {}",
|
|
@@ -13251,8 +13074,7 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
|
|
|
13251
13074
|
//#region src/core/sea-orm.ts
|
|
13252
13075
|
function seaOrm(options) {
|
|
13253
13076
|
return Effect.gen(function* () {
|
|
13254
|
-
|
|
13255
|
-
const outDir = options.generator.output.value;
|
|
13077
|
+
const output = yield* requireOutput(options, "Hekireki-SeaORM");
|
|
13256
13078
|
const serde = { renameAll: getString(options.generator.config?.renameAll) };
|
|
13257
13079
|
const enums = options.dmmf.datamodel.enums;
|
|
13258
13080
|
const models = options.dmmf.datamodel.models;
|
|
@@ -13260,7 +13082,7 @@ function seaOrm(options) {
|
|
|
13260
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.` });
|
|
13261
13083
|
const provider = options.datasources[0]?.activeProvider;
|
|
13262
13084
|
const files = seaOrmFiles(models, enums, serde, provider);
|
|
13263
|
-
return yield* emitMany(files,
|
|
13085
|
+
return yield* emitMany(files, output);
|
|
13264
13086
|
});
|
|
13265
13087
|
}
|
|
13266
13088
|
//#endregion
|
|
@@ -13321,15 +13143,7 @@ export const schema = defineSchema({
|
|
|
13321
13143
|
*/
|
|
13322
13144
|
function seed(options) {
|
|
13323
13145
|
return Effect.gen(function* () {
|
|
13324
|
-
|
|
13325
|
-
const output = options.generator.output.value;
|
|
13326
|
-
const resolved = path.extname(output) ? {
|
|
13327
|
-
dir: path.dirname(output),
|
|
13328
|
-
file: output
|
|
13329
|
-
} : {
|
|
13330
|
-
dir: output,
|
|
13331
|
-
file: path.join(output, "schema.ts")
|
|
13332
|
-
};
|
|
13146
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Seed"), "schema.ts");
|
|
13333
13147
|
return yield* emit(seedSchemaCode(options.dmmf.datamodel), resolved.dir, resolved.file);
|
|
13334
13148
|
});
|
|
13335
13149
|
}
|
|
@@ -13554,15 +13368,16 @@ function getAssociations(model, allModels) {
|
|
|
13554
13368
|
const hasMany = [];
|
|
13555
13369
|
const hasOne = [];
|
|
13556
13370
|
const manyToMany = [];
|
|
13557
|
-
for (const
|
|
13558
|
-
|
|
13559
|
-
if (
|
|
13371
|
+
for (const end of relationEnds(model, allModels)) {
|
|
13372
|
+
const { field } = end;
|
|
13373
|
+
if (end.kind === "belongsTo") {
|
|
13374
|
+
const foreignKeys = field.relationFromFields ?? [];
|
|
13560
13375
|
belongsTo.push({
|
|
13561
13376
|
name: field.name,
|
|
13562
13377
|
targetModel: field.type,
|
|
13563
|
-
foreignKey:
|
|
13378
|
+
foreignKey: foreignKeys[0],
|
|
13564
13379
|
references: field.relationToFields?.[0] ?? "id",
|
|
13565
|
-
foreignKeys
|
|
13380
|
+
foreignKeys,
|
|
13566
13381
|
referencesList: field.relationToFields ?? ["id"],
|
|
13567
13382
|
optional: !field.isRequired,
|
|
13568
13383
|
onDelete: field.relationOnDelete ?? (field.isRequired ? "Restrict" : "SetNull"),
|
|
@@ -13570,23 +13385,18 @@ function getAssociations(model, allModels) {
|
|
|
13570
13385
|
});
|
|
13571
13386
|
continue;
|
|
13572
13387
|
}
|
|
13573
|
-
|
|
13574
|
-
|
|
13575
|
-
|
|
13576
|
-
|
|
13577
|
-
|
|
13578
|
-
|
|
13579
|
-
|
|
13580
|
-
relationName: field.relationName ?? `${model.name}To${field.type}`
|
|
13581
|
-
});
|
|
13582
|
-
continue;
|
|
13583
|
-
}
|
|
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;
|
|
13584
13395
|
}
|
|
13585
|
-
const fkField =
|
|
13586
|
-
const foreignKey = fkField
|
|
13587
|
-
if (!(fkField && foreignKey)) continue;
|
|
13396
|
+
const fkField = end.inverse;
|
|
13397
|
+
const foreignKey = (fkField.relationFromFields ?? [])[0];
|
|
13588
13398
|
const onDelete = fkField.relationOnDelete ?? (fkField.isRequired ? "Restrict" : "SetNull");
|
|
13589
|
-
if (
|
|
13399
|
+
if (end.kind === "hasMany") hasMany.push({
|
|
13590
13400
|
name: field.name,
|
|
13591
13401
|
targetModel: field.type,
|
|
13592
13402
|
foreignKey,
|
|
@@ -13612,9 +13422,8 @@ function getAssociations(model, allModels) {
|
|
|
13612
13422
|
function collectManyToManyTables(allModels) {
|
|
13613
13423
|
const candidates = allModels.flatMap((model) => model.fields.flatMap((field) => {
|
|
13614
13424
|
if (field.kind !== "object" || !field.isList) return [];
|
|
13615
|
-
|
|
13616
|
-
if (!
|
|
13617
|
-
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 [];
|
|
13618
13427
|
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
13619
13428
|
const leftModelObj = allModels.find((m) => m.name === leftName);
|
|
13620
13429
|
const rightModelObj = allModels.find((m) => m.name === rightName);
|
|
@@ -13661,19 +13470,6 @@ function generateAssociationTable(info, provider) {
|
|
|
13661
13470
|
")"
|
|
13662
13471
|
].join("\n");
|
|
13663
13472
|
}
|
|
13664
|
-
function toPythonString(value) {
|
|
13665
|
-
return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
|
|
13666
|
-
}
|
|
13667
|
-
function jsonToPythonLiteral(value) {
|
|
13668
|
-
if (value === null) return "None";
|
|
13669
|
-
if (value === true) return "True";
|
|
13670
|
-
if (value === false) return "False";
|
|
13671
|
-
if (typeof value === "number") return String(value);
|
|
13672
|
-
if (typeof value === "string") return toPythonString(value);
|
|
13673
|
-
if (Array.isArray(value)) return `[${value.map(jsonToPythonLiteral).join(", ")}]`;
|
|
13674
|
-
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString(k)}: ${jsonToPythonLiteral(v)}`).join(", ")}}`;
|
|
13675
|
-
return "None";
|
|
13676
|
-
}
|
|
13677
13473
|
const SQL_ACTION = {
|
|
13678
13474
|
Cascade: "CASCADE",
|
|
13679
13475
|
SetNull: "SET NULL",
|
|
@@ -13767,12 +13563,6 @@ function serverDefault(field, enumDef, provider) {
|
|
|
13767
13563
|
const cast = field.kind === "enum" || items.length === 0 ? `::${element}[]` : "";
|
|
13768
13564
|
return `ARRAY[${items.join(", ")}]${cast}`;
|
|
13769
13565
|
}
|
|
13770
|
-
function isFunctionDefault(def) {
|
|
13771
|
-
return def !== null && typeof def === "object" && "name" in def;
|
|
13772
|
-
}
|
|
13773
|
-
function isNowDefault(field) {
|
|
13774
|
-
return field.type === "DateTime" && isFunctionDefault(field.default) && field.default.name === "now";
|
|
13775
|
-
}
|
|
13776
13566
|
function usesNativeType(models, names) {
|
|
13777
13567
|
return models.some((m) => m.fields.some((f) => names.includes(f.nativeType?.[0] ?? "")));
|
|
13778
13568
|
}
|
|
@@ -13783,16 +13573,6 @@ function usesUtcDateTime(models) {
|
|
|
13783
13573
|
"DateTime"
|
|
13784
13574
|
].includes(f.nativeType?.[0] ?? "")));
|
|
13785
13575
|
}
|
|
13786
|
-
function isAutoincrement(field) {
|
|
13787
|
-
return isFunctionDefault(field.default) && field.default.name === "autoincrement";
|
|
13788
|
-
}
|
|
13789
|
-
function uuidDefaultVersion(field) {
|
|
13790
|
-
if (!(isFunctionDefault(field.default) && field.default.name === "uuid")) return null;
|
|
13791
|
-
return field.default.args[0] === 7 ? 7 : 4;
|
|
13792
|
-
}
|
|
13793
|
-
function isUlidDefault(field) {
|
|
13794
|
-
return isFunctionDefault(field.default) && field.default.name === "ulid";
|
|
13795
|
-
}
|
|
13796
13576
|
function needsForeignKeysParam(targetModel, assocs) {
|
|
13797
13577
|
return assocs.filter((a) => a.targetModel === targetModel).length > 1;
|
|
13798
13578
|
}
|
|
@@ -13847,7 +13627,7 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, pro
|
|
|
13847
13627
|
if (isPk && isAutoincrement(field)) colArgs.push("autoincrement=True");
|
|
13848
13628
|
if (provider !== "sqlite" && field.isId && ["Int", "BigInt"].includes(field.type) && !isAutoincrement(field)) colArgs.push("autoincrement=False");
|
|
13849
13629
|
if (field.isList) colArgs.push("nullable=True");
|
|
13850
|
-
const hasNowDefault = isNowDefault(field);
|
|
13630
|
+
const hasNowDefault = isNowDefault$1(field);
|
|
13851
13631
|
const nativeName = field.nativeType?.[0];
|
|
13852
13632
|
const utcNow = nativeName === "Date" ? "lambda: utc_now().date()" : nativeName === "Time" ? "lambda: utc_now().time()" : nativeName === "Timetz" ? "lambda: utc_now().timetz()" : "utc_now";
|
|
13853
13633
|
const fsp = field.nativeType ? field.nativeType[1][0] : "3";
|
|
@@ -13999,7 +13779,7 @@ function collectGlobalImports(models, _enums, indexes, m2mTables, provider) {
|
|
|
13999
13779
|
const needsUtcDateTime = usesUtcDateTime(models);
|
|
14000
13780
|
const needsUtcTimestamp = provider === "mysql" && usesNativeType(models, ["Timestamp"]);
|
|
14001
13781
|
const needsUtcType = needsUtcDateTime || provider !== "mysql" && usesNativeType(models, ["Timestamptz"]);
|
|
14002
|
-
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));
|
|
14003
13783
|
const needsDatetime = needsUtcNow || models.some((m) => m.fields.some((f) => f.type === "DateTime" && ![
|
|
14004
13784
|
"Date",
|
|
14005
13785
|
"Time",
|
|
@@ -14203,7 +13983,7 @@ function generateBase(models, provider) {
|
|
|
14203
13983
|
"",
|
|
14204
13984
|
""
|
|
14205
13985
|
] : [];
|
|
14206
|
-
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)) ? [
|
|
14207
13987
|
"def utc_now() -> datetime:",
|
|
14208
13988
|
" return datetime.now(timezone.utc)",
|
|
14209
13989
|
"",
|
|
@@ -14246,13 +14026,11 @@ function generateSingleFile(models, enums, indexes, provider = "postgresql") {
|
|
|
14246
14026
|
//#region src/core/sqlalchemy.ts
|
|
14247
14027
|
function sqlalchemy(options) {
|
|
14248
14028
|
return Effect.gen(function* () {
|
|
14249
|
-
|
|
14250
|
-
const output = options.generator.output.value;
|
|
14251
|
-
const outPath = path.extname(output) ? output : path.join(output, "models.py");
|
|
14029
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-SQLAlchemy"), "models.py");
|
|
14252
14030
|
const enums = options.dmmf.datamodel.enums;
|
|
14253
14031
|
const indexes = options.dmmf.datamodel.indexes;
|
|
14254
14032
|
const code = generateSingleFile(options.dmmf.datamodel.models, enums, indexes, options.datasources[0]?.activeProvider);
|
|
14255
|
-
return yield* emitRaw(code,
|
|
14033
|
+
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
14256
14034
|
});
|
|
14257
14035
|
}
|
|
14258
14036
|
//#endregion
|
|
@@ -14316,15 +14094,7 @@ function typeboxCode(dmmf, type, relation) {
|
|
|
14316
14094
|
//#region src/core/typebox.ts
|
|
14317
14095
|
function typebox(options) {
|
|
14318
14096
|
return Effect.gen(function* () {
|
|
14319
|
-
|
|
14320
|
-
const output = options.generator.output.value;
|
|
14321
|
-
const resolved = path.extname(output) ? {
|
|
14322
|
-
dir: path.dirname(output),
|
|
14323
|
-
file: output
|
|
14324
|
-
} : {
|
|
14325
|
-
dir: output,
|
|
14326
|
-
file: path.join(output, "index.ts")
|
|
14327
|
-
};
|
|
14097
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-TypeBox"), "index.ts");
|
|
14328
14098
|
const code = typeboxCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
14329
14099
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14330
14100
|
});
|
|
@@ -14382,15 +14152,7 @@ function valibotCode(dmmf, type, relation) {
|
|
|
14382
14152
|
//#region src/core/valibot.ts
|
|
14383
14153
|
function valibot(options) {
|
|
14384
14154
|
return Effect.gen(function* () {
|
|
14385
|
-
|
|
14386
|
-
const output = options.generator.output.value;
|
|
14387
|
-
const resolved = path.extname(output) ? {
|
|
14388
|
-
dir: path.dirname(output),
|
|
14389
|
-
file: output
|
|
14390
|
-
} : {
|
|
14391
|
-
dir: output,
|
|
14392
|
-
file: path.join(output, "index.ts")
|
|
14393
|
-
};
|
|
14155
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Valibot"), "index.ts");
|
|
14394
14156
|
const code = valibotCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation));
|
|
14395
14157
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14396
14158
|
});
|
|
@@ -14448,15 +14210,7 @@ function zodCode(dmmf, type, relation, version) {
|
|
|
14448
14210
|
//#region src/core/zod.ts
|
|
14449
14211
|
function zod(options) {
|
|
14450
14212
|
return Effect.gen(function* () {
|
|
14451
|
-
|
|
14452
|
-
const output = options.generator.output.value;
|
|
14453
|
-
const resolved = path.extname(output) ? {
|
|
14454
|
-
dir: path.dirname(output),
|
|
14455
|
-
file: output
|
|
14456
|
-
} : {
|
|
14457
|
-
dir: output,
|
|
14458
|
-
file: path.join(output, "index.ts")
|
|
14459
|
-
};
|
|
14213
|
+
const resolved = outputFile(yield* requireOutput(options, "Hekireki-Zod"), "index.ts");
|
|
14460
14214
|
const code = zodCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.relation), getString(options.generator.config?.zod) ?? "v4");
|
|
14461
14215
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
14462
14216
|
});
|
|
@@ -14559,7 +14313,7 @@ function registerGenerator(name) {
|
|
|
14559
14313
|
};
|
|
14560
14314
|
},
|
|
14561
14315
|
onGenerate(options) {
|
|
14562
|
-
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)));
|
|
14563
14317
|
}
|
|
14564
14318
|
});
|
|
14565
14319
|
}
|