hekireki 0.20.2 → 0.22.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 +63 -314
- 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.d.ts +1 -0
- package/dist/bin/efcore.js +6 -0
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.js +1 -1
- package/dist/bin/er.js +1 -1
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/hekireki.js +1 -1
- 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/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-CjbhMZs0.js → bin-DxYpJikH.js} +1475 -44
- package/dist/studio/assets/{chip-CLdO-gL5.js → chip-B9UolvIl.js} +1 -1
- package/dist/studio/assets/{copy-CcAufM8p.js → copy-DiFFafx_.js} +1 -1
- package/dist/studio/assets/{debounce-T36H3Pq5.js → debounce-WjLaYdFF.js} +1 -1
- package/dist/studio/assets/{docs-DW8-viIy.js → docs-D2Vpbqbg.js} +1 -1
- package/dist/studio/assets/{enums._name-C2s5pbQ3.js → enums._name-t90NJ6-H.js} +1 -1
- package/dist/studio/assets/hooks-UJuF1mqe.js +1 -0
- package/dist/studio/assets/{index-BP1uJf2T.js → index-C29_CUjj.js} +3 -3
- package/dist/studio/assets/{labels-BXtM_faz.js → labels-D0IhxSmD.js} +1 -1
- package/dist/studio/assets/{lazyRouteComponent-C6zg30cR.js → lazyRouteComponent-G8mNaW9J.js} +1 -1
- package/dist/studio/assets/{lu-BKd2Ee9U.js → lu-DvK-u3Mx.js} +1 -1
- package/dist/studio/assets/{models._name-BgQ9M7k3.js → models._name-DUEsQrdC.js} +1 -1
- package/dist/studio/assets/{not-found-OmQoujxN.js → not-found-Dr2QuAjv.js} +1 -1
- package/dist/studio/assets/{prisma-BbI26USq.js → prisma-Co828tLd.js} +1 -1
- package/dist/studio/assets/routes-BIbzUF01.js +1 -0
- package/dist/studio/assets/{schema-gate-Dq_XVfAD.js → schema-gate-Bad9LKCZ.js} +1 -1
- package/dist/studio/assets/{schema-view-BuWOw5GX.js → schema-view-nCetSUyn.js} +1 -1
- package/dist/studio/assets/{sql--CSU_IR2.js → sql-Db9voX3l.js} +1 -1
- package/dist/studio/assets/{table-Dfy6EciQ.js → table-BfaXyuqp.js} +1 -1
- package/dist/studio/assets/{tabs-Ce14hvOa.js → tabs-BXvBDUhR.js} +1 -1
- package/dist/studio/assets/{useFormValidation-gdk4CRGT.js → useFormValidation-D6Nfw1Ec.js} +1 -1
- package/dist/studio/assets/{useMatch-CdyJXF1Q.js → useMatch-BZSBUGcY.js} +1 -1
- package/dist/studio/assets/{useMultipleSelectionState-a9-PqoPk.js → useMultipleSelectionState-Bz2aFLv7.js} +1 -1
- package/dist/studio/assets/{useOverlayTriggerState-DCPjC07T.js → useOverlayTriggerState-C-S92dgf.js} +1 -1
- package/dist/studio/index.html +8 -8
- package/package.json +10 -6
- package/dist/studio/assets/hooks-Ctp_pGlY.js +0 -1
- package/dist/studio/assets/routes-Bp4Bkwc2.js +0 -1
|
@@ -503,7 +503,7 @@ function tableRef(target, models, defaultSchema) {
|
|
|
503
503
|
const name = tableNameOf(target);
|
|
504
504
|
return duplicateTableNames(models).has(name) ? `table${refPart(schemaOf(target, defaultSchema))}${refPart(name)}` : `table${refPart(name)}`;
|
|
505
505
|
}
|
|
506
|
-
function isFunctionDefault$
|
|
506
|
+
function isFunctionDefault$7(def) {
|
|
507
507
|
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
508
508
|
}
|
|
509
509
|
function pgNativeType$1(name, args) {
|
|
@@ -749,7 +749,7 @@ function listDefault(items, field, dialect, enums) {
|
|
|
749
749
|
function resolveDefault(field, dialect, enums) {
|
|
750
750
|
const dflt = field.default;
|
|
751
751
|
if (!field.hasDefaultValue || dflt === void 0 || dflt === null) return void 0;
|
|
752
|
-
if (isFunctionDefault$
|
|
752
|
+
if (isFunctionDefault$7(dflt)) {
|
|
753
753
|
if (dflt.name === "now") return dialect === "mysql" ? sqlExpr("CURRENT_TIMESTAMP(3)") : sqlExpr("CURRENT_TIMESTAMP");
|
|
754
754
|
if (dflt.name === "dbgenerated") return typeof dflt.args[0] === "string" ? sqlExpr(dflt.args[0]) : void 0;
|
|
755
755
|
return;
|
|
@@ -764,7 +764,7 @@ function resolveDefault(field, dialect, enums) {
|
|
|
764
764
|
}
|
|
765
765
|
function makeAtlasColumn(field, dialect, enums, comment) {
|
|
766
766
|
const name = field.dbName ?? field.name;
|
|
767
|
-
const isAutoincrement = isFunctionDefault$
|
|
767
|
+
const isAutoincrement = isFunctionDefault$7(field.default) && field.default.name === "autoincrement";
|
|
768
768
|
const typeInfo = columnTypeInfo(field, dialect, enums, isAutoincrement);
|
|
769
769
|
const defaultValue = isAutoincrement ? void 0 : resolveDefault(field, dialect, enums);
|
|
770
770
|
const doc = comment ? stripAnnotations(field.documentation) : void 0;
|
|
@@ -1182,24 +1182,24 @@ function jsonToPythonLiteral$1(value) {
|
|
|
1182
1182
|
if (typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${toPythonString$1(k)}: ${jsonToPythonLiteral$1(v)}`).join(", ")}}`;
|
|
1183
1183
|
return "None";
|
|
1184
1184
|
}
|
|
1185
|
-
function isFunctionDefault$
|
|
1185
|
+
function isFunctionDefault$6(def) {
|
|
1186
1186
|
return def !== null && typeof def === "object" && "name" in def && !Array.isArray(def);
|
|
1187
1187
|
}
|
|
1188
1188
|
function isAutoincrement$3(field) {
|
|
1189
|
-
return isFunctionDefault$
|
|
1189
|
+
return isFunctionDefault$6(field.default) && field.default.name === "autoincrement";
|
|
1190
1190
|
}
|
|
1191
1191
|
function uuidDefaultVersion$1(field) {
|
|
1192
|
-
if (!(isFunctionDefault$
|
|
1192
|
+
if (!(isFunctionDefault$6(field.default) && field.default.name === "uuid")) return null;
|
|
1193
1193
|
return field.default.args[0] === 7 ? 7 : 4;
|
|
1194
1194
|
}
|
|
1195
1195
|
function isUlidDefault$1(field) {
|
|
1196
|
-
return isFunctionDefault$
|
|
1196
|
+
return isFunctionDefault$6(field.default) && field.default.name === "ulid";
|
|
1197
1197
|
}
|
|
1198
1198
|
function isNowDefault(field) {
|
|
1199
|
-
return field.type === "DateTime" && isFunctionDefault$
|
|
1199
|
+
return field.type === "DateTime" && isFunctionDefault$6(field.default) && field.default.name === "now";
|
|
1200
1200
|
}
|
|
1201
1201
|
function dbGeneratedExpr(field) {
|
|
1202
|
-
return isFunctionDefault$
|
|
1202
|
+
return isFunctionDefault$6(field.default) && field.default.name === "dbgenerated" && typeof field.default.args[0] === "string" ? field.default.args[0] : null;
|
|
1203
1203
|
}
|
|
1204
1204
|
function scalarElementLiteral(type, value) {
|
|
1205
1205
|
if (typeof value === "boolean") return value ? "True" : "False";
|
|
@@ -1320,7 +1320,7 @@ function formatDefaultArgs(model, field, isPk, names) {
|
|
|
1320
1320
|
if (isUlidDefault$1(field)) return ["default=ulid_str"];
|
|
1321
1321
|
const def = field.default;
|
|
1322
1322
|
if (def === void 0 || def === null) return [];
|
|
1323
|
-
if (isFunctionDefault$
|
|
1323
|
+
if (isFunctionDefault$6(def)) return [];
|
|
1324
1324
|
if (Array.isArray(def)) return def.length === 0 ? ["default=list"] : [`default=${helperNameOf(names, model, field)}`];
|
|
1325
1325
|
if (field.kind === "enum" && typeof def === "string") return [`default=${makePascalCase(field.type)}.${enumMemberName(def)}`];
|
|
1326
1326
|
if (isPk) return [];
|
|
@@ -2594,6 +2594,1401 @@ function ecto(options) {
|
|
|
2594
2594
|
});
|
|
2595
2595
|
}
|
|
2596
2596
|
//#endregion
|
|
2597
|
+
//#region src/helper/humanizer.ts
|
|
2598
|
+
function irregular(singular, plural) {
|
|
2599
|
+
return {
|
|
2600
|
+
plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
|
|
2601
|
+
singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
function wholeWordIrregular(singular, plural) {
|
|
2605
|
+
return {
|
|
2606
|
+
plural: [`^${singular}$`, plural],
|
|
2607
|
+
singular: [`^${plural}$`, singular]
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
const IRREGULARS = [
|
|
2611
|
+
irregular("person", "people"),
|
|
2612
|
+
irregular("man", "men"),
|
|
2613
|
+
irregular("human", "humans"),
|
|
2614
|
+
irregular("child", "children"),
|
|
2615
|
+
irregular("sex", "sexes"),
|
|
2616
|
+
irregular("glove", "gloves"),
|
|
2617
|
+
irregular("move", "moves"),
|
|
2618
|
+
irregular("goose", "geese"),
|
|
2619
|
+
irregular("wave", "waves"),
|
|
2620
|
+
irregular("foot", "feet"),
|
|
2621
|
+
irregular("tooth", "teeth"),
|
|
2622
|
+
irregular("curriculum", "curricula"),
|
|
2623
|
+
irregular("database", "databases"),
|
|
2624
|
+
irregular("zombie", "zombies"),
|
|
2625
|
+
irregular("personnel", "personnel"),
|
|
2626
|
+
irregular("cache", "caches"),
|
|
2627
|
+
wholeWordIrregular("ex", "exes"),
|
|
2628
|
+
wholeWordIrregular("is", "are"),
|
|
2629
|
+
wholeWordIrregular("that", "those"),
|
|
2630
|
+
wholeWordIrregular("this", "these"),
|
|
2631
|
+
wholeWordIrregular("bus", "buses"),
|
|
2632
|
+
wholeWordIrregular("die", "dice"),
|
|
2633
|
+
wholeWordIrregular("tie", "ties")
|
|
2634
|
+
];
|
|
2635
|
+
const PLURAL_RULES = [
|
|
2636
|
+
["$", "s"],
|
|
2637
|
+
["s$", "s"],
|
|
2638
|
+
["(ax|test)is$", "$1es"],
|
|
2639
|
+
["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
|
|
2640
|
+
["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
|
|
2641
|
+
["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
|
|
2642
|
+
["([dti])um$", "$1a"],
|
|
2643
|
+
["sis$", "ses"],
|
|
2644
|
+
["(?:([^f])fe|([lr])f)$", "$1$2ves"],
|
|
2645
|
+
["(hive)$", "$1s"],
|
|
2646
|
+
["([^aeiouy]|qu)y$", "$1ies"],
|
|
2647
|
+
["(x|ch|ss|sh)$", "$1es"],
|
|
2648
|
+
["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
|
|
2649
|
+
["(^[m|l])ouse$", "$1ice"],
|
|
2650
|
+
["^(ox)$", "$1en"],
|
|
2651
|
+
["(quiz)$", "$1zes"],
|
|
2652
|
+
["(buz|blit|walt)z$", "$1zes"],
|
|
2653
|
+
["(hoo|lea|loa|thie)f$", "$1ves"],
|
|
2654
|
+
["(alumn|alg|larv|vertebr)a$", "$1ae"],
|
|
2655
|
+
["(criteri|phenomen)on$", "$1a"],
|
|
2656
|
+
...IRREGULARS.map((rule) => rule.plural)
|
|
2657
|
+
].map(([pattern, replacement]) => ({
|
|
2658
|
+
pattern: new RegExp(pattern, "iu"),
|
|
2659
|
+
replacement
|
|
2660
|
+
}));
|
|
2661
|
+
const SINGULAR_RULES = [
|
|
2662
|
+
["s$", ""],
|
|
2663
|
+
["(n)ews$", "$1ews"],
|
|
2664
|
+
["([dti])a$", "$1um"],
|
|
2665
|
+
["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
|
|
2666
|
+
["([^f])ves$", "$1fe"],
|
|
2667
|
+
["(hive)s$", "$1"],
|
|
2668
|
+
["(tive)s$", "$1"],
|
|
2669
|
+
["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
|
|
2670
|
+
["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
|
|
2671
|
+
["(s)eries$", "$1eries"],
|
|
2672
|
+
["(m)ovies$", "$1ovie"],
|
|
2673
|
+
["(x|ch|ss|sh)es$", "$1"],
|
|
2674
|
+
["(^[m|l])ice$", "$1ouse"],
|
|
2675
|
+
["(?<!^[a-z])(o)es$", "$1"],
|
|
2676
|
+
["(shoe)s$", "$1"],
|
|
2677
|
+
["(cris|ax|test)es$", "$1is"],
|
|
2678
|
+
["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
|
|
2679
|
+
["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
|
|
2680
|
+
["^(ox)en", "$1"],
|
|
2681
|
+
["(matr|d)ices$", "$1ix"],
|
|
2682
|
+
["(vert|ind)ices$", "$1ex"],
|
|
2683
|
+
["(quiz)zes$", "$1"],
|
|
2684
|
+
["(buz|blit|walt)zes$", "$1z"],
|
|
2685
|
+
["(alumn|alg|larv|vertebr)ae$", "$1a"],
|
|
2686
|
+
["(criteri|phenomen)a$", "$1on"],
|
|
2687
|
+
["([b|r|c]ook|room|smooth)ies$", "$1ie"],
|
|
2688
|
+
...IRREGULARS.map((rule) => rule.singular)
|
|
2689
|
+
].map(([pattern, replacement]) => ({
|
|
2690
|
+
pattern: new RegExp(pattern, "iu"),
|
|
2691
|
+
replacement
|
|
2692
|
+
}));
|
|
2693
|
+
const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
|
|
2694
|
+
"staff",
|
|
2695
|
+
"training",
|
|
2696
|
+
"equipment",
|
|
2697
|
+
"information",
|
|
2698
|
+
"corn",
|
|
2699
|
+
"milk",
|
|
2700
|
+
"rice",
|
|
2701
|
+
"money",
|
|
2702
|
+
"species",
|
|
2703
|
+
"series",
|
|
2704
|
+
"fish",
|
|
2705
|
+
"sheep",
|
|
2706
|
+
"deer",
|
|
2707
|
+
"aircraft",
|
|
2708
|
+
"oz",
|
|
2709
|
+
"tsp",
|
|
2710
|
+
"tbsp",
|
|
2711
|
+
"ml",
|
|
2712
|
+
"l",
|
|
2713
|
+
"water",
|
|
2714
|
+
"waters",
|
|
2715
|
+
"semen",
|
|
2716
|
+
"sperm",
|
|
2717
|
+
"bison",
|
|
2718
|
+
"grass",
|
|
2719
|
+
"hair",
|
|
2720
|
+
"mud",
|
|
2721
|
+
"elk",
|
|
2722
|
+
"luggage",
|
|
2723
|
+
"moose",
|
|
2724
|
+
"offspring",
|
|
2725
|
+
"salmon",
|
|
2726
|
+
"shrimp",
|
|
2727
|
+
"someone",
|
|
2728
|
+
"swine",
|
|
2729
|
+
"trout",
|
|
2730
|
+
"tuna",
|
|
2731
|
+
"corps",
|
|
2732
|
+
"scissors",
|
|
2733
|
+
"means",
|
|
2734
|
+
"mail",
|
|
2735
|
+
"metadata"
|
|
2736
|
+
]);
|
|
2737
|
+
function isUpperCaseLetter(char) {
|
|
2738
|
+
return char !== char.toLowerCase() && char === char.toUpperCase();
|
|
2739
|
+
}
|
|
2740
|
+
function isLowerCaseLetter(char) {
|
|
2741
|
+
return char !== char.toUpperCase() && char === char.toLowerCase();
|
|
2742
|
+
}
|
|
2743
|
+
function applyRules(rules, word) {
|
|
2744
|
+
if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
|
|
2745
|
+
const rule = rules.findLast((candidate) => candidate.pattern.test(word));
|
|
2746
|
+
if (rule === void 0) return null;
|
|
2747
|
+
const result = word.replace(rule.pattern, rule.replacement);
|
|
2748
|
+
const first = result.charAt(0);
|
|
2749
|
+
return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
|
|
2753
|
+
* is returned as it is.
|
|
2754
|
+
*
|
|
2755
|
+
* @param word - The word to pluralize.
|
|
2756
|
+
* @returns The plural form Humanizer 2.14.1 gives.
|
|
2757
|
+
*/
|
|
2758
|
+
function pluralize(word) {
|
|
2759
|
+
const result = applyRules(PLURAL_RULES, word);
|
|
2760
|
+
const asSingular = applyRules(SINGULAR_RULES, word);
|
|
2761
|
+
const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
|
|
2762
|
+
return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
|
|
2763
|
+
}
|
|
2764
|
+
//#endregion
|
|
2765
|
+
//#region src/helper/efcore.ts
|
|
2766
|
+
const REF = "\0";
|
|
2767
|
+
function typeRef(fullName) {
|
|
2768
|
+
return `${REF}T|${fullName}${REF}`;
|
|
2769
|
+
}
|
|
2770
|
+
function exprRef(fullName) {
|
|
2771
|
+
return `${REF}E|${fullName}${REF}`;
|
|
2772
|
+
}
|
|
2773
|
+
const CS = {
|
|
2774
|
+
BitArray: "System.Collections.BitArray",
|
|
2775
|
+
CancellationToken: "System.Threading.CancellationToken",
|
|
2776
|
+
Convert: "System.Convert",
|
|
2777
|
+
Cuid: "Visus.Cuid.Cuid",
|
|
2778
|
+
Cuid2: "Visus.Cuid.Cuid2",
|
|
2779
|
+
DateOnly: "System.DateOnly",
|
|
2780
|
+
DateTime: "System.DateTime",
|
|
2781
|
+
DateTimeKind: "System.DateTimeKind",
|
|
2782
|
+
DateTimeOffset: "System.DateTimeOffset",
|
|
2783
|
+
DbContext: "Microsoft.EntityFrameworkCore.DbContext",
|
|
2784
|
+
DbContextOptions: "Microsoft.EntityFrameworkCore.DbContextOptions",
|
|
2785
|
+
DbSet: "Microsoft.EntityFrameworkCore.DbSet",
|
|
2786
|
+
DeleteBehavior: "Microsoft.EntityFrameworkCore.DeleteBehavior",
|
|
2787
|
+
Dictionary: "System.Collections.Generic.Dictionary",
|
|
2788
|
+
EntityEntry: "Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry",
|
|
2789
|
+
EntityState: "Microsoft.EntityFrameworkCore.EntityState",
|
|
2790
|
+
ForeignKeyIndexConvention: "Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyIndexConvention",
|
|
2791
|
+
Guid: "System.Guid",
|
|
2792
|
+
ICollection: "System.Collections.Generic.ICollection",
|
|
2793
|
+
List: "System.Collections.Generic.List",
|
|
2794
|
+
ModelBuilder: "Microsoft.EntityFrameworkCore.ModelBuilder",
|
|
2795
|
+
ModelConfigurationBuilder: "Microsoft.EntityFrameworkCore.ModelConfigurationBuilder",
|
|
2796
|
+
NpgsqlDataSourceBuilder: "Npgsql.NpgsqlDataSourceBuilder",
|
|
2797
|
+
NpgsqlDbContextOptionsBuilder: "Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.NpgsqlDbContextOptionsBuilder",
|
|
2798
|
+
NpgsqlInet: "NpgsqlTypes.NpgsqlInet",
|
|
2799
|
+
NpgsqlValueGenerationStrategy: "Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.NpgsqlValueGenerationStrategy",
|
|
2800
|
+
PgName: "NpgsqlTypes.PgName",
|
|
2801
|
+
RandomNumberGenerator: "System.Security.Cryptography.RandomNumberGenerator",
|
|
2802
|
+
Task: "System.Threading.Tasks.Task",
|
|
2803
|
+
TimeOnly: "System.TimeOnly",
|
|
2804
|
+
Ulid: "System.Ulid",
|
|
2805
|
+
ValueGenerator: "Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator"
|
|
2806
|
+
};
|
|
2807
|
+
const CSHARP_KEYWORDS = /* @__PURE__ */ new Set([
|
|
2808
|
+
"abstract",
|
|
2809
|
+
"as",
|
|
2810
|
+
"base",
|
|
2811
|
+
"bool",
|
|
2812
|
+
"break",
|
|
2813
|
+
"byte",
|
|
2814
|
+
"case",
|
|
2815
|
+
"catch",
|
|
2816
|
+
"char",
|
|
2817
|
+
"checked",
|
|
2818
|
+
"class",
|
|
2819
|
+
"const",
|
|
2820
|
+
"continue",
|
|
2821
|
+
"decimal",
|
|
2822
|
+
"default",
|
|
2823
|
+
"delegate",
|
|
2824
|
+
"do",
|
|
2825
|
+
"double",
|
|
2826
|
+
"else",
|
|
2827
|
+
"enum",
|
|
2828
|
+
"event",
|
|
2829
|
+
"explicit",
|
|
2830
|
+
"extern",
|
|
2831
|
+
"false",
|
|
2832
|
+
"finally",
|
|
2833
|
+
"fixed",
|
|
2834
|
+
"float",
|
|
2835
|
+
"for",
|
|
2836
|
+
"foreach",
|
|
2837
|
+
"goto",
|
|
2838
|
+
"if",
|
|
2839
|
+
"implicit",
|
|
2840
|
+
"in",
|
|
2841
|
+
"int",
|
|
2842
|
+
"interface",
|
|
2843
|
+
"internal",
|
|
2844
|
+
"is",
|
|
2845
|
+
"lock",
|
|
2846
|
+
"long",
|
|
2847
|
+
"namespace",
|
|
2848
|
+
"new",
|
|
2849
|
+
"null",
|
|
2850
|
+
"object",
|
|
2851
|
+
"operator",
|
|
2852
|
+
"out",
|
|
2853
|
+
"override",
|
|
2854
|
+
"params",
|
|
2855
|
+
"private",
|
|
2856
|
+
"protected",
|
|
2857
|
+
"public",
|
|
2858
|
+
"readonly",
|
|
2859
|
+
"ref",
|
|
2860
|
+
"return",
|
|
2861
|
+
"sbyte",
|
|
2862
|
+
"sealed",
|
|
2863
|
+
"short",
|
|
2864
|
+
"sizeof",
|
|
2865
|
+
"stackalloc",
|
|
2866
|
+
"static",
|
|
2867
|
+
"string",
|
|
2868
|
+
"struct",
|
|
2869
|
+
"switch",
|
|
2870
|
+
"this",
|
|
2871
|
+
"throw",
|
|
2872
|
+
"true",
|
|
2873
|
+
"try",
|
|
2874
|
+
"typeof",
|
|
2875
|
+
"uint",
|
|
2876
|
+
"ulong",
|
|
2877
|
+
"unchecked",
|
|
2878
|
+
"unsafe",
|
|
2879
|
+
"ushort",
|
|
2880
|
+
"using",
|
|
2881
|
+
"virtual",
|
|
2882
|
+
"void",
|
|
2883
|
+
"volatile",
|
|
2884
|
+
"while"
|
|
2885
|
+
]);
|
|
2886
|
+
/**
|
|
2887
|
+
* Checks a name written in the generator block — one segment of a namespace, or a class name.
|
|
2888
|
+
*
|
|
2889
|
+
* @param name - The name as written.
|
|
2890
|
+
* @returns Whether it is an ASCII C# identifier that is not a keyword.
|
|
2891
|
+
*/
|
|
2892
|
+
function isCSharpIdentifier(name) {
|
|
2893
|
+
return /^[A-Z_a-z]\w*$/u.test(name) && !CSHARP_KEYWORDS.has(name);
|
|
2894
|
+
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Checks a class name written in the generator block: an identifier C# accepts as the name of a
|
|
2897
|
+
* type without a warning — it warns on one in lower-case letters only (CS8981), which also covers
|
|
2898
|
+
* the contextual keywords it forbids as type names (`record`, `file`, `required`, `scoped`).
|
|
2899
|
+
*
|
|
2900
|
+
* @param name - The name as written.
|
|
2901
|
+
* @returns Whether it can name the DbContext.
|
|
2902
|
+
*/
|
|
2903
|
+
function isCSharpTypeName(name) {
|
|
2904
|
+
return isCSharpIdentifier(name) && !/^[a-z]+$/u.test(name);
|
|
2905
|
+
}
|
|
2906
|
+
function codeUnits(value) {
|
|
2907
|
+
return Array.from({ length: value.length }, (_, index) => value.charAt(index));
|
|
2908
|
+
}
|
|
2909
|
+
/**
|
|
2910
|
+
* A Prisma name as a C# one: the underscores join words, each word starts in upper case, and a word
|
|
2911
|
+
* in capitals throughout (`PENDING`, `ID`) is lower-cased after its first letter; any other casing
|
|
2912
|
+
* is the schema author's and is kept (`sku_code` → `SkuCode`, `userID` → `UserID`,
|
|
2913
|
+
* `PENDING_REVIEW` → `PendingReview`).
|
|
2914
|
+
*
|
|
2915
|
+
* @param name - A Prisma model, field or enum value name.
|
|
2916
|
+
* @returns The PascalCase name.
|
|
2917
|
+
*/
|
|
2918
|
+
function pascalCase(name) {
|
|
2919
|
+
const text = name.split("_").filter((word) => word !== "").map((word) => {
|
|
2920
|
+
const rest = word.slice(1);
|
|
2921
|
+
return `${word.charAt(0).toUpperCase()}${word === word.toUpperCase() ? rest.toLowerCase() : rest}`;
|
|
2922
|
+
}).join("");
|
|
2923
|
+
return /^\p{L}/u.test(text) ? text : `_${text}`;
|
|
2924
|
+
}
|
|
2925
|
+
/**
|
|
2926
|
+
* The first of `candidate`, `candidate1`, `candidate2`, ... that is free — the numbering
|
|
2927
|
+
* `dotnet ef dbcontext scaffold` gives names that collide.
|
|
2928
|
+
*
|
|
2929
|
+
* @param candidate - The preferred name.
|
|
2930
|
+
* @param isTaken - Whether a name is already in use.
|
|
2931
|
+
* @returns A free name.
|
|
2932
|
+
*/
|
|
2933
|
+
function uniqueName(candidate, isTaken) {
|
|
2934
|
+
if (!isTaken(candidate)) return candidate;
|
|
2935
|
+
return `${candidate}${Array.from({ length: 1e4 }, (_, index) => index + 1).find((index) => !isTaken(`${candidate}${index}`)) ?? ""}`;
|
|
2936
|
+
}
|
|
2937
|
+
function allocate(candidates, reserved, fold) {
|
|
2938
|
+
return candidates.reduce((acc, { key, candidate }) => {
|
|
2939
|
+
const name = uniqueName(candidate, (taken) => acc.taken.has(fold(taken)));
|
|
2940
|
+
return {
|
|
2941
|
+
names: new Map([...acc.names, [key, name]]),
|
|
2942
|
+
taken: /* @__PURE__ */ new Set([...acc.taken, fold(name)])
|
|
2943
|
+
};
|
|
2944
|
+
}, {
|
|
2945
|
+
names: /* @__PURE__ */ new Map(),
|
|
2946
|
+
taken: new Set(reserved.map(fold))
|
|
2947
|
+
}).names;
|
|
2948
|
+
}
|
|
2949
|
+
function csharpString(value) {
|
|
2950
|
+
return `"${codeUnits(value).map((char) => {
|
|
2951
|
+
const code = char.codePointAt(0) ?? 0;
|
|
2952
|
+
if (char === "\\") return "\\\\";
|
|
2953
|
+
if (char === "\"") return "\\\"";
|
|
2954
|
+
if (char === "\n") return "\\n";
|
|
2955
|
+
if (char === "\r") return "\\r";
|
|
2956
|
+
if (char === " ") return "\\t";
|
|
2957
|
+
if (char === "\0") return "\\0";
|
|
2958
|
+
if (code < 32 || code >= 127 && code <= 159 || code === 8232 || code === 8233) return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
2959
|
+
return char;
|
|
2960
|
+
}).join("")}"`;
|
|
2961
|
+
}
|
|
2962
|
+
/** PostgreSQL's NAMEDATALEN - 1: the longest name, in bytes, that Prisma Migrate derives. */
|
|
2963
|
+
const IDENTIFIER_LIMIT = 63;
|
|
2964
|
+
function utf8Length(value) {
|
|
2965
|
+
return new TextEncoder().encode(value).length;
|
|
2966
|
+
}
|
|
2967
|
+
/**
|
|
2968
|
+
* A constraint or index name as Prisma Migrate derives it: when base and suffix together exceed
|
|
2969
|
+
* PostgreSQL's identifier limit, the base is cut — at a character boundary, counting UTF-8 bytes
|
|
2970
|
+
* as PostgreSQL does — to leave room for the suffix.
|
|
2971
|
+
*
|
|
2972
|
+
* @param base - The table name, joined with the column names where Prisma includes them.
|
|
2973
|
+
* @param suffix - `_pkey`, `_key`, `_idx`, `_fkey` and so on.
|
|
2974
|
+
* @returns The name Prisma gives the constraint or index.
|
|
2975
|
+
*/
|
|
2976
|
+
function prismaConstraintName(base, suffix) {
|
|
2977
|
+
const room = IDENTIFIER_LIMIT - utf8Length(suffix);
|
|
2978
|
+
if (utf8Length(base) <= room) return `${base}${suffix}`;
|
|
2979
|
+
const chars = [...base.matchAll(/./gsu)].map(([char]) => char);
|
|
2980
|
+
return `${chars.filter((_, index) => utf8Length(chars.slice(0, index + 1).join("")) <= room).join("")}${suffix}`;
|
|
2981
|
+
}
|
|
2982
|
+
function tableName(model) {
|
|
2983
|
+
return model.dbName ?? model.name;
|
|
2984
|
+
}
|
|
2985
|
+
function columnName(field) {
|
|
2986
|
+
return field.dbName ?? field.name;
|
|
2987
|
+
}
|
|
2988
|
+
function isListDefault(def) {
|
|
2989
|
+
return Array.isArray(def);
|
|
2990
|
+
}
|
|
2991
|
+
function isFunctionDefault$5(def) {
|
|
2992
|
+
return def !== null && typeof def === "object" && !Array.isArray(def) && "name" in def;
|
|
2993
|
+
}
|
|
2994
|
+
function modelIndexes(model, indexes) {
|
|
2995
|
+
const own = indexes.filter((index) => index.model === model.name);
|
|
2996
|
+
if (own.length > 0) return own;
|
|
2997
|
+
const primaryKey = model.primaryKey?.fields ?? model.fields.filter((f) => f.isId).map((f) => f.name);
|
|
2998
|
+
return [
|
|
2999
|
+
...primaryKey.length > 0 ? [{
|
|
3000
|
+
type: "id",
|
|
3001
|
+
fields: primaryKey.map((name) => ({ name }))
|
|
3002
|
+
}] : [],
|
|
3003
|
+
...model.fields.filter((f) => f.isUnique).map((f) => ({
|
|
3004
|
+
type: "unique",
|
|
3005
|
+
fields: [{ name: f.name }]
|
|
3006
|
+
})),
|
|
3007
|
+
...model.uniqueFields.map((fields) => ({
|
|
3008
|
+
type: "unique",
|
|
3009
|
+
fields: fields.map((name) => ({ name }))
|
|
3010
|
+
}))
|
|
3011
|
+
];
|
|
3012
|
+
}
|
|
3013
|
+
function isSameFieldSet(left, right) {
|
|
3014
|
+
return left.length === right.length && left.every((name) => right.includes(name));
|
|
3015
|
+
}
|
|
3016
|
+
function fieldNames(index) {
|
|
3017
|
+
return index.fields.map((f) => f.name);
|
|
3018
|
+
}
|
|
3019
|
+
function entityKey(model, indexes) {
|
|
3020
|
+
return indexes.find((index) => index.type === "id") ?? indexes.find((index) => index.type === "unique" && index.fields.every((f) => model.fields.find((mf) => mf.name === f.name)?.isRequired === true)) ?? null;
|
|
3021
|
+
}
|
|
3022
|
+
function indexName(model, index) {
|
|
3023
|
+
if (index.dbName) return index.dbName;
|
|
3024
|
+
const table = tableName(model);
|
|
3025
|
+
if (index.type === "id") return prismaConstraintName(table, "_pkey");
|
|
3026
|
+
return prismaConstraintName([table, ...index.fields.map((f) => {
|
|
3027
|
+
const field = model.fields.find((mf) => mf.name === f.name);
|
|
3028
|
+
return field ? columnName(field) : f.name;
|
|
3029
|
+
})].join("_"), index.type === "unique" ? "_key" : "_idx");
|
|
3030
|
+
}
|
|
3031
|
+
function backRelation(field, owner, models) {
|
|
3032
|
+
const related = models.find((m) => m.name === field.type);
|
|
3033
|
+
return related?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && f.type === owner.name && !(related.name === owner.name && f.name === field.name));
|
|
3034
|
+
}
|
|
3035
|
+
function foreignKeys(models, indexesOf) {
|
|
3036
|
+
return models.flatMap((dependent) => dependent.fields.filter((f) => f.kind === "object" && (f.relationFromFields ?? []).length > 0).flatMap((navigation) => {
|
|
3037
|
+
const principal = models.find((m) => m.name === navigation.type);
|
|
3038
|
+
if (!principal) return [];
|
|
3039
|
+
const from = navigation.relationFromFields ?? [];
|
|
3040
|
+
const to = navigation.relationToFields ?? [];
|
|
3041
|
+
const principalIndexes = indexesOf(principal);
|
|
3042
|
+
const referenced = principalIndexes.find((index) => (index.type === "id" || index.type === "unique") && isSameFieldSet(fieldNames(index), to));
|
|
3043
|
+
const pairs = (referenced ? fieldNames(referenced) : to).flatMap((target) => {
|
|
3044
|
+
const position = to.indexOf(target);
|
|
3045
|
+
return position === -1 ? [] : [{
|
|
3046
|
+
from: from[position],
|
|
3047
|
+
to: target
|
|
3048
|
+
}];
|
|
3049
|
+
});
|
|
3050
|
+
const isKey = referenced !== void 0 && referenced === entityKey(principal, principalIndexes);
|
|
3051
|
+
return [{
|
|
3052
|
+
dependent,
|
|
3053
|
+
navigation,
|
|
3054
|
+
principal,
|
|
3055
|
+
inverse: backRelation(navigation, dependent, models),
|
|
3056
|
+
pairs,
|
|
3057
|
+
alternateKey: isKey ? null : referenced ?? {
|
|
3058
|
+
type: "unique",
|
|
3059
|
+
fields: to.map((name) => ({ name }))
|
|
3060
|
+
}
|
|
3061
|
+
}];
|
|
3062
|
+
}));
|
|
3063
|
+
}
|
|
3064
|
+
function manyToManyRelations(models) {
|
|
3065
|
+
return models.flatMap((model) => model.fields.filter((f) => f.kind === "object" && f.isList && (f.relationFromFields ?? []).length === 0).flatMap((field) => {
|
|
3066
|
+
const inverse = backRelation(field, model, models);
|
|
3067
|
+
const other = models.find((m) => m.name === field.type);
|
|
3068
|
+
if (!(other && inverse?.isList)) return [];
|
|
3069
|
+
if (!(model.name === other.name ? field.name < inverse.name : model.name < other.name)) return [];
|
|
3070
|
+
return [{
|
|
3071
|
+
relationName: field.relationName ?? `${model.name}To${other.name}`,
|
|
3072
|
+
a: {
|
|
3073
|
+
model,
|
|
3074
|
+
field
|
|
3075
|
+
},
|
|
3076
|
+
b: {
|
|
3077
|
+
model: other,
|
|
3078
|
+
field: inverse
|
|
3079
|
+
}
|
|
3080
|
+
}];
|
|
3081
|
+
}));
|
|
3082
|
+
}
|
|
3083
|
+
const OBJECT_MEMBERS = [
|
|
3084
|
+
"Equals",
|
|
3085
|
+
"Finalize",
|
|
3086
|
+
"GetHashCode",
|
|
3087
|
+
"GetType",
|
|
3088
|
+
"MemberwiseClone",
|
|
3089
|
+
"ReferenceEquals",
|
|
3090
|
+
"ToString"
|
|
3091
|
+
];
|
|
3092
|
+
const DB_CONTEXT_MEMBERS = [
|
|
3093
|
+
...OBJECT_MEMBERS,
|
|
3094
|
+
"Add",
|
|
3095
|
+
"AddAsync",
|
|
3096
|
+
"AddRange",
|
|
3097
|
+
"AddRangeAsync",
|
|
3098
|
+
"Attach",
|
|
3099
|
+
"AttachRange",
|
|
3100
|
+
"ChangeTracker",
|
|
3101
|
+
"ConfigureConventions",
|
|
3102
|
+
"ContextId",
|
|
3103
|
+
"Database",
|
|
3104
|
+
"Dispose",
|
|
3105
|
+
"DisposeAsync",
|
|
3106
|
+
"Entry",
|
|
3107
|
+
"Find",
|
|
3108
|
+
"FindAsync",
|
|
3109
|
+
"FromExpression",
|
|
3110
|
+
"Model",
|
|
3111
|
+
"OnConfiguring",
|
|
3112
|
+
"OnModelCreating",
|
|
3113
|
+
"Remove",
|
|
3114
|
+
"RemoveRange",
|
|
3115
|
+
"SaveChanges",
|
|
3116
|
+
"SaveChangesAsync",
|
|
3117
|
+
"SaveChangesFailed",
|
|
3118
|
+
"SavedChanges",
|
|
3119
|
+
"SavingChanges",
|
|
3120
|
+
"Set",
|
|
3121
|
+
"Update",
|
|
3122
|
+
"UpdateRange"
|
|
3123
|
+
];
|
|
3124
|
+
const GENERATED_CONTEXT_MEMBERS = [
|
|
3125
|
+
"ConfigureConventionsPartial",
|
|
3126
|
+
"MapEnums",
|
|
3127
|
+
"OnModelCreatingPartial",
|
|
3128
|
+
"StampUpdatedAt"
|
|
3129
|
+
];
|
|
3130
|
+
function lowerCase(name) {
|
|
3131
|
+
return name.toLowerCase();
|
|
3132
|
+
}
|
|
3133
|
+
function asIs(name) {
|
|
3134
|
+
return name;
|
|
3135
|
+
}
|
|
3136
|
+
function planNames(models, enums, generatorKeys, options) {
|
|
3137
|
+
const types = allocate([
|
|
3138
|
+
...models.map((m) => ({
|
|
3139
|
+
key: `model:${m.name}`,
|
|
3140
|
+
candidate: pascalCase(m.name)
|
|
3141
|
+
})),
|
|
3142
|
+
...enums.map((e) => ({
|
|
3143
|
+
key: `enum:${e.name}`,
|
|
3144
|
+
candidate: pascalCase(e.name)
|
|
3145
|
+
})),
|
|
3146
|
+
...generatorKeys.map((key) => ({
|
|
3147
|
+
key: `generator:${key}`,
|
|
3148
|
+
candidate: key
|
|
3149
|
+
}))
|
|
3150
|
+
], [options.context], lowerCase);
|
|
3151
|
+
const typeName = (key) => types.get(key) ?? key;
|
|
3152
|
+
const classes = new Map(models.map((m) => [m.name, typeName(`model:${m.name}`)]));
|
|
3153
|
+
return {
|
|
3154
|
+
namespace: options.namespace,
|
|
3155
|
+
context: options.context,
|
|
3156
|
+
classes,
|
|
3157
|
+
enums: new Map(enums.map((e) => [e.name, typeName(`enum:${e.name}`)])),
|
|
3158
|
+
generators: new Map(generatorKeys.map((key) => [key, typeName(`generator:${key}`)])),
|
|
3159
|
+
properties: new Map(models.map((model) => [model.name, allocate(model.fields.map((f) => ({
|
|
3160
|
+
key: f.name,
|
|
3161
|
+
candidate: pascalCase(f.name)
|
|
3162
|
+
})), [classes.get(model.name) ?? model.name, ...OBJECT_MEMBERS], asIs)])),
|
|
3163
|
+
enumMembers: new Map(enums.map((e) => [e.name, allocate(e.values.map((v) => ({
|
|
3164
|
+
key: v.name,
|
|
3165
|
+
candidate: pascalCase(v.name)
|
|
3166
|
+
})), [], asIs)])),
|
|
3167
|
+
dbSets: allocate(models.map((m) => ({
|
|
3168
|
+
key: m.name,
|
|
3169
|
+
candidate: pluralize(classes.get(m.name) ?? m.name)
|
|
3170
|
+
})), [
|
|
3171
|
+
options.context,
|
|
3172
|
+
...DB_CONTEXT_MEMBERS,
|
|
3173
|
+
...GENERATED_CONTEXT_MEMBERS
|
|
3174
|
+
], asIs)
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
function className(names, model) {
|
|
3178
|
+
return names.classes.get(model.name) ?? model.name;
|
|
3179
|
+
}
|
|
3180
|
+
function enumName(names, name) {
|
|
3181
|
+
return names.enums.get(name) ?? name;
|
|
3182
|
+
}
|
|
3183
|
+
function propertyName(names, model, fieldName) {
|
|
3184
|
+
return names.properties.get(model.name)?.get(fieldName) ?? fieldName;
|
|
3185
|
+
}
|
|
3186
|
+
function generatedRef(names, name) {
|
|
3187
|
+
return `${names.namespace}.${name}`;
|
|
3188
|
+
}
|
|
3189
|
+
function modelType(names, model) {
|
|
3190
|
+
return typeRef(generatedRef(names, className(names, model)));
|
|
3191
|
+
}
|
|
3192
|
+
function mapping(clr, isValueType, facets = [], elementStoreType = null, temporal = null) {
|
|
3193
|
+
return {
|
|
3194
|
+
clr,
|
|
3195
|
+
isValueType,
|
|
3196
|
+
facets,
|
|
3197
|
+
elementStoreType,
|
|
3198
|
+
temporal
|
|
3199
|
+
};
|
|
3200
|
+
}
|
|
3201
|
+
function columnType(storeType) {
|
|
3202
|
+
return `.HasColumnType(${csharpString(storeType)})`;
|
|
3203
|
+
}
|
|
3204
|
+
function lengthArg(args) {
|
|
3205
|
+
const [length] = args;
|
|
3206
|
+
return length !== void 0 && /^\d+$/u.test(length) ? length : null;
|
|
3207
|
+
}
|
|
3208
|
+
function postgresMapping(field, names) {
|
|
3209
|
+
if (field.kind === "enum") return mapping(typeRef(generatedRef(names, enumName(names, field.type))), true);
|
|
3210
|
+
return (field.nativeType ? nativeMapping(...field.nativeType) : null) ?? scalarMapping(field.type);
|
|
3211
|
+
}
|
|
3212
|
+
function nativeMapping(nativeName, args) {
|
|
3213
|
+
const length = lengthArg(args);
|
|
3214
|
+
switch (nativeName) {
|
|
3215
|
+
case "Text": return mapping("string", false);
|
|
3216
|
+
case "VarChar": return length ? mapping("string", false, [`.HasMaxLength(${length})`], `character varying(${length})`) : mapping("string", false, [columnType("character varying")], "character varying");
|
|
3217
|
+
case "Char": return mapping("string", false, [`.HasMaxLength(${length ?? "1"})`, ".IsFixedLength()"], `character(${length ?? "1"})`);
|
|
3218
|
+
case "Citext": return mapping("string", false, [columnType("citext")], "citext");
|
|
3219
|
+
case "Xml": return mapping("string", false, [columnType("xml")], "xml");
|
|
3220
|
+
case "Uuid": return mapping(typeRef(CS.Guid), true);
|
|
3221
|
+
case "Inet": return mapping(typeRef(CS.NpgsqlInet), true);
|
|
3222
|
+
case "Bit": {
|
|
3223
|
+
const storeType = `bit(${length ?? "1"})`;
|
|
3224
|
+
return mapping(typeRef(CS.BitArray), false, [columnType(storeType)], storeType);
|
|
3225
|
+
}
|
|
3226
|
+
case "VarBit": return length ? mapping(typeRef(CS.BitArray), false, [`.HasMaxLength(${length})`], `bit varying(${length})`) : mapping(typeRef(CS.BitArray), false);
|
|
3227
|
+
case "SmallInt": return mapping("short", true);
|
|
3228
|
+
case "Integer": return mapping("int", true);
|
|
3229
|
+
case "Oid": return mapping("uint", true, [columnType("oid")], "oid");
|
|
3230
|
+
case "BigInt": return mapping("long", true);
|
|
3231
|
+
case "Real": return mapping("float", true);
|
|
3232
|
+
case "DoublePrecision": return mapping("double", true);
|
|
3233
|
+
case "Money": return mapping("decimal", true, [columnType("money")], "money");
|
|
3234
|
+
case "Decimal": {
|
|
3235
|
+
const [precision, scale] = args;
|
|
3236
|
+
return precision !== void 0 && scale !== void 0 ? mapping("decimal", true, [`.HasPrecision(${precision}, ${scale})`], `numeric(${precision},${scale})`) : mapping("decimal", true);
|
|
3237
|
+
}
|
|
3238
|
+
case "Timestamp": {
|
|
3239
|
+
const storeType = length ? `timestamp(${length}) without time zone` : "timestamp without time zone";
|
|
3240
|
+
return mapping(typeRef(CS.DateTime), true, [columnType(storeType)], storeType, "timestamp");
|
|
3241
|
+
}
|
|
3242
|
+
case "Timestamptz": return length ? mapping(typeRef(CS.DateTime), true, [`.HasPrecision(${length})`], `timestamp(${length}) with time zone`, "timestamptz") : mapping(typeRef(CS.DateTime), true, [], null, "timestamptz");
|
|
3243
|
+
case "Date": return mapping(typeRef(CS.DateOnly), true, [], null, "date");
|
|
3244
|
+
case "Time": return length ? mapping(typeRef(CS.TimeOnly), true, [`.HasPrecision(${length})`], `time(${length}) without time zone`, "time") : mapping(typeRef(CS.TimeOnly), true, [], null, "time");
|
|
3245
|
+
case "Timetz": {
|
|
3246
|
+
const storeType = length ? `time(${length}) with time zone` : "time with time zone";
|
|
3247
|
+
return mapping(typeRef(CS.DateTimeOffset), true, [columnType(storeType)], storeType, "timetz");
|
|
3248
|
+
}
|
|
3249
|
+
case "Json": return mapping("string", false, [columnType("json")], "json");
|
|
3250
|
+
case "JsonB": return mapping("string", false, [columnType("jsonb")], "jsonb");
|
|
3251
|
+
case "ByteA": return mapping("byte[]", false);
|
|
3252
|
+
case "Boolean": return mapping("bool", true);
|
|
3253
|
+
default: return null;
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
function scalarMapping(type) {
|
|
3257
|
+
switch (type) {
|
|
3258
|
+
case "Int": return mapping("int", true);
|
|
3259
|
+
case "BigInt": return mapping("long", true);
|
|
3260
|
+
case "Float": return mapping("double", true);
|
|
3261
|
+
case "Decimal": return mapping("decimal", true, [".HasPrecision(65, 30)"], "numeric(65,30)");
|
|
3262
|
+
case "Boolean": return mapping("bool", true);
|
|
3263
|
+
case "DateTime": return mapping(typeRef(CS.DateTime), true, [columnType("timestamp(3) without time zone")], "timestamp(3) without time zone", "timestamp");
|
|
3264
|
+
case "Json": return mapping("string", false, [columnType("jsonb")], "jsonb");
|
|
3265
|
+
case "Bytes": return mapping("byte[]", false);
|
|
3266
|
+
default: return mapping("string", false);
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
function generatorKey(generator) {
|
|
3270
|
+
if (generator.kind === "uuid") return `UuidV${generator.version}${generator.clr === "Guid" ? "Guid" : "String"}Generator`;
|
|
3271
|
+
if (generator.kind === "ulid") return "UlidGenerator";
|
|
3272
|
+
if (generator.kind === "cuid") return generator.version === 2 ? "Cuid2Generator" : "CuidGenerator";
|
|
3273
|
+
return `Nanoid${generator.size}Generator`;
|
|
3274
|
+
}
|
|
3275
|
+
function valueGeneratorOf(field, clr) {
|
|
3276
|
+
if (!isFunctionDefault$5(field.default) || field.isList) return null;
|
|
3277
|
+
const isGuid = clr.clr === typeRef(CS.Guid);
|
|
3278
|
+
const isString = clr.clr === "string";
|
|
3279
|
+
const [arg] = field.default.args;
|
|
3280
|
+
switch (field.default.name) {
|
|
3281
|
+
case "uuid": return isGuid || isString ? {
|
|
3282
|
+
kind: "uuid",
|
|
3283
|
+
version: arg === 7 ? 7 : 4,
|
|
3284
|
+
clr: isGuid ? "Guid" : "string"
|
|
3285
|
+
} : null;
|
|
3286
|
+
case "ulid": return isString ? { kind: "ulid" } : null;
|
|
3287
|
+
case "cuid": return isString ? {
|
|
3288
|
+
kind: "cuid",
|
|
3289
|
+
version: arg === 2 ? 2 : 1
|
|
3290
|
+
} : null;
|
|
3291
|
+
case "nanoid": return isString ? {
|
|
3292
|
+
kind: "nanoid",
|
|
3293
|
+
size: typeof arg === "number" && arg > 0 ? arg : 21
|
|
3294
|
+
} : null;
|
|
3295
|
+
default: return null;
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
function integerLiteral(value) {
|
|
3299
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? String(value) : null;
|
|
3300
|
+
}
|
|
3301
|
+
function doubleLiteral(value) {
|
|
3302
|
+
const text = String(value);
|
|
3303
|
+
return /^-?\d+$/u.test(text) ? `${text}.0` : text;
|
|
3304
|
+
}
|
|
3305
|
+
/**
|
|
3306
|
+
* Reads an RFC 3339 timestamp as it may stand in `@default("...")`.
|
|
3307
|
+
*
|
|
3308
|
+
* @param value - The default as DMMF carries it.
|
|
3309
|
+
* @returns Its fields, the fraction as microseconds, or null when it is not a calendar timestamp.
|
|
3310
|
+
*/
|
|
3311
|
+
function parseDateTimeDefault(value) {
|
|
3312
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:(Z)|([+-])(\d{2}):?(\d{2}))$/iu.exec(value);
|
|
3313
|
+
if (!match) return null;
|
|
3314
|
+
const [, year, month, day, hour, minute, second, fraction, zulu, sign, offsetHour, offsetMinute] = match;
|
|
3315
|
+
const parsed = {
|
|
3316
|
+
year: Number(year),
|
|
3317
|
+
month: Number(month),
|
|
3318
|
+
day: Number(day),
|
|
3319
|
+
hour: Number(hour),
|
|
3320
|
+
minute: Number(minute),
|
|
3321
|
+
second: Number(second),
|
|
3322
|
+
microsecond: roundToMicroseconds(fraction ?? ""),
|
|
3323
|
+
offsetMinutes: zulu === void 0 ? (sign === "-" ? -1 : 1) * (Number(offsetHour) * 60 + Number(offsetMinute)) : 0
|
|
3324
|
+
};
|
|
3325
|
+
const date = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day, parsed.hour, parsed.minute, parsed.second));
|
|
3326
|
+
return parsed.year >= 1 && date.getUTCFullYear() === parsed.year && date.getUTCMonth() === parsed.month - 1 && date.getUTCDate() === parsed.day && date.getUTCHours() === parsed.hour && date.getUTCMinutes() === parsed.minute && date.getUTCSeconds() === parsed.second ? parsed : null;
|
|
3327
|
+
}
|
|
3328
|
+
function roundToMicroseconds(digits) {
|
|
3329
|
+
const padded = digits.padEnd(7, "0");
|
|
3330
|
+
const whole = Number(padded.slice(0, 6));
|
|
3331
|
+
const rest = padded.slice(6);
|
|
3332
|
+
const isHalf = /^50*$/u.test(rest);
|
|
3333
|
+
return !isHalf && rest.charAt(0) >= "5" || isHalf && whole % 2 === 1 ? whole + 1 : whole;
|
|
3334
|
+
}
|
|
3335
|
+
function shift(moment, offsetMinutes) {
|
|
3336
|
+
const carry = moment.microsecond === 1e6 ? 1 : 0;
|
|
3337
|
+
const date = /* @__PURE__ */ new Date(Date.UTC(moment.year, moment.month - 1, moment.day, moment.hour, moment.minute, moment.second + carry) - offsetMinutes * 6e4);
|
|
3338
|
+
return {
|
|
3339
|
+
year: date.getUTCFullYear(),
|
|
3340
|
+
month: date.getUTCMonth() + 1,
|
|
3341
|
+
day: date.getUTCDate(),
|
|
3342
|
+
hour: date.getUTCHours(),
|
|
3343
|
+
minute: date.getUTCMinutes(),
|
|
3344
|
+
second: date.getUTCSeconds(),
|
|
3345
|
+
microsecond: moment.microsecond % 1e6
|
|
3346
|
+
};
|
|
3347
|
+
}
|
|
3348
|
+
function clockArgs(moment) {
|
|
3349
|
+
const millisecond = Math.trunc(moment.microsecond / 1e3);
|
|
3350
|
+
const microsecond = moment.microsecond % 1e3;
|
|
3351
|
+
return [
|
|
3352
|
+
moment.hour,
|
|
3353
|
+
moment.minute,
|
|
3354
|
+
moment.second,
|
|
3355
|
+
millisecond,
|
|
3356
|
+
...microsecond > 0 ? [microsecond] : []
|
|
3357
|
+
];
|
|
3358
|
+
}
|
|
3359
|
+
function temporalLiteral(value, temporal) {
|
|
3360
|
+
const parsed = parseDateTimeDefault(value);
|
|
3361
|
+
if (!parsed || temporal === "timetz") return null;
|
|
3362
|
+
const moment = shift(parsed, parsed.offsetMinutes);
|
|
3363
|
+
if (moment.year > 9999) return null;
|
|
3364
|
+
if (temporal === "date") return `new ${typeRef(CS.DateOnly)}(${moment.year}, ${moment.month}, ${moment.day})`;
|
|
3365
|
+
if (temporal === "time") return `new ${typeRef(CS.TimeOnly)}(${clockArgs(moment).join(", ")})`;
|
|
3366
|
+
const kind = temporal === "timestamptz" ? "Utc" : "Unspecified";
|
|
3367
|
+
return `new ${typeRef(CS.DateTime)}(${[
|
|
3368
|
+
moment.year,
|
|
3369
|
+
moment.month,
|
|
3370
|
+
moment.day,
|
|
3371
|
+
...clockArgs(moment)
|
|
3372
|
+
].join(", ")}, ${exprRef(CS.DateTimeKind)}.${kind})`;
|
|
3373
|
+
}
|
|
3374
|
+
function sqlString(value) {
|
|
3375
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
3376
|
+
}
|
|
3377
|
+
function pad$1(value, width = 2) {
|
|
3378
|
+
return String(value).padStart(width, "0");
|
|
3379
|
+
}
|
|
3380
|
+
function sqlTimestamp(value) {
|
|
3381
|
+
const parsed = typeof value === "string" ? parseDateTimeDefault(value) : null;
|
|
3382
|
+
if (!parsed) return String(value);
|
|
3383
|
+
const clock = shift(parsed, 0);
|
|
3384
|
+
const fraction = clock.microsecond === 0 ? "" : clock.microsecond % 1e3 === 0 ? `.${pad$1(clock.microsecond / 1e3, 3)}` : `.${pad$1(clock.microsecond, 6)}`;
|
|
3385
|
+
const offset = Math.abs(parsed.offsetMinutes);
|
|
3386
|
+
const sign = parsed.offsetMinutes < 0 ? "-" : "+";
|
|
3387
|
+
return `${pad$1(clock.year, 4)}-${pad$1(clock.month)}-${pad$1(clock.day)} ${pad$1(clock.hour)}:${pad$1(clock.minute)}:${pad$1(clock.second)}${fraction} ${sign}${pad$1(Math.trunc(offset / 60))}:${pad$1(offset % 60)}`;
|
|
3388
|
+
}
|
|
3389
|
+
function sqlArray(values) {
|
|
3390
|
+
return sqlString(`{${values.map((value) => `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`).join(",")}}`);
|
|
3391
|
+
}
|
|
3392
|
+
function literal(value, field, clr, names, enums) {
|
|
3393
|
+
if (field.kind === "enum") {
|
|
3394
|
+
const isKnown = enums.find((e) => e.name === field.type)?.values.some((v) => v.name === value);
|
|
3395
|
+
const member = names.enumMembers.get(field.type)?.get(String(value));
|
|
3396
|
+
return isKnown && member ? `${exprRef(generatedRef(names, enumName(names, field.type)))}.${member}` : null;
|
|
3397
|
+
}
|
|
3398
|
+
if (clr.temporal !== null) return typeof value === "string" ? temporalLiteral(value, clr.temporal) : null;
|
|
3399
|
+
switch (clr.clr) {
|
|
3400
|
+
case "string": return typeof value === "string" ? csharpString(value) : null;
|
|
3401
|
+
case "bool": return typeof value === "boolean" ? String(value) : null;
|
|
3402
|
+
case "int": return integerLiteral(value);
|
|
3403
|
+
case "short": {
|
|
3404
|
+
const text = integerLiteral(value);
|
|
3405
|
+
return text === null ? null : `(short)${text}`;
|
|
3406
|
+
}
|
|
3407
|
+
case "uint": {
|
|
3408
|
+
const text = integerLiteral(value);
|
|
3409
|
+
return text === null || text.startsWith("-") ? null : `${text}u`;
|
|
3410
|
+
}
|
|
3411
|
+
case "long": return /^-?\d+$/u.test(String(value)) ? `${value}L` : null;
|
|
3412
|
+
case "double": return typeof value === "number" ? doubleLiteral(value) : null;
|
|
3413
|
+
case "float": return typeof value === "number" ? `${value}f` : null;
|
|
3414
|
+
case "decimal": return /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/iu.test(String(value)) ? `${value}m` : null;
|
|
3415
|
+
case "byte[]": return typeof value === "string" ? `${exprRef(CS.Convert)}.FromBase64String(${csharpString(value)})` : null;
|
|
3416
|
+
}
|
|
3417
|
+
if (clr.clr === typeRef(CS.Guid) && typeof value === "string") return `new ${typeRef(CS.Guid)}(${csharpString(value)})`;
|
|
3418
|
+
return null;
|
|
3419
|
+
}
|
|
3420
|
+
function defaultPlan(field, clr, names, enums) {
|
|
3421
|
+
const def = field.default;
|
|
3422
|
+
if (def === void 0 || def === null) return null;
|
|
3423
|
+
if (isFunctionDefault$5(def)) {
|
|
3424
|
+
const [arg] = def.args;
|
|
3425
|
+
if (def.name === "autoincrement") return { kind: "autoincrement" };
|
|
3426
|
+
if (def.name === "now") return {
|
|
3427
|
+
kind: "sql",
|
|
3428
|
+
sql: "CURRENT_TIMESTAMP"
|
|
3429
|
+
};
|
|
3430
|
+
if (def.name === "dbgenerated") return typeof arg === "string" && arg.length > 0 ? {
|
|
3431
|
+
kind: "sql",
|
|
3432
|
+
sql: arg
|
|
3433
|
+
} : { kind: "generated" };
|
|
3434
|
+
const generator = valueGeneratorOf(field, clr);
|
|
3435
|
+
if (!generator) return null;
|
|
3436
|
+
return field.isRequired ? {
|
|
3437
|
+
kind: "generator",
|
|
3438
|
+
generator
|
|
3439
|
+
} : {
|
|
3440
|
+
kind: "initializer",
|
|
3441
|
+
generator
|
|
3442
|
+
};
|
|
3443
|
+
}
|
|
3444
|
+
const isTemporal = clr.temporal !== null;
|
|
3445
|
+
if (isListDefault(def)) {
|
|
3446
|
+
const elements = def.map((value) => literal(value, field, clr, names, enums));
|
|
3447
|
+
const sqlValues = def.map((value) => isTemporal ? sqlTimestamp(value) : String(value));
|
|
3448
|
+
if (!elements.every((element) => element !== null)) return {
|
|
3449
|
+
kind: "sql",
|
|
3450
|
+
sql: sqlArray(sqlValues)
|
|
3451
|
+
};
|
|
3452
|
+
const listType = `${typeRef(CS.List)}<${clr.clr}>`;
|
|
3453
|
+
return {
|
|
3454
|
+
kind: "literal",
|
|
3455
|
+
expr: elements.length === 0 ? `new ${listType}()` : `new ${listType} { ${elements.join(", ")} }`,
|
|
3456
|
+
sql: isTemporal ? sqlArray(sqlValues) : null
|
|
3457
|
+
};
|
|
3458
|
+
}
|
|
3459
|
+
const expr = literal(def, field, clr, names, enums);
|
|
3460
|
+
if (expr !== null) return {
|
|
3461
|
+
kind: "literal",
|
|
3462
|
+
expr,
|
|
3463
|
+
sql: isTemporal ? sqlString(sqlTimestamp(def)) : null
|
|
3464
|
+
};
|
|
3465
|
+
const text = isTemporal ? sqlTimestamp(def) : String(def);
|
|
3466
|
+
return {
|
|
3467
|
+
kind: "sql",
|
|
3468
|
+
sql: typeof def === "string" ? sqlString(text) : text
|
|
3469
|
+
};
|
|
3470
|
+
}
|
|
3471
|
+
function isSystemNamespace(name) {
|
|
3472
|
+
return name === "System" || name.startsWith("System.");
|
|
3473
|
+
}
|
|
3474
|
+
function compareUsings(left, right) {
|
|
3475
|
+
if (isSystemNamespace(left) !== isSystemNamespace(right)) return isSystemNamespace(left) ? -1 : 1;
|
|
3476
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
3477
|
+
}
|
|
3478
|
+
/**
|
|
3479
|
+
* Resolves the type placeholders of an assembled file and puts its header on.
|
|
3480
|
+
*
|
|
3481
|
+
* @param body - The file below its `namespace` line.
|
|
3482
|
+
* @param scope - The namespace, the simple names of the generated types (which a same-named
|
|
3483
|
+
* framework type would lose to) and, per offset, the members an expression there sees.
|
|
3484
|
+
* @returns The finished file.
|
|
3485
|
+
*/
|
|
3486
|
+
function renderFile(body, scope) {
|
|
3487
|
+
const matches = [...body.matchAll(/\0([TE])\|([^\0]+)\0/gu)];
|
|
3488
|
+
const resolved = matches.map((match) => {
|
|
3489
|
+
const [, kind, fullName] = match;
|
|
3490
|
+
const dot = fullName.lastIndexOf(".");
|
|
3491
|
+
const simple = fullName.slice(dot + 1);
|
|
3492
|
+
const namespace = fullName.slice(0, dot);
|
|
3493
|
+
const isGenerated = namespace === scope.namespace;
|
|
3494
|
+
const members = scope.membersAt(match.index);
|
|
3495
|
+
const isShadowed = kind === "E" && members.has(simple) && members.get(simple) !== fullName || !isGenerated && scope.types.has(simple);
|
|
3496
|
+
return {
|
|
3497
|
+
text: isShadowed ? `global::${fullName}` : simple,
|
|
3498
|
+
using: isShadowed || isGenerated ? null : namespace
|
|
3499
|
+
};
|
|
3500
|
+
});
|
|
3501
|
+
const assembled = matches.reduce((acc, match, index) => ({
|
|
3502
|
+
text: `${acc.text}${body.slice(acc.cursor, match.index)}${resolved[index].text}`,
|
|
3503
|
+
cursor: match.index + match[0].length
|
|
3504
|
+
}), {
|
|
3505
|
+
text: "",
|
|
3506
|
+
cursor: 0
|
|
3507
|
+
});
|
|
3508
|
+
const usings = [.../* @__PURE__ */ new Set([...scope.usings ?? [], ...resolved.map((r) => r.using).filter((u) => u !== null)])].toSorted(compareUsings);
|
|
3509
|
+
return [
|
|
3510
|
+
"#nullable enable",
|
|
3511
|
+
"",
|
|
3512
|
+
...usings.length > 0 ? [...usings.map((u) => `using ${u};`), ""] : [],
|
|
3513
|
+
`namespace ${scope.namespace};`,
|
|
3514
|
+
"",
|
|
3515
|
+
`${assembled.text}${body.slice(assembled.cursor)}`
|
|
3516
|
+
].join("\n");
|
|
3517
|
+
}
|
|
3518
|
+
function chain(head, calls, indent) {
|
|
3519
|
+
if (calls.length <= 1) return [`${indent}${head}${calls.join("")};`];
|
|
3520
|
+
return [`${indent}${head}`, ...calls.map((call, index) => `${indent} ${call}${index === calls.length - 1 ? ";" : ""}`)];
|
|
3521
|
+
}
|
|
3522
|
+
function keyLambda(parameter, properties) {
|
|
3523
|
+
return properties.length === 1 ? `${parameter} => ${parameter}.${properties[0]}` : `${parameter} => new { ${properties.map((p) => `${parameter}.${p}`).join(", ")} }`;
|
|
3524
|
+
}
|
|
3525
|
+
function joinBlocks(blocks) {
|
|
3526
|
+
return blocks.filter((block) => block.length > 0).flatMap((block, index) => index === 0 ? block : ["", ...block]);
|
|
3527
|
+
}
|
|
3528
|
+
function scalarFields(model) {
|
|
3529
|
+
return model.fields.filter((f) => f.kind === "scalar" || f.kind === "enum");
|
|
3530
|
+
}
|
|
3531
|
+
function fieldPlan(plan, field) {
|
|
3532
|
+
const clr = postgresMapping(field, plan.names);
|
|
3533
|
+
return {
|
|
3534
|
+
clr,
|
|
3535
|
+
def: defaultPlan(field, clr, plan.names, plan.enums)
|
|
3536
|
+
};
|
|
3537
|
+
}
|
|
3538
|
+
function valueGenerators(plan) {
|
|
3539
|
+
return [...new Map(plan.models.flatMap((model) => scalarFields(model).flatMap((field) => {
|
|
3540
|
+
const { def } = fieldPlan(plan, field);
|
|
3541
|
+
return def?.kind === "generator" ? [[generatorKey(def.generator), def.generator]] : [];
|
|
3542
|
+
}))).entries()];
|
|
3543
|
+
}
|
|
3544
|
+
/**
|
|
3545
|
+
* Reads the schema into what the files are written from.
|
|
3546
|
+
*
|
|
3547
|
+
* @param datamodel - The DMMF datamodel.
|
|
3548
|
+
* @param options - The namespace and the DbContext class name.
|
|
3549
|
+
* @returns The plan the file writers take.
|
|
3550
|
+
*/
|
|
3551
|
+
function planEfCore(datamodel, options) {
|
|
3552
|
+
const indexesOf = (model) => modelIndexes(model, datamodel.indexes ?? []);
|
|
3553
|
+
const schema = {
|
|
3554
|
+
models: datamodel.models,
|
|
3555
|
+
enums: datamodel.enums,
|
|
3556
|
+
indexesOf,
|
|
3557
|
+
foreignKeys: foreignKeys(datamodel.models, indexesOf),
|
|
3558
|
+
manyToMany: manyToManyRelations(datamodel.models)
|
|
3559
|
+
};
|
|
3560
|
+
const generatorKeys = valueGenerators({
|
|
3561
|
+
...schema,
|
|
3562
|
+
names: planNames(datamodel.models, datamodel.enums, [], options)
|
|
3563
|
+
}).map(([key]) => key);
|
|
3564
|
+
return {
|
|
3565
|
+
...schema,
|
|
3566
|
+
names: planNames(datamodel.models, datamodel.enums, generatorKeys, options)
|
|
3567
|
+
};
|
|
3568
|
+
}
|
|
3569
|
+
function generatedTypes(plan) {
|
|
3570
|
+
return /* @__PURE__ */ new Set([
|
|
3571
|
+
plan.names.context,
|
|
3572
|
+
...plan.names.classes.values(),
|
|
3573
|
+
...plan.names.enums.values(),
|
|
3574
|
+
...plan.names.generators.values()
|
|
3575
|
+
]);
|
|
3576
|
+
}
|
|
3577
|
+
function memberType(plan, field) {
|
|
3578
|
+
if (field.isList || !field.isRequired) return null;
|
|
3579
|
+
if (field.kind === "object") {
|
|
3580
|
+
const target = plan.models.find((m) => m.name === field.type);
|
|
3581
|
+
return target ? generatedRef(plan.names, className(plan.names, target)) : null;
|
|
3582
|
+
}
|
|
3583
|
+
const match = /^\0T\|([^\0]+)\0$/u.exec(fieldPlan(plan, field).clr.clr);
|
|
3584
|
+
return match ? match[1] : null;
|
|
3585
|
+
}
|
|
3586
|
+
function entityProperty(plan, model, field) {
|
|
3587
|
+
const name = propertyName(plan.names, model, field.name);
|
|
3588
|
+
if (field.kind === "object") {
|
|
3589
|
+
const target = plan.models.find((m) => m.name === field.type);
|
|
3590
|
+
const targetType = target ? modelType(plan.names, target) : typeRef(generatedRef(plan.names, field.type));
|
|
3591
|
+
if (field.isList) return [` public virtual ${typeRef(CS.ICollection)}<${targetType}> ${name} { get; set; } = new ${typeRef(CS.List)}<${targetType}>();`];
|
|
3592
|
+
return field.isRequired ? [` public virtual ${targetType} ${name} { get; set; } = null!;`] : [` public virtual ${targetType}? ${name} { get; set; }`];
|
|
3593
|
+
}
|
|
3594
|
+
const { clr, def } = fieldPlan(plan, field);
|
|
3595
|
+
const line = ` public ${field.isList ? `${typeRef(CS.List)}<${clr.clr}>?` : field.isRequired ? clr.clr : `${clr.clr}?`} ${name} { get; set; }${def?.kind === "literal" ? ` = ${def.expr};` : def?.kind === "initializer" ? ` = ${nextValue(def.generator)};` : !field.isList && field.isRequired && !clr.isValueType ? " = null!;" : ""}`;
|
|
3596
|
+
return def?.kind === "initializer" ? withCuidV1(def.generator, [line]) : [line];
|
|
3597
|
+
}
|
|
3598
|
+
/**
|
|
3599
|
+
* The entity class of a model.
|
|
3600
|
+
*
|
|
3601
|
+
* @param plan - The plan.
|
|
3602
|
+
* @param model - The model.
|
|
3603
|
+
* @returns The file, as `{ fileName, code }`.
|
|
3604
|
+
*/
|
|
3605
|
+
function entityFile(plan, model) {
|
|
3606
|
+
const name = className(plan.names, model);
|
|
3607
|
+
const fields = model.fields.filter((f) => f.kind !== "unsupported");
|
|
3608
|
+
const body = [
|
|
3609
|
+
`public partial class ${name}`,
|
|
3610
|
+
"{",
|
|
3611
|
+
...joinBlocks(fields.map((f) => entityProperty(plan, model, f))),
|
|
3612
|
+
"}",
|
|
3613
|
+
""
|
|
3614
|
+
].join("\n");
|
|
3615
|
+
const members = new Map(fields.map((f) => [propertyName(plan.names, model, f.name), memberType(plan, f)]));
|
|
3616
|
+
return {
|
|
3617
|
+
fileName: `${name}.cs`,
|
|
3618
|
+
code: renderFile(body, {
|
|
3619
|
+
namespace: plan.names.namespace,
|
|
3620
|
+
types: generatedTypes(plan),
|
|
3621
|
+
membersAt: () => members
|
|
3622
|
+
})
|
|
3623
|
+
};
|
|
3624
|
+
}
|
|
3625
|
+
/**
|
|
3626
|
+
* The C# enum of a Prisma enum. Each member names its PostgreSQL label through `[PgName]`, which
|
|
3627
|
+
* is how Npgsql maps it — the label is the value's `@map`, or its name.
|
|
3628
|
+
*
|
|
3629
|
+
* @param plan - The plan.
|
|
3630
|
+
* @param e - The enum.
|
|
3631
|
+
* @returns The file, as `{ fileName, code }`.
|
|
3632
|
+
*/
|
|
3633
|
+
function enumFile(plan, e) {
|
|
3634
|
+
const name = enumName(plan.names, e.name);
|
|
3635
|
+
const members = e.values.map((value) => [` [${typeRef(CS.PgName)}(${csharpString(value.dbName ?? value.name)})]`, ` ${plan.names.enumMembers.get(e.name)?.get(value.name) ?? value.name},`]);
|
|
3636
|
+
const body = [
|
|
3637
|
+
`public enum ${name}`,
|
|
3638
|
+
"{",
|
|
3639
|
+
...joinBlocks(members),
|
|
3640
|
+
"}",
|
|
3641
|
+
""
|
|
3642
|
+
].join("\n");
|
|
3643
|
+
return {
|
|
3644
|
+
fileName: `${name}.cs`,
|
|
3645
|
+
code: renderFile(body, {
|
|
3646
|
+
namespace: plan.names.namespace,
|
|
3647
|
+
types: generatedTypes(plan),
|
|
3648
|
+
membersAt: () => /* @__PURE__ */ new Map()
|
|
3649
|
+
})
|
|
3650
|
+
};
|
|
3651
|
+
}
|
|
3652
|
+
function valueGenerationCalls(plan, def, isConventionallyGenerated) {
|
|
3653
|
+
if (def === null) return isConventionallyGenerated ? [".ValueGeneratedNever()"] : [];
|
|
3654
|
+
if (def.kind === "autoincrement") return [...isConventionallyGenerated ? [] : [".ValueGeneratedOnAdd()"], ".UseSerialColumn()"];
|
|
3655
|
+
if (def.kind === "generated") return [".ValueGeneratedOnAdd()"];
|
|
3656
|
+
if (def.kind === "generator") return [`.HasValueGenerator<${plan.names.generators.get(generatorKey(def.generator))}>()`];
|
|
3657
|
+
if (def.kind === "literal") return [".ValueGeneratedNever()"];
|
|
3658
|
+
return [];
|
|
3659
|
+
}
|
|
3660
|
+
function propertyConfig(plan, model, field, key) {
|
|
3661
|
+
const { clr, def } = fieldPlan(plan, field);
|
|
3662
|
+
const name = propertyName(plan.names, model, field.name);
|
|
3663
|
+
const valueGeneration = valueGenerationCalls(plan, def, key.length === 1 && key[0] === field.name && !field.isList && [
|
|
3664
|
+
"int",
|
|
3665
|
+
"long",
|
|
3666
|
+
"short",
|
|
3667
|
+
"uint",
|
|
3668
|
+
typeRef(CS.Guid)
|
|
3669
|
+
].includes(clr.clr));
|
|
3670
|
+
const facets = field.isList ? clr.elementStoreType === null ? [] : [columnType(`${clr.elementStoreType}[]`)] : clr.facets;
|
|
3671
|
+
const column = columnName(field);
|
|
3672
|
+
const isTriggerFilledInteger = def?.kind === "generated" && !field.isList && [
|
|
3673
|
+
"int",
|
|
3674
|
+
"long",
|
|
3675
|
+
"short"
|
|
3676
|
+
].includes(clr.clr);
|
|
3677
|
+
const calls = [
|
|
3678
|
+
...valueGeneration,
|
|
3679
|
+
...facets.filter((f) => !f.startsWith(".HasColumnType")),
|
|
3680
|
+
...def?.kind === "literal" && def.sql === null ? [`.HasDefaultValue(${def.expr})`] : [],
|
|
3681
|
+
...(def?.kind === "literal" || def?.kind === "sql") && def.sql !== null ? [`.HasDefaultValueSql(${csharpString(def.sql)})`] : [],
|
|
3682
|
+
...facets.filter((f) => f.startsWith(".HasColumnType")),
|
|
3683
|
+
...column === name ? [] : [`.HasColumnName(${csharpString(column)})`],
|
|
3684
|
+
...isTriggerFilledInteger ? [`.Metadata.SetValueGenerationStrategy(${exprRef(CS.NpgsqlValueGenerationStrategy)}.None)`] : []
|
|
3685
|
+
];
|
|
3686
|
+
return calls.length === 0 ? [] : chain(`entity.Property(e => e.${name})`, calls, " ");
|
|
3687
|
+
}
|
|
3688
|
+
/**
|
|
3689
|
+
* Prisma's `onDelete` as the EF Core `DeleteBehavior` that behaves the same.
|
|
3690
|
+
*
|
|
3691
|
+
* Without `onDelete`, Prisma restricts the delete of a required relation and sets an optional one
|
|
3692
|
+
* to null. `Restrict` and `NoAction` keep EF Core's `Restrict` / `NoAction` on a required relation,
|
|
3693
|
+
* where EF Core refuses the delete as the database would; on an optional relation those two have EF
|
|
3694
|
+
* Core set the foreign keys of the dependents it tracks to null and delete the principal anyway, so
|
|
3695
|
+
* `ClientNoAction` leaves the decision to the database instead — as for `SetDefault`, which EF Core
|
|
3696
|
+
* cannot express.
|
|
3697
|
+
*
|
|
3698
|
+
* @param onDelete - The referential action, as DMMF carries it.
|
|
3699
|
+
* @param isRequired - Whether the foreign key is required.
|
|
3700
|
+
* @returns A member of `DeleteBehavior`.
|
|
3701
|
+
*/
|
|
3702
|
+
function deleteBehavior(onDelete, isRequired) {
|
|
3703
|
+
const action = onDelete ?? (isRequired ? "Restrict" : "SetNull");
|
|
3704
|
+
if (action === "Cascade" || action === "SetNull") return action;
|
|
3705
|
+
if (isRequired && (action === "Restrict" || action === "NoAction")) return action;
|
|
3706
|
+
return "ClientNoAction";
|
|
3707
|
+
}
|
|
3708
|
+
function relationConfig(plan, fk) {
|
|
3709
|
+
const names = plan.names;
|
|
3710
|
+
const dependentProperty = (field) => propertyName(names, fk.dependent, field);
|
|
3711
|
+
const isOneToOne = fk.inverse !== void 0 && !fk.inverse.isList;
|
|
3712
|
+
const withCall = `.With${isOneToOne ? "One" : "Many"}(${fk.inverse ? `p => p.${propertyName(names, fk.principal, fk.inverse.name)}` : ""})`;
|
|
3713
|
+
const isRequired = fk.pairs.every((pair) => fk.dependent.fields.find((f) => f.name === pair.from)?.isRequired === true);
|
|
3714
|
+
const principalKey = fk.alternateKey ? [`.HasPrincipalKey${isOneToOne ? `<${modelType(names, fk.principal)}>` : ""}(${keyLambda("p", fk.pairs.map((pair) => propertyName(names, fk.principal, pair.to)))})`] : [];
|
|
3715
|
+
const constraint = prismaConstraintName([tableName(fk.dependent), ...(fk.navigation.relationFromFields ?? []).map((from) => {
|
|
3716
|
+
const field = fk.dependent.fields.find((f) => f.name === from);
|
|
3717
|
+
return field ? columnName(field) : from;
|
|
3718
|
+
})].join("_"), "_fkey");
|
|
3719
|
+
const calls = [
|
|
3720
|
+
...principalKey,
|
|
3721
|
+
`.HasForeignKey${isOneToOne ? `<${modelType(names, fk.dependent)}>` : ""}(${keyLambda("d", fk.pairs.map((pair) => dependentProperty(pair.from)))})`,
|
|
3722
|
+
`.OnDelete(${exprRef(CS.DeleteBehavior)}.${deleteBehavior(fk.navigation.relationOnDelete, isRequired)})`,
|
|
3723
|
+
`.HasConstraintName(${csharpString(constraint)})`
|
|
3724
|
+
];
|
|
3725
|
+
return [` entity.HasOne(d => d.${dependentProperty(fk.navigation.name)})${withCall}`, ...calls.map((call, index) => ` ${call}${index === calls.length - 1 ? ";" : ""}`)];
|
|
3726
|
+
}
|
|
3727
|
+
function manyToManyConfig(plan, m2m) {
|
|
3728
|
+
const names = plan.names;
|
|
3729
|
+
const table = prismaConstraintName(`_${m2m.relationName}`, "");
|
|
3730
|
+
const joinName = (suffix) => csharpString(prismaConstraintName(table, suffix));
|
|
3731
|
+
const cascade = `${exprRef(CS.DeleteBehavior)}.Cascade`;
|
|
3732
|
+
const toTable = m2m.a.model.schema ? `j.ToTable(${csharpString(table)}, ${csharpString(m2m.a.model.schema)});` : `j.ToTable(${csharpString(table)});`;
|
|
3733
|
+
return [
|
|
3734
|
+
` entity.HasMany(d => d.${propertyName(names, m2m.a.model, m2m.a.field.name)}).WithMany(p => p.${propertyName(names, m2m.b.model, m2m.b.field.name)})`,
|
|
3735
|
+
` .UsingEntity<${typeRef(CS.Dictionary)}<string, object>>(`,
|
|
3736
|
+
` ${csharpString(table)},`,
|
|
3737
|
+
` r => r.HasOne<${modelType(names, m2m.b.model)}>().WithMany()`,
|
|
3738
|
+
" .HasForeignKey(\"B\")",
|
|
3739
|
+
` .OnDelete(${cascade})`,
|
|
3740
|
+
` .HasConstraintName(${joinName("_B_fkey")}),`,
|
|
3741
|
+
` l => l.HasOne<${modelType(names, m2m.a.model)}>().WithMany()`,
|
|
3742
|
+
" .HasForeignKey(\"A\")",
|
|
3743
|
+
` .OnDelete(${cascade})`,
|
|
3744
|
+
` .HasConstraintName(${joinName("_A_fkey")}),`,
|
|
3745
|
+
" j =>",
|
|
3746
|
+
" {",
|
|
3747
|
+
` j.HasKey("A", "B").HasName(${joinName("_AB_pkey")});`,
|
|
3748
|
+
` ${toTable}`,
|
|
3749
|
+
` j.HasIndex(new[] { "B" }, ${joinName("_B_index")});`,
|
|
3750
|
+
" });"
|
|
3751
|
+
];
|
|
3752
|
+
}
|
|
3753
|
+
const INDEX_METHODS = {
|
|
3754
|
+
Hash: "hash",
|
|
3755
|
+
Gist: "gist",
|
|
3756
|
+
Gin: "gin",
|
|
3757
|
+
SpGist: "spgist",
|
|
3758
|
+
Brin: "brin"
|
|
3759
|
+
};
|
|
3760
|
+
/**
|
|
3761
|
+
* A PostgreSQL operator class as Prisma Migrate writes it: `JsonbPathOps` is `jsonb_path_ops`,
|
|
3762
|
+
* `Int4MinMaxMultiOps` is `int4_minmax_multi_ops`, and one given with `raw("...")` is used as it is.
|
|
3763
|
+
*
|
|
3764
|
+
* @param operatorClass - The operator class as DMMF carries it.
|
|
3765
|
+
* @param nativeType - The native type of the indexed field.
|
|
3766
|
+
* @returns The operator class's name in PostgreSQL.
|
|
3767
|
+
*/
|
|
3768
|
+
function operatorClassName(operatorClass, nativeType) {
|
|
3769
|
+
if (!/^[A-Z][\dA-Za-z]*Ops$/u.test(operatorClass)) return operatorClass;
|
|
3770
|
+
if (operatorClass === "BitMinMaxOps" && nativeType === "Uuid") return "uuid_minmax_multi_ops";
|
|
3771
|
+
return operatorClass.replace("MinMax", "Minmax").replace("VarBit", "Varbit").replace("TimestampTz", "Timestamptz").replace("TimeTz", "Timetz").replaceAll(/([\da-z])([A-Z])/gu, "$1_$2").toLowerCase();
|
|
3772
|
+
}
|
|
3773
|
+
function indexConfig(plan, model, index, isAlternateKey) {
|
|
3774
|
+
const properties = fieldNames(index).map((f) => propertyName(plan.names, model, f));
|
|
3775
|
+
const name = csharpString(indexName(model, index));
|
|
3776
|
+
if (isAlternateKey) return chain(`entity.HasAlternateKey(${keyLambda("e", properties)})`, [`.HasName(${name})`], " ");
|
|
3777
|
+
const descending = index.fields.map((f) => f.sortOrder === "desc");
|
|
3778
|
+
const method = index.algorithm === void 0 ? void 0 : INDEX_METHODS[index.algorithm];
|
|
3779
|
+
const operators = index.fields.map((f) => f.operatorClass === void 0 ? "" : operatorClassName(f.operatorClass, model.fields.find((mf) => mf.name === f.name)?.nativeType?.[0]));
|
|
3780
|
+
const calls = [
|
|
3781
|
+
...index.type === "unique" ? [".IsUnique()"] : [],
|
|
3782
|
+
...descending.includes(true) ? [`.IsDescending(${descending.join(", ")})`] : [],
|
|
3783
|
+
...method === void 0 ? [] : [`.HasMethod(${csharpString(method)})`],
|
|
3784
|
+
...operators.some((operator) => operator !== "") ? [`.HasOperators(${operators.map(csharpString).join(", ")})`] : []
|
|
3785
|
+
];
|
|
3786
|
+
return chain(`entity.HasIndex(${keyLambda("e", properties)}, ${name})`, calls, " ");
|
|
3787
|
+
}
|
|
3788
|
+
function entityConfig(plan, model) {
|
|
3789
|
+
const names = plan.names;
|
|
3790
|
+
const indexes = plan.indexesOf(model);
|
|
3791
|
+
const key = entityKey(model, indexes);
|
|
3792
|
+
const keyFields = key ? fieldNames(key) : [];
|
|
3793
|
+
const keyLine = key ? chain(`entity.HasKey(${keyLambda("e", keyFields.map((f) => propertyName(names, model, f)))})`, [`.HasName(${csharpString(indexName(model, key))})`], " ") : [" entity.HasNoKey();"];
|
|
3794
|
+
const table = model.schema ? ` entity.ToTable(${csharpString(tableName(model))}, ${csharpString(model.schema)});` : ` entity.ToTable(${csharpString(tableName(model))});`;
|
|
3795
|
+
const referencedKeys = plan.foreignKeys.flatMap((fk) => fk.principal === model && fk.alternateKey ? [fieldNames(fk.alternateKey)] : []);
|
|
3796
|
+
const indexBlocks = indexes.filter((index) => (index.type === "unique" || index.type === "normal") && index !== key).map((index) => indexConfig(plan, model, index, index.type === "unique" && referencedKeys.some((fields) => isSameFieldSet(fields, fieldNames(index)))));
|
|
3797
|
+
return [
|
|
3798
|
+
` modelBuilder.Entity<${modelType(names, model)}>(entity =>`,
|
|
3799
|
+
" {",
|
|
3800
|
+
...joinBlocks([
|
|
3801
|
+
keyLine,
|
|
3802
|
+
[table],
|
|
3803
|
+
...indexBlocks,
|
|
3804
|
+
scalarFields(model).flatMap((field) => propertyConfig(plan, model, field, keyFields)),
|
|
3805
|
+
...plan.foreignKeys.filter((fk) => fk.dependent === model).map((fk) => relationConfig(plan, fk)),
|
|
3806
|
+
...plan.manyToMany.filter((m2m) => m2m.a.model === model).map((m2m) => manyToManyConfig(plan, m2m))
|
|
3807
|
+
]),
|
|
3808
|
+
" });"
|
|
3809
|
+
];
|
|
3810
|
+
}
|
|
3811
|
+
function updatedAtValue(clr) {
|
|
3812
|
+
if (clr.temporal === "timestamptz") return "now";
|
|
3813
|
+
if (clr.temporal === "date") return `${exprRef(CS.DateOnly)}.FromDateTime(now)`;
|
|
3814
|
+
if (clr.temporal === "time") return `${exprRef(CS.TimeOnly)}.FromDateTime(now)`;
|
|
3815
|
+
if (clr.temporal === "timetz") return `new ${typeRef(CS.DateTimeOffset)}(now)`;
|
|
3816
|
+
return `${exprRef(CS.DateTime)}.SpecifyKind(now, ${exprRef(CS.DateTimeKind)}.Unspecified)`;
|
|
3817
|
+
}
|
|
3818
|
+
function stampUpdatedAt(plan) {
|
|
3819
|
+
const state = exprRef(CS.EntityState);
|
|
3820
|
+
const blocks = plan.models.flatMap((model) => {
|
|
3821
|
+
const fields = scalarFields(model).filter((field) => field.isUpdatedAt === true);
|
|
3822
|
+
if (fields.length === 0) return [];
|
|
3823
|
+
const stamps = fields.map((field) => {
|
|
3824
|
+
const name = propertyName(plan.names, model, field.name);
|
|
3825
|
+
return [
|
|
3826
|
+
` if ((entry.State == ${state}.Added && entry.Entity.${name} == default)`,
|
|
3827
|
+
` || (entry.State == ${state}.Modified && !entry.Property(e => e.${name}).IsModified))`,
|
|
3828
|
+
" {",
|
|
3829
|
+
` entry.Entity.${name} = ${updatedAtValue(fieldPlan(plan, field).clr)};`,
|
|
3830
|
+
" }"
|
|
3831
|
+
];
|
|
3832
|
+
});
|
|
3833
|
+
return [[
|
|
3834
|
+
` foreach (var entry in ChangeTracker.Entries<${modelType(plan.names, model)}>())`,
|
|
3835
|
+
" {",
|
|
3836
|
+
...joinBlocks(stamps),
|
|
3837
|
+
" }"
|
|
3838
|
+
]];
|
|
3839
|
+
});
|
|
3840
|
+
if (blocks.length === 0) return [];
|
|
3841
|
+
return [
|
|
3842
|
+
" public override int SaveChanges(bool acceptAllChangesOnSuccess)",
|
|
3843
|
+
" {",
|
|
3844
|
+
" StampUpdatedAt();",
|
|
3845
|
+
" return base.SaveChanges(acceptAllChangesOnSuccess);",
|
|
3846
|
+
" }",
|
|
3847
|
+
"",
|
|
3848
|
+
` public override ${typeRef(CS.Task)}<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, ${typeRef(CS.CancellationToken)} cancellationToken = default)`,
|
|
3849
|
+
" {",
|
|
3850
|
+
" StampUpdatedAt();",
|
|
3851
|
+
" return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);",
|
|
3852
|
+
" }",
|
|
3853
|
+
"",
|
|
3854
|
+
" private void StampUpdatedAt()",
|
|
3855
|
+
" {",
|
|
3856
|
+
` var now = ${exprRef(CS.DateTime)}.UtcNow;`,
|
|
3857
|
+
...joinBlocks(blocks),
|
|
3858
|
+
" }"
|
|
3859
|
+
];
|
|
3860
|
+
}
|
|
3861
|
+
function nextValue(generator) {
|
|
3862
|
+
if (generator.kind === "uuid") {
|
|
3863
|
+
const guid = `${exprRef(CS.Guid)}.${generator.version === 7 ? "CreateVersion7" : "NewGuid"}()`;
|
|
3864
|
+
return generator.clr === "Guid" ? guid : `${guid}.ToString()`;
|
|
3865
|
+
}
|
|
3866
|
+
if (generator.kind === "ulid") return `${exprRef(CS.Ulid)}.NewUlid().ToString()`;
|
|
3867
|
+
if (generator.kind === "cuid") return generator.version === 2 ? `new ${typeRef(CS.Cuid2)}().ToString()` : `${exprRef(CS.Cuid)}.NewCuid().ToString()`;
|
|
3868
|
+
return `${exprRef(CS.RandomNumberGenerator)}.GetString("_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ${generator.size})`;
|
|
3869
|
+
}
|
|
3870
|
+
function withCuidV1(generator, lines) {
|
|
3871
|
+
return generator.kind === "cuid" && generator.version === 1 ? [
|
|
3872
|
+
"#pragma warning disable VISLIB0001",
|
|
3873
|
+
...lines,
|
|
3874
|
+
"#pragma warning restore VISLIB0001"
|
|
3875
|
+
] : lines;
|
|
3876
|
+
}
|
|
3877
|
+
function generatorClass(name, generator) {
|
|
3878
|
+
const valueType = generator.kind === "uuid" && generator.clr === "Guid" ? typeRef(CS.Guid) : "string";
|
|
3879
|
+
const next = nextValue(generator);
|
|
3880
|
+
const nextLine = ` public override ${valueType} Next(${typeRef(CS.EntityEntry)} entry) => ${next};`;
|
|
3881
|
+
return [
|
|
3882
|
+
`file sealed class ${name} : ${typeRef(CS.ValueGenerator)}<${valueType}>`,
|
|
3883
|
+
"{",
|
|
3884
|
+
" public override bool GeneratesTemporaryValues => false;",
|
|
3885
|
+
"",
|
|
3886
|
+
...withCuidV1(generator, [nextLine]),
|
|
3887
|
+
"}"
|
|
3888
|
+
];
|
|
3889
|
+
}
|
|
3890
|
+
/**
|
|
3891
|
+
* The DbContext: a DbSet per model, the Fluent API mapping of every model onto the tables Prisma
|
|
3892
|
+
* Migrate creates, the enum mappings Npgsql needs, @updatedAt, and the value generators of
|
|
3893
|
+
* `uuid()`, `ulid()`, `cuid()` and `nanoid()`.
|
|
3894
|
+
*
|
|
3895
|
+
* @param plan - The plan.
|
|
3896
|
+
* @returns The file, as `{ fileName, code }`.
|
|
3897
|
+
*/
|
|
3898
|
+
function contextFile(plan) {
|
|
3899
|
+
const names = plan.names;
|
|
3900
|
+
const context = names.context;
|
|
3901
|
+
const enumType = (e) => typeRef(generatedRef(names, enumName(names, e.name)));
|
|
3902
|
+
const mapEnums = (parameter, type) => [
|
|
3903
|
+
` public static void MapEnums(${typeRef(type)} ${parameter})`,
|
|
3904
|
+
" {",
|
|
3905
|
+
...plan.enums.map((e) => ` ${parameter}.MapEnum<${enumType(e)}>(${csharpString(e.dbName ?? e.name)});`),
|
|
3906
|
+
" }"
|
|
3907
|
+
];
|
|
3908
|
+
const enumMappings = [
|
|
3909
|
+
...mapEnums("npgsql", CS.NpgsqlDbContextOptionsBuilder),
|
|
3910
|
+
"",
|
|
3911
|
+
...mapEnums("dataSource", CS.NpgsqlDataSourceBuilder),
|
|
3912
|
+
""
|
|
3913
|
+
];
|
|
3914
|
+
const updatedAt = stampUpdatedAt(plan);
|
|
3915
|
+
const classBody = [
|
|
3916
|
+
`public partial class ${context} : ${typeRef(CS.DbContext)}`,
|
|
3917
|
+
"{",
|
|
3918
|
+
` public ${context}(${typeRef(CS.DbContextOptions)}<${context}> options)`,
|
|
3919
|
+
" : base(options)",
|
|
3920
|
+
" {",
|
|
3921
|
+
" }",
|
|
3922
|
+
"",
|
|
3923
|
+
...plan.models.flatMap((model) => [` public virtual ${typeRef(CS.DbSet)}<${modelType(names, model)}> ${names.dbSets.get(model.name) ?? model.name} { get; set; }`, ""]),
|
|
3924
|
+
...enumMappings,
|
|
3925
|
+
` protected override void ConfigureConventions(${typeRef(CS.ModelConfigurationBuilder)} configurationBuilder)`,
|
|
3926
|
+
" {",
|
|
3927
|
+
` configurationBuilder.Conventions.Remove<${typeRef(CS.ForeignKeyIndexConvention)}>();`,
|
|
3928
|
+
" ConfigureConventionsPartial(configurationBuilder);",
|
|
3929
|
+
" }",
|
|
3930
|
+
"",
|
|
3931
|
+
` partial void ConfigureConventionsPartial(${typeRef(CS.ModelConfigurationBuilder)} configurationBuilder);`,
|
|
3932
|
+
"",
|
|
3933
|
+
` protected override void OnModelCreating(${typeRef(CS.ModelBuilder)} modelBuilder)`,
|
|
3934
|
+
" {",
|
|
3935
|
+
...joinBlocks([
|
|
3936
|
+
plan.enums.map((e) => ` modelBuilder.HasPostgresEnum<${enumType(e)}>(name: ${csharpString(e.dbName ?? e.name)});`),
|
|
3937
|
+
...plan.models.map((model) => entityConfig(plan, model)),
|
|
3938
|
+
[" OnModelCreatingPartial(modelBuilder);"]
|
|
3939
|
+
]),
|
|
3940
|
+
" }",
|
|
3941
|
+
"",
|
|
3942
|
+
` partial void OnModelCreatingPartial(${typeRef(CS.ModelBuilder)} modelBuilder);`,
|
|
3943
|
+
...updatedAt.length > 0 ? ["", ...updatedAt] : [],
|
|
3944
|
+
"}",
|
|
3945
|
+
""
|
|
3946
|
+
].join("\n");
|
|
3947
|
+
const generators = valueGenerators(plan).map(([key, generator]) => generatorClass(names.generators.get(key) ?? key, generator).join("\n"));
|
|
3948
|
+
const body = generators.length > 0 ? `${classBody}\n${generators.join("\n\n")}\n` : classBody;
|
|
3949
|
+
const contextMembers = new Map([
|
|
3950
|
+
...names.dbSets.values(),
|
|
3951
|
+
...DB_CONTEXT_MEMBERS,
|
|
3952
|
+
...GENERATED_CONTEXT_MEMBERS
|
|
3953
|
+
].map((member) => [member, null]));
|
|
3954
|
+
return {
|
|
3955
|
+
fileName: `${context}.cs`,
|
|
3956
|
+
code: renderFile(body, {
|
|
3957
|
+
namespace: names.namespace,
|
|
3958
|
+
types: generatedTypes(plan),
|
|
3959
|
+
usings: ["Microsoft.EntityFrameworkCore"],
|
|
3960
|
+
membersAt: (offset) => offset < classBody.length ? contextMembers : /* @__PURE__ */ new Map()
|
|
3961
|
+
})
|
|
3962
|
+
};
|
|
3963
|
+
}
|
|
3964
|
+
//#endregion
|
|
3965
|
+
//#region src/generator/efcore.ts
|
|
3966
|
+
function efcoreFiles(datamodel, options) {
|
|
3967
|
+
const plan = planEfCore(datamodel, options);
|
|
3968
|
+
return [
|
|
3969
|
+
...datamodel.models.map((model) => entityFile(plan, model)),
|
|
3970
|
+
...datamodel.enums.map((e) => enumFile(plan, e)),
|
|
3971
|
+
contextFile(plan)
|
|
3972
|
+
];
|
|
3973
|
+
}
|
|
3974
|
+
//#endregion
|
|
3975
|
+
//#region src/core/efcore.ts
|
|
3976
|
+
function efcore(options) {
|
|
3977
|
+
return Effect.gen(function* () {
|
|
3978
|
+
if (!(options.generator.isCustomOutput && options.generator.output?.value)) return yield* new GeneratorConfigError({ message: "output is required for Hekireki-EFCore. Please specify output in your generator config." });
|
|
3979
|
+
const provider = options.datasources[0]?.activeProvider ?? "postgresql";
|
|
3980
|
+
if (provider !== "postgresql") return yield* new GeneratorConfigError({ message: `Unsupported provider for Hekireki-EFCore: ${provider}. Supported providers are postgresql.` });
|
|
3981
|
+
const namespace = getString(options.generator.config?.namespace) ?? "Models";
|
|
3982
|
+
if (!namespace.split(".").every(isCSharpIdentifier)) return yield* new GeneratorConfigError({ message: `namespace for Hekireki-EFCore must be a C# namespace such as "MyApp.Models": ${namespace}` });
|
|
3983
|
+
const context = getString(options.generator.config?.context) ?? "AppDbContext";
|
|
3984
|
+
if (!isCSharpTypeName(context)) return yield* new GeneratorConfigError({ message: `context for Hekireki-EFCore must be a C# class name such as "AppDbContext": ${context}` });
|
|
3985
|
+
return yield* emitMany(efcoreFiles(options.dmmf.datamodel, {
|
|
3986
|
+
namespace,
|
|
3987
|
+
context
|
|
3988
|
+
}), options.generator.output.value);
|
|
3989
|
+
});
|
|
3990
|
+
}
|
|
3991
|
+
//#endregion
|
|
2597
3992
|
//#region src/helper/effect.ts
|
|
2598
3993
|
function makeEffectInfer(modelName) {
|
|
2599
3994
|
return `export type ${modelName} = typeof ${modelName}Schema.Type`;
|
|
@@ -3812,20 +5207,39 @@ function makePrismaColumn(column) {
|
|
|
3812
5207
|
].filter((c) => Boolean(c));
|
|
3813
5208
|
return ` ${column.name} ${column.type}${formatConstraints(constraints)}`;
|
|
3814
5209
|
}
|
|
5210
|
+
/**
|
|
5211
|
+
* The name a model, field, enum or enum value has in the database: its `@map` / `@@map` when it
|
|
5212
|
+
* has one, its Prisma name otherwise. DBML describes the database, so every name it writes is this.
|
|
5213
|
+
*/
|
|
5214
|
+
function dbNameOf(item) {
|
|
5215
|
+
return item.dbName ?? item.name;
|
|
5216
|
+
}
|
|
5217
|
+
/** The column a Prisma field of `model` is stored in. */
|
|
5218
|
+
function columnOf(model, field) {
|
|
5219
|
+
const found = model?.fields.find((f) => f.name === field);
|
|
5220
|
+
return found ? dbNameOf(found) : field;
|
|
5221
|
+
}
|
|
3815
5222
|
function isFunctionDefault$4(def) {
|
|
3816
5223
|
return def !== null && typeof def === "object" && "name" in def;
|
|
3817
5224
|
}
|
|
3818
|
-
function toDBMLColumn(field,
|
|
5225
|
+
function toDBMLColumn(field, enums) {
|
|
3819
5226
|
const defaultName = isFunctionDefault$4(field.default) ? field.default.name : void 0;
|
|
3820
|
-
const
|
|
5227
|
+
const enumDef = field.kind === "enum" ? enums.find((e) => e.name === field.type) : void 0;
|
|
5228
|
+
const baseType = enumDef ? dbNameOf(enumDef) : field.type;
|
|
3821
5229
|
const type = field.isList && !field.relationName ? `${baseType}[]` : baseType;
|
|
3822
5230
|
const defaultValue = (() => {
|
|
3823
5231
|
if (defaultName === "autoincrement") return void 0;
|
|
3824
5232
|
if (defaultName === "now") return "`now()`";
|
|
3825
|
-
if (field.hasDefaultValue && typeof field.default !== "object")
|
|
5233
|
+
if (field.hasDefaultValue && typeof field.default !== "object") {
|
|
5234
|
+
if (field.kind === "enum") {
|
|
5235
|
+
const value = enumDef?.values.find((v) => v.name === field.default);
|
|
5236
|
+
return `'${value ? dbNameOf(value) : String(field.default)}'`;
|
|
5237
|
+
}
|
|
5238
|
+
return field.type === "String" || field.type === "Json" ? `'${field.default}'` : String(field.default);
|
|
5239
|
+
}
|
|
3826
5240
|
})();
|
|
3827
5241
|
return {
|
|
3828
|
-
name: field
|
|
5242
|
+
name: dbNameOf(field),
|
|
3829
5243
|
type,
|
|
3830
5244
|
isPrimaryKey: field.isId,
|
|
3831
5245
|
isIncrement: defaultName === "autoincrement",
|
|
@@ -3835,15 +5249,16 @@ function toDBMLColumn(field, models, mapToDbSchema) {
|
|
|
3835
5249
|
note: stripAnnotations(field.documentation)
|
|
3836
5250
|
};
|
|
3837
5251
|
}
|
|
3838
|
-
function makeTables(models,
|
|
5252
|
+
function makeTables(models, enums = []) {
|
|
3839
5253
|
return models.map((model) => {
|
|
3840
|
-
const modelName =
|
|
3841
|
-
const columnLines = model.fields.filter((field) => !field.relationName).map((field) => toDBMLColumn(field,
|
|
5254
|
+
const modelName = dbNameOf(model);
|
|
5255
|
+
const columnLines = model.fields.filter((field) => !field.relationName).map((field) => toDBMLColumn(field, enums)).map(makePrismaColumn).join("\n");
|
|
5256
|
+
const columnsOf = (fields) => fields.map((f) => columnOf(model, f));
|
|
3842
5257
|
const indexes = [...model.primaryKey?.fields && model.primaryKey.fields.length > 0 ? [{
|
|
3843
|
-
columns: model.primaryKey.fields,
|
|
5258
|
+
columns: columnsOf(model.primaryKey.fields),
|
|
3844
5259
|
isPrimaryKey: true
|
|
3845
5260
|
}] : [], ...model.uniqueFields.filter((c) => c.length > 1).map((c) => ({
|
|
3846
|
-
columns: c,
|
|
5261
|
+
columns: columnsOf(c),
|
|
3847
5262
|
isUnique: true
|
|
3848
5263
|
}))];
|
|
3849
5264
|
const indexBlock = indexes.length > 0 ? `\n\n indexes {\n${indexes.map(makeIndex).join("\n")}\n }` : "";
|
|
@@ -3853,19 +5268,19 @@ function makeTables(models, mapToDbSchema = false) {
|
|
|
3853
5268
|
}
|
|
3854
5269
|
function makeEnums(enums) {
|
|
3855
5270
|
return enums.map((e) => makeEnum({
|
|
3856
|
-
name: e
|
|
3857
|
-
values: e.values.map(
|
|
5271
|
+
name: dbNameOf(e),
|
|
5272
|
+
values: e.values.map(dbNameOf)
|
|
3858
5273
|
}));
|
|
3859
5274
|
}
|
|
3860
|
-
function makeRelations(models
|
|
5275
|
+
function makeRelations(models) {
|
|
3861
5276
|
return models.flatMap((model) => model.fields.filter((field) => field.relationName && field.relationToFields?.length && field.relationFromFields?.length).map((field) => {
|
|
3862
5277
|
const relationTo = field.type;
|
|
3863
5278
|
const toModel = models.find((m) => m.name === relationTo);
|
|
3864
5279
|
const operator = (toModel?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && !(toModel.name === model.name && f.name === field.name)))?.isList ? ">" : "-";
|
|
3865
|
-
const relationFromName =
|
|
3866
|
-
const relationToName =
|
|
3867
|
-
const fromColumn = combineKeys(field.relationFromFields ?? []);
|
|
3868
|
-
const toColumn = combineKeys(field.relationToFields ?? []);
|
|
5280
|
+
const relationFromName = dbNameOf(model);
|
|
5281
|
+
const relationToName = toModel ? dbNameOf(toModel) : relationTo;
|
|
5282
|
+
const fromColumn = combineKeys((field.relationFromFields ?? []).map((f) => columnOf(model, f)));
|
|
5283
|
+
const toColumn = combineKeys((field.relationToFields ?? []).map((f) => columnOf(toModel, f)));
|
|
3869
5284
|
return makeRef({
|
|
3870
5285
|
name: `${relationFromName}_${fromColumn}_fk`,
|
|
3871
5286
|
fromTable: relationFromName,
|
|
@@ -3889,19 +5304,27 @@ function dbmlOperator(leftMany, rightMany) {
|
|
|
3889
5304
|
}
|
|
3890
5305
|
function annotatedDbmlRefs(models) {
|
|
3891
5306
|
const inferredKeys = new Set(inferredERRelations(models).map(erKey));
|
|
5307
|
+
const end = (side) => {
|
|
5308
|
+
const model = models.find((m) => m.name === side.model);
|
|
5309
|
+
return {
|
|
5310
|
+
table: model ? dbNameOf(model) : side.model,
|
|
5311
|
+
column: columnOf(model, side.field)
|
|
5312
|
+
};
|
|
5313
|
+
};
|
|
3892
5314
|
return annotatedERRelations(models).filter((relation) => !inferredKeys.has(erKey(relation))).map((relation) => {
|
|
3893
|
-
const
|
|
3894
|
-
const
|
|
5315
|
+
const to = end(relation.to);
|
|
5316
|
+
const from = end(relation.from);
|
|
3895
5317
|
const operator = dbmlOperator(isMany(relation.to.cardinality), isMany(relation.from.cardinality));
|
|
3896
|
-
return `Ref ${`${
|
|
5318
|
+
return `Ref ${`${to.table}_${to.column}_${from.table}_${from.column}`}: ${to.table}.${to.column} ${operator} ${from.table}.${from.column}`;
|
|
3897
5319
|
});
|
|
3898
5320
|
}
|
|
3899
5321
|
//#endregion
|
|
3900
5322
|
//#region src/generator/dbml.ts
|
|
3901
|
-
|
|
3902
|
-
|
|
5323
|
+
/** The schema as DBML, named as the database names it: every `@map` / `@@map` applied. */
|
|
5324
|
+
function dbmlContent(datamodel) {
|
|
5325
|
+
const tables = makeTables(datamodel.models, datamodel.enums);
|
|
3903
5326
|
const enums = makeEnums(datamodel.enums);
|
|
3904
|
-
const refs = makeRelations(datamodel.models
|
|
5327
|
+
const refs = makeRelations(datamodel.models);
|
|
3905
5328
|
const logicalRefs = annotatedDbmlRefs(datamodel.models);
|
|
3906
5329
|
return [
|
|
3907
5330
|
...enums,
|
|
@@ -4011,8 +5434,8 @@ const FORMATS = {
|
|
|
4011
5434
|
render: (options) => erContent(options.dmmf.datamodel.models).join("\n")
|
|
4012
5435
|
},
|
|
4013
5436
|
".dbml": {
|
|
4014
|
-
options: [
|
|
4015
|
-
render: (options) => dbmlContent(options.dmmf.datamodel
|
|
5437
|
+
options: [],
|
|
5438
|
+
render: (options) => dbmlContent(options.dmmf.datamodel)
|
|
4016
5439
|
},
|
|
4017
5440
|
".png": {
|
|
4018
5441
|
options: ["theme"],
|
|
@@ -4037,28 +5460,33 @@ function endsIn(name) {
|
|
|
4037
5460
|
return extension === "" ? "nothing" : `"${extension}"`;
|
|
4038
5461
|
}
|
|
4039
5462
|
/**
|
|
4040
|
-
* The files to write
|
|
5463
|
+
* The files to write: the one `output` names, or every one `outputs` lists.
|
|
4041
5464
|
*
|
|
4042
|
-
*
|
|
4043
|
-
*
|
|
5465
|
+
* Neither ever names a directory — each entry is a whole path, extension included — so the file
|
|
5466
|
+
* the caller writes is the file they get. A schema that wants the ER model in several formats
|
|
5467
|
+
* declares `Hekireki-ER` once and lists them in `outputs`, each resolved the way Prisma resolves
|
|
5468
|
+
* `output`: against the directory of the schema file that declares the block.
|
|
4044
5469
|
*/
|
|
4045
|
-
function filesOf(
|
|
5470
|
+
function filesOf(options, outputs) {
|
|
4046
5471
|
return Effect.gen(function* () {
|
|
4047
|
-
|
|
5472
|
+
const output = options.generator.isCustomOutput ? options.generator.output?.value : void 0;
|
|
5473
|
+
if (output && outputs !== void 0) return yield* new GeneratorConfigError({ message: "Hekireki-ER takes output or outputs, not both: output names one file, outputs lists several." });
|
|
5474
|
+
if (output) {
|
|
4048
5475
|
const extension = path.extname(output).toLowerCase();
|
|
4049
|
-
if (!isFormat(extension)) return yield* new GeneratorConfigError({ message: `output for Hekireki-ER has to name a file ending in ${EXTENSIONS}; "${output}" ends in ${endsIn(output)}.` });
|
|
5476
|
+
if (!isFormat(extension)) return yield* new GeneratorConfigError({ message: `output for Hekireki-ER has to name a file ending in ${EXTENSIONS}, not a directory; "${output}" ends in ${endsIn(output)}.` });
|
|
4050
5477
|
return [{
|
|
4051
5478
|
file: output,
|
|
4052
5479
|
extension
|
|
4053
5480
|
}];
|
|
4054
5481
|
}
|
|
5482
|
+
if (outputs === void 0) return yield* new GeneratorConfigError({ message: `output or outputs is required for Hekireki-ER: output names one file, outputs lists several, each ending in ${EXTENSIONS}.` });
|
|
4055
5483
|
if (outputs.length === 0) return yield* new GeneratorConfigError({ message: "outputs for Hekireki-ER has to name at least one file." });
|
|
4056
|
-
|
|
5484
|
+
const base = path.dirname(options.generator.sourceFilePath);
|
|
4057
5485
|
return yield* Effect.forEach(outputs, (name) => {
|
|
4058
5486
|
const extension = path.extname(name).toLowerCase();
|
|
4059
5487
|
if (!isFormat(extension)) return new GeneratorConfigError({ message: `outputs for Hekireki-ER has to name files ending in ${EXTENSIONS}; "${name}" ends in ${endsIn(name)}.` });
|
|
4060
5488
|
return Effect.succeed({
|
|
4061
|
-
file: path.resolve(
|
|
5489
|
+
file: path.resolve(base, name),
|
|
4062
5490
|
extension
|
|
4063
5491
|
});
|
|
4064
5492
|
});
|
|
@@ -4066,10 +5494,9 @@ function filesOf(output, outputs) {
|
|
|
4066
5494
|
}
|
|
4067
5495
|
function er(options) {
|
|
4068
5496
|
return Effect.gen(function* () {
|
|
4069
|
-
if (!(options.generator.isCustomOutput && options.generator.output?.value)) return yield* new GeneratorConfigError({ message: "output is required for Hekireki-ER. Please specify output in your generator config." });
|
|
4070
5497
|
const config = options.generator.config ?? {};
|
|
4071
5498
|
const outputs = getStrings(config.outputs);
|
|
4072
|
-
const files = yield* filesOf(options
|
|
5499
|
+
const files = yield* filesOf(options, outputs);
|
|
4073
5500
|
const read = new Set(outputs === void 0 ? [] : ["outputs"]);
|
|
4074
5501
|
for (const { extension } of files) for (const option of FORMATS[extension].options) read.add(option);
|
|
4075
5502
|
const unread = Object.keys(config).filter((name) => !read.has(name));
|
|
@@ -6204,6 +7631,10 @@ const GENERATORS = {
|
|
|
6204
7631
|
prettyName: "Hekireki-Effect",
|
|
6205
7632
|
handler: effect
|
|
6206
7633
|
},
|
|
7634
|
+
efcore: {
|
|
7635
|
+
prettyName: "Hekireki-EFCore",
|
|
7636
|
+
handler: efcore
|
|
7637
|
+
},
|
|
6207
7638
|
eloquent: {
|
|
6208
7639
|
prettyName: "Hekireki-Eloquent",
|
|
6209
7640
|
handler: eloquent
|