hekireki 0.41.0 → 0.43.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.
Files changed (69) hide show
  1. package/README.md +8 -0
  2. package/dist/bin/activerecord.js +1 -1
  3. package/dist/bin/ajv.js +1 -1
  4. package/dist/bin/arktype.js +1 -1
  5. package/dist/bin/atlas.js +1 -1
  6. package/dist/bin/django.js +1 -1
  7. package/dist/bin/drizzle.js +1 -1
  8. package/dist/bin/ecto.js +1 -1
  9. package/dist/bin/efcore.js +1 -1
  10. package/dist/bin/effect.js +1 -1
  11. package/dist/bin/eloquent.js +1 -1
  12. package/dist/bin/er.js +1 -1
  13. package/dist/bin/exposed.js +1 -1
  14. package/dist/bin/gorm.js +1 -1
  15. package/dist/bin/hekireki.js +5 -5
  16. package/dist/bin/kysely.js +1 -1
  17. package/dist/bin/openapi.js +1 -1
  18. package/dist/bin/pydantic.js +1 -1
  19. package/dist/bin/sea-orm.js +1 -1
  20. package/dist/bin/seed.js +1 -1
  21. package/dist/bin/sqlalchemy.js +1 -1
  22. package/dist/bin/typebox.js +1 -1
  23. package/dist/bin/valibot.js +1 -1
  24. package/dist/bin/zod.js +1 -1
  25. package/dist/{bin-T1le3lMh.js → bin-Bs0hPt0P.js} +966 -357
  26. package/dist/{discover-BaDQsKnF.js → discover-Dyzb_7x-.js} +1 -1
  27. package/dist/{emit-C4CeSye3.js → emit-CbBm_I0C.js} +1 -1
  28. package/dist/{migrate-2xlj7ayX.js → migrate-B-EMC7CC.js} +3 -3
  29. package/dist/{plan-B8PRmVdV.js → plan-DVBOCKsd.js} +3 -3
  30. package/dist/{prisma-model-DFq7AQgV.js → prisma-model-D98BBcmY.js} +12 -1
  31. package/dist/{run-BQlJs4wi.js → run-BKHmqvBJ.js} +4 -4
  32. package/dist/{schema-CfxnFLAw.js → schema-BRtObhQG.js} +1 -1
  33. package/dist/{sql-izRRI1Bi.js → sql-BYvD2bjK.js} +1 -1
  34. package/dist/{start-C7m4KyUz.js → start-KD0RjI3H.js} +128 -128
  35. package/dist/studio/assets/{chip-D4JuozFz.js → chip-Yqg0IG0j.js} +1 -1
  36. package/dist/studio/assets/{client-DTRYUhbF.js → client-C-v3Paav.js} +1 -1
  37. package/dist/studio/assets/{code-block-B7oBDy4S.js → code-block-CPMTXPBi.js} +1 -1
  38. package/dist/studio/assets/{confirm-dialog-DgDjONHy.js → confirm-dialog-CKCkchiq.js} +1 -1
  39. package/dist/studio/assets/{copy-CO4Wewxa.js → copy-BwEVZZV_.js} +1 -1
  40. package/dist/studio/assets/{copy-button-DDzfUcsZ.js → copy-button-jDpd_nhT.js} +1 -1
  41. package/dist/studio/assets/{docs-DyJ-qhu9.js → docs-CXORFY0Y.js} +1 -1
  42. package/dist/studio/assets/{enums._name-CcIWxnq0.js → enums._name-BUBU_WMt.js} +1 -1
  43. package/dist/studio/assets/{field-icon-DwOxCe9v.js → field-icon-C1wSRFKO.js} +1 -1
  44. package/dist/studio/assets/hooks-DXskM7gG.js +2 -0
  45. package/dist/studio/assets/{index-D2cpa83b.js → index-DzCcMC-d.js} +4 -4
  46. package/dist/studio/assets/{labels-BrdjOFB0.js → labels-B5gZ2suK.js} +1 -1
  47. package/dist/studio/assets/{lazyRouteComponent-CzElNsBd.js → lazyRouteComponent-8L8QSEt_.js} +1 -1
  48. package/dist/studio/assets/{lu-BwZ0uwaH.js → lu-CuC8O-Qz.js} +1 -1
  49. package/dist/studio/assets/{marked-text-CRUtsVYt.js → marked-text-B27DfhKS.js} +1 -1
  50. package/dist/studio/assets/{models._name-Drem1hqS.js → models._name-CQFgPD0T.js} +1 -1
  51. package/dist/studio/assets/{monaco-Doo5FK2W.js → monaco-CMwienx7.js} +1 -1
  52. package/dist/studio/assets/{monaco-CKCcdl6_.js → monaco-DRYJTcJl.js} +1 -1
  53. package/dist/studio/assets/{not-found-KT_nPOAU.js → not-found-69Bz9b3p.js} +1 -1
  54. package/dist/studio/assets/{prisma-4lQKwVn6.js → prisma-1nDx08Wb.js} +1 -1
  55. package/dist/studio/assets/{result-table-DY7sKJQq.js → result-table-0P18Nywh.js} +1 -1
  56. package/dist/studio/assets/routes-Bl7HRpBJ.js +1 -0
  57. package/dist/studio/assets/{schema-gate-Dq2l2Sh6.js → schema-gate-BmKFmHnL.js} +1 -1
  58. package/dist/studio/assets/schema-view-BEdx0cC2.js +9 -0
  59. package/dist/studio/assets/{sql-CjIkv--0.js → sql-GBZZtEKI.js} +1 -1
  60. package/dist/studio/assets/{table-BxRDQMeA.js → table-UZ-Yt-OH.js} +1 -1
  61. package/dist/studio/assets/{tabs-BwlFa2ot.js → tabs-BpZ0hh1V.js} +1 -1
  62. package/dist/studio/assets/{useFormValidation-DifOycKN.js → useFormValidation-CC75L7h9.js} +1 -1
  63. package/dist/studio/assets/{useMatch-D2UWqcDy.js → useMatch-BF6XlF2m.js} +1 -1
  64. package/dist/studio/assets/{useMultipleSelectionState-2b0OEWtf.js → useMultipleSelectionState-zIKA_ZNd.js} +1 -1
  65. package/dist/studio/index.html +9 -9
  66. package/package.json +10 -10
  67. package/dist/studio/assets/hooks-6J-1786l.js +0 -2
  68. package/dist/studio/assets/routes-D6hrrw5V.js +0 -1
  69. package/dist/studio/assets/schema-view-CnitOLrD.js +0 -9
@@ -1,6 +1,6 @@
1
- import { A as isSameList, C as getString, D as isAnnotationLine, E as indexPrefix, I as schemaFromFields, L as stripAnnotations, M as makePascalCase, N as makeSnakeCase, O as isFields, P as makeValidationExtractor, S as getBool, T as groupByModel, _ as tableName, a as isAutoincrement, b as constraintName, c as isJoinSideA, d as isUlidDefault, f as lengthArg, g as scalarFields, h as relationEnds, i as implicitJoinTables, l as isListDefault, m as referentialActions, n as columnName, o as isFunctionDefault, p as manyToManyRelations, r as fieldColumn, s as isImplicitManyToMany, t as backRelation, u as isNowDefault$1, v as uuidDefaultVersion, w as getStrings, x as extractObjectType } from "./prisma-model-DFq7AQgV.js";
2
- import { n as emitMany, r as emitRaw, t as emit } from "./emit-C4CeSye3.js";
3
- import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-CfxnFLAw.js";
1
+ import { C as getBool, D as indexPrefix, E as groupByModel, F as makeValidationExtractor, L as schemaFromFields, N as makePascalCase, O as isAnnotationLine, P as makeSnakeCase, R as stripAnnotations, S as extractObjectType, T as getStrings, _ as scalarFields, a as isAutoincrement, c as isJoinSideA, d as isUlidDefault, f as lengthArg, g as relationEnds, h as referentialActions, i as implicitJoinTables, j as isSameList, k as isFields, l as isListDefault, m as primaryKeyFields$1, n as columnName, o as isFunctionDefault, p as manyToManyRelations, r as fieldColumn, s as isImplicitManyToMany, t as backRelation, u as isNowDefault$1, v as tableName, w as getString, x as constraintName, y as uuidDefaultVersion } from "./prisma-model-D98BBcmY.js";
2
+ import { n as emitMany, r as emitRaw, t as emit } from "./emit-CbBm_I0C.js";
3
+ import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-BRtObhQG.js";
4
4
  import { Data, Effect } from "effect";
5
5
  import path from "node:path";
6
6
  import { layer } from "@effect/platform-node/NodeFileSystem";
@@ -8,173 +8,264 @@ import pkg from "@prisma/generator-helper";
8
8
  import { graphlib, layout } from "@dagrejs/dagre";
9
9
  import * as z from "zod";
10
10
  import { Resvg } from "@resvg/resvg-js";
11
- // src/utils/humanizer.ts
12
- function irregular(singular, plural) {
13
- return {
14
- plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
15
- singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
16
- };
17
- }
18
- function wholeWordIrregular(singular, plural) {
19
- return {
20
- plural: [`^${singular}$`, plural],
21
- singular: [`^${plural}$`, singular]
22
- };
23
- }
24
- const IRREGULARS = [
25
- irregular("person", "people"),
26
- irregular("man", "men"),
27
- irregular("human", "humans"),
28
- irregular("child", "children"),
29
- irregular("sex", "sexes"),
30
- irregular("glove", "gloves"),
31
- irregular("move", "moves"),
32
- irregular("goose", "geese"),
33
- irregular("wave", "waves"),
34
- irregular("foot", "feet"),
35
- irregular("tooth", "teeth"),
36
- irregular("curriculum", "curricula"),
37
- irregular("database", "databases"),
38
- irregular("zombie", "zombies"),
39
- irregular("personnel", "personnel"),
40
- irregular("cache", "caches"),
41
- wholeWordIrregular("ex", "exes"),
42
- wholeWordIrregular("is", "are"),
43
- wholeWordIrregular("that", "those"),
44
- wholeWordIrregular("this", "these"),
45
- wholeWordIrregular("bus", "buses"),
46
- wholeWordIrregular("die", "dice"),
47
- wholeWordIrregular("tie", "ties")
11
+ // src/utils/active-support.ts
12
+ const IRREGULARS$1 = [
13
+ ["person", "people"],
14
+ ["man", "men"],
15
+ ["child", "children"],
16
+ ["sex", "sexes"],
17
+ ["move", "moves"],
18
+ ["zombie", "zombies"]
48
19
  ];
49
- const PLURAL_RULES = [
20
+ const PLURAL_RULES$1 = [
50
21
  ["$", "s"],
51
22
  ["s$", "s"],
52
- ["(ax|test)is$", "$1es"],
53
- ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
54
- ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
55
- ["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
56
- ["([dti])um$", "$1a"],
23
+ ["^(ax|test)is$", "$1es"],
24
+ ["(octop|vir)us$", "$1i"],
25
+ ["(octop|vir)i$", "$1i"],
26
+ ["(alias|status)$", "$1es"],
27
+ ["(bu)s$", "$1ses"],
28
+ ["(buffal|tomat)o$", "$1oes"],
29
+ ["([ti])um$", "$1a"],
30
+ ["([ti])a$", "$1a"],
57
31
  ["sis$", "ses"],
58
32
  ["(?:([^f])fe|([lr])f)$", "$1$2ves"],
59
33
  ["(hive)$", "$1s"],
60
34
  ["([^aeiouy]|qu)y$", "$1ies"],
61
35
  ["(x|ch|ss|sh)$", "$1es"],
62
- ["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
63
- ["(^[m|l])ouse$", "$1ice"],
36
+ ["(matr|vert|ind)(?:ix|ex)$", "$1ices"],
37
+ ["^(m|l)ouse$", "$1ice"],
38
+ ["^(m|l)ice$", "$1ice"],
64
39
  ["^(ox)$", "$1en"],
40
+ ["^(oxen)$", "$1"],
65
41
  ["(quiz)$", "$1zes"],
66
- ["(buz|blit|walt)z$", "$1zes"],
67
- ["(hoo|lea|loa|thie)f$", "$1ves"],
68
- ["(alumn|alg|larv|vertebr)a$", "$1ae"],
69
- ["(criteri|phenomen)on$", "$1a"],
70
- ...IRREGULARS.map((rule) => rule.plural)
71
- ].map(([pattern, replacement]) => ({
42
+ ...IRREGULARS$1.flatMap(([singular = "", plural = ""]) => [[`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`], [`(${plural[0]})${plural.slice(1)}$`, `$1${plural.slice(1)}`]])
43
+ ].toReversed().map(([pattern = "", replacement = ""]) => ({
72
44
  pattern: new RegExp(pattern, "iu"),
73
45
  replacement
74
46
  }));
75
- const SINGULAR_RULES = [
47
+ const SINGULAR_RULES$1 = [
76
48
  ["s$", ""],
49
+ ["(ss)$", "$1"],
77
50
  ["(n)ews$", "$1ews"],
78
- ["([dti])a$", "$1um"],
79
- ["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
51
+ ["([ti])a$", "$1um"],
52
+ ["((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$", "$1sis"],
53
+ ["(^analy)(sis|ses)$", "$1sis"],
80
54
  ["([^f])ves$", "$1fe"],
81
55
  ["(hive)s$", "$1"],
82
56
  ["(tive)s$", "$1"],
83
- ["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
84
- ["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
57
+ ["([lr])ves$", "$1f"],
58
+ ["([^aeiouy]|qu)ies$", "$1y"],
85
59
  ["(s)eries$", "$1eries"],
86
60
  ["(m)ovies$", "$1ovie"],
87
61
  ["(x|ch|ss|sh)es$", "$1"],
88
- ["(^[m|l])ice$", "$1ouse"],
89
- ["(?<!^[a-z])(o)es$", "$1"],
62
+ ["^(m|l)ice$", "$1ouse"],
63
+ ["(bus)(es)?$", "$1"],
64
+ ["(o)es$", "$1"],
90
65
  ["(shoe)s$", "$1"],
91
- ["(cris|ax|test)es$", "$1is"],
92
- ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
93
- ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
66
+ ["(cris|test)(is|es)$", "$1is"],
67
+ ["^(a)x[ie]s$", "$1xis"],
68
+ ["(octop|vir)(us|i)$", "$1us"],
69
+ ["(alias|status)(es)?$", "$1"],
94
70
  ["^(ox)en", "$1"],
95
- ["(matr|d)ices$", "$1ix"],
96
71
  ["(vert|ind)ices$", "$1ex"],
72
+ ["(matr)ices$", "$1ix"],
97
73
  ["(quiz)zes$", "$1"],
98
- ["(buz|blit|walt)zes$", "$1z"],
99
- ["(alumn|alg|larv|vertebr)ae$", "$1a"],
100
- ["(criteri|phenomen)a$", "$1on"],
101
- ["([b|r|c]ook|room|smooth)ies$", "$1ie"],
102
- ...IRREGULARS.map((rule) => rule.singular)
103
- ].map(([pattern, replacement]) => ({
74
+ ["(database)s$", "$1"],
75
+ ...IRREGULARS$1.flatMap(([singular = "", plural = ""]) => [[`(${singular[0]})${singular.slice(1)}$`, `$1${singular.slice(1)}`], [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]])
76
+ ].toReversed().map(([pattern = "", replacement = ""]) => ({
104
77
  pattern: new RegExp(pattern, "iu"),
105
78
  replacement
106
79
  }));
107
- const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
108
- "staff",
109
- "training",
110
- "equipment",
111
- "information",
112
- "corn",
113
- "milk",
114
- "rice",
115
- "money",
116
- "species",
117
- "series",
118
- "fish",
119
- "sheep",
120
- "deer",
121
- "aircraft",
122
- "oz",
123
- "tsp",
124
- "tbsp",
125
- "ml",
126
- "l",
127
- "water",
128
- "waters",
129
- "semen",
130
- "sperm",
131
- "bison",
132
- "grass",
133
- "hair",
134
- "mud",
135
- "elk",
136
- "luggage",
137
- "moose",
138
- "offspring",
139
- "salmon",
140
- "shrimp",
141
- "someone",
142
- "swine",
143
- "trout",
144
- "tuna",
145
- "corps",
146
- "scissors",
147
- "means",
148
- "mail",
149
- "metadata"
150
- ]);
151
- function isUpperCaseLetter(char) {
152
- return char !== char.toLowerCase() && char === char.toUpperCase();
80
+ const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/iu;
81
+ function applyInflections(word, rules) {
82
+ if (word === "" || UNCOUNTABLE.test(word)) return word;
83
+ const rule = rules.find((candidate) => candidate.pattern.test(word));
84
+ return rule === void 0 ? word : word.replace(rule.pattern, rule.replacement);
153
85
  }
154
- function isLowerCaseLetter(char) {
155
- return char !== char.toUpperCase() && char === char.toLowerCase();
86
+ /**
87
+ * ActiveSupport's `pluralize`: the table Rails infers for a class is its `underscore`d name
88
+ * pluralized (`event_data` stays `event_data`, `person` is `people`).
89
+ *
90
+ * @param word - A singular word.
91
+ * @returns The plural Rails gives.
92
+ */
93
+ function pluralize$1(word) {
94
+ return applyInflections(word, PLURAL_RULES$1);
156
95
  }
157
- function applyRules(rules, word) {
158
- if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
159
- const rule = rules.findLast((candidate) => candidate.pattern.test(word));
160
- if (rule === void 0) return null;
161
- const result = word.replace(rule.pattern, rule.replacement);
162
- const first = result.charAt(0);
163
- return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
96
+ /**
97
+ * ActiveSupport's `singularize`: a collection association's class is its name singularized and
98
+ * camelized (`event_data` is `event_datum`, `site_settings` is `site_setting`).
99
+ *
100
+ * @param word - A plural word.
101
+ * @returns The singular Rails gives.
102
+ */
103
+ function singularize(word) {
104
+ return applyInflections(word, SINGULAR_RULES$1);
105
+ }
106
+ function capitalize(word) {
107
+ return `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`;
164
108
  }
165
109
  /**
166
- * Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
167
- * is returned as it is.
110
+ * ActiveSupport's `camelize`: each word after an underscore is capitalised, which lowers the rest
111
+ * of it (`api_key` is `ApiKey`, `user_ID` is `UserId`), and a slash is a namespace.
168
112
  *
169
- * @param word - The word to pluralize.
170
- * @returns The plural form Humanizer 2.14.1 gives.
113
+ * @param term - An underscored name.
114
+ * @returns The class name Rails gives.
171
115
  */
172
- function pluralize(word) {
173
- const result = applyRules(PLURAL_RULES, word);
174
- const asSingular = applyRules(SINGULAR_RULES, word);
175
- const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
176
- return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
116
+ function camelize(term) {
117
+ return term.replace(/^[a-z\d]*/u, capitalize).replaceAll(/(?:_|(\/))([a-z\d]*)/giu, (_match, slash, word) => `${slash === void 0 ? "" : "::"}${capitalize(word)}`);
118
+ }
119
+ /**
120
+ * ActiveSupport's `underscore`: a capital starts a word after a lower-case letter or a digit, or
121
+ * before a lower-case letter after a capital (`HTTPLog` is `http_log`), and a namespace is a slash.
122
+ *
123
+ * @param word - A class name.
124
+ * @returns The underscored name Rails gives.
125
+ */
126
+ function underscore(word) {
127
+ if (!/[A-Z-]|::/u.test(word)) return word;
128
+ return word.replaceAll("::", "/").replaceAll(/(?<=[A-Z])(?=[A-Z][a-z])|(?<=[a-z\d])(?=[A-Z])/gu, "_").replaceAll("-", "_").toLowerCase();
177
129
  }
130
+ // src/utils/naming.ts
131
+ /**
132
+ * A Prisma name as a type name: the underscores join words, each word starts in upper case, and a
133
+ * word in capitals throughout (`PENDING`, `ID`) is lower-cased after its first letter; any other
134
+ * casing is the schema author's and is kept (`sku_code` → `SkuCode`, `userID` → `UserID`,
135
+ * `PENDING_REVIEW` → `PendingReview`).
136
+ *
137
+ * @param name - A Prisma model, field or enum value name.
138
+ * @returns The PascalCase name.
139
+ */
140
+ function pascalCase(name) {
141
+ const text = name.split("_").filter((word) => word !== "").map((word) => {
142
+ const rest = word.slice(1);
143
+ return `${word.charAt(0).toUpperCase()}${word === word.toUpperCase() ? rest.toLowerCase() : rest}`;
144
+ }).join("");
145
+ return /^\p{L}/u.test(text) ? text : `_${text}`;
146
+ }
147
+ /**
148
+ * The first of `candidate`, `candidate1`, `candidate2`, ... that is free — the numbering
149
+ * `dotnet ef dbcontext scaffold` gives names that collide, which the other generators follow too.
150
+ *
151
+ * @param candidate - The preferred name.
152
+ * @param isTaken - Whether a name is already in use.
153
+ * @returns A free name.
154
+ */
155
+ function uniqueName(candidate, isTaken) {
156
+ if (!isTaken(candidate)) return candidate;
157
+ for (let index = 1; index <= 1e4; index += 1) if (!isTaken(`${candidate}${index}`)) return `${candidate}${index}`;
158
+ return candidate;
159
+ }
160
+ function allocate(candidates, reserved, fold) {
161
+ const names = /* @__PURE__ */ new Map();
162
+ const taken = new Set(reserved.map(fold));
163
+ for (const { key, candidate } of candidates) {
164
+ const name = uniqueName(candidate, (one) => taken.has(fold(one)));
165
+ names.set(key, name);
166
+ taken.add(fold(name));
167
+ }
168
+ return names;
169
+ }
170
+ // src/helper/activerecord-names.ts
171
+ const ACTIVE_RECORD_INSTANCE_METHODS = new Set(`
172
+ __callbacks __id__ _assign_attribute _assign_attributes _before_commit_callbacks
173
+ _clear_locking_column _commit_callbacks _committed_already_called _create_callbacks _create_record
174
+ _delete_row _destroy _destroy_callbacks _ensure_no_duplicate_errors _find_callbacks _find_record
175
+ _in_memory_query_constraints_hash _initialize_callbacks _last_transaction_return_status
176
+ _lock_value_for_database _marshal_dump_7_1 _merge_attributes _new_record_before_last_commit
177
+ _query_attribute _query_constraints_hash _raise_readonly_record_error _raise_record_not_destroyed
178
+ _raise_record_not_touched_error _read_attribute _reflections _rollback_callbacks
179
+ _run_before_commit_callbacks _run_commit_callbacks _run_create_callbacks _run_destroy_callbacks
180
+ _run_find_callbacks _run_initialize_callbacks _run_rollback_callbacks _run_save_callbacks
181
+ _run_touch_callbacks _run_update_callbacks _run_validate_callbacks _run_validation_callbacks
182
+ _save_callbacks _touch_callbacks _touch_row _trigger_destroy_callback _trigger_update_callback
183
+ _update_callbacks _update_record _update_row _validate_callbacks _validation_callbacks _validators
184
+ _write_attribute accessed_fields add_to_transaction aggregate_reflections
185
+ all_attributes_for_inspect all_timestamp_attributes_in_model around_save_collection_association
186
+ assign_attributes assign_multiparameter_attributes
187
+ assign_nested_attributes_for_collection_association
188
+ assign_nested_attributes_for_one_to_one_association assign_nested_parameter_attributes
189
+ assign_to_or_mark_for_destruction associated_records_to_validate_or_save association
190
+ association_instance_get association_instance_set attachment_changes attachment_reflections
191
+ attribute attribute_aliases attribute_before_last_save attribute_before_type_cast attribute_change
192
+ attribute_change_to_be_saved attribute_for_database attribute_for_inspect attribute_in_database
193
+ attribute_method_patterns attribute_missing attribute_names attribute_names_for_partial_inserts
194
+ attribute_names_for_partial_updates attribute_names_for_serialization attribute_previous_change
195
+ attribute_previously_was attribute_was attribute_writer_missing attributes
196
+ attributes_before_type_cast attributes_for_create attributes_for_database attributes_for_inspect
197
+ attributes_for_update attributes_in_database attributes_with_values automatic_scope_inversing
198
+ automatically_invert_plural_associations becomes build_decrypt_attribute_assignments
199
+ build_encrypt_attribute_assignments cache_key cache_key_with_version cache_timestamp_format
200
+ cache_version cache_versioning call_reject_if cant_modify_encrypted_attributes_when_frozen changed
201
+ changed_attribute_names_to_save changed_attributes changes changes_applied changes_to_save
202
+ ciphertext_for class clear_attribute_change clear_attribute_changes clear_changes_information
203
+ clear_timestamp_attributes clear_transaction_record_state clone collection_cache_versioning
204
+ column_for_attribute compute_primary_key connection_handler context_for_validation
205
+ counter_cached_association_names create_or_update current_time_from_proper_timezone decrement
206
+ decrypt decrypt_attributes decrypt_rich_texts default_connection_handler default_role
207
+ default_scope_override default_scopes default_shard default_validation_context defined_enums
208
+ delete deprecated_associations_api_guard destroy destroy_association_async_batch_size
209
+ destroy_association_async_job destroy_associations destroy_row destroyed_by_association dup
210
+ encode_with encrypt encrypt_attributes encrypt_rich_texts encryptable_rich_texts
211
+ encrypted_attributes ensure_proper_type errors execute_callstack_for_multiparameter_attributes
212
+ extract_callstack_for_multiparameter_attributes find_parameter_position find_record_by_id
213
+ forget_attribute_assignments format_for_inspect freeze from_json full_inspect generate_token_for
214
+ halted_callback_hook hash id id_before_type_cast id_for_database id_in_database id_was
215
+ include_root_in_json increment init_attributes init_internals init_with init_with_attributes
216
+ initialize_internals_callback inspect_with_attributes inspection_filter lock_optimistically logger
217
+ mark_for_destruction marshal_dump marshal_load matched_attribute_method
218
+ max_updated_column_timestamp missing_attribute model_name mutations_before_last_save
219
+ mutations_from_database nested_attributes_options normalize_attribute
220
+ normalize_changed_in_place_attributes normalized_attributes partial_inserts partial_updates
221
+ perform_validations pluralize_table_names populate_with_current_scope_attributes pretty_print
222
+ previous_changes primary_key_prefix_type query_attribute query_cast_attribute
223
+ raise_validation_error raw_timestamp_to_cache_version read_attribute
224
+ read_attribute_before_type_cast read_attribute_for_database read_attribute_for_serialization
225
+ read_attribute_for_validation read_store_attribute record_timestamps record_update_timestamps
226
+ reload remember_transaction_record_state report_deprecated_association restore_attributes
227
+ restore_transaction_record_state run_callbacks sanitize_for_mass_assignment
228
+ sanitize_forbidden_attributes save save_belongs_to_association save_collection_association
229
+ save_has_one_association saved_change_to_attribute saved_changes serializable_add_includes
230
+ serializable_attributes serializable_hash signed_id signed_id_verifier_secret
231
+ skip_time_zone_conversion_for_attributes slice store_accessor_for store_full_class_name
232
+ store_full_sti_class strict_loaded_associations strict_loading_mode surreptitiously_touch
233
+ table_name_prefix table_name_suffix time_zone_aware_attributes time_zone_aware_types
234
+ timestamp_attributes_for_create_in_model timestamp_attributes_for_update_in_model to_ary to_gid
235
+ to_gid_param to_global_id to_key to_model to_partial_path to_sgid to_sgid_param
236
+ to_signed_global_id toggle touch touch_deferred_attributes touch_later transaction
237
+ type_cast_attribute_value type_for_attribute update update_attribute update_column update_columns
238
+ validate validate_belongs_to_association validate_collection_association
239
+ validate_encryption_allowed validate_has_one_association validates_absence_of
240
+ validates_acceptance_of validates_comparison_of validates_confirmation_of validates_exclusion_of
241
+ validates_format_of validates_inclusion_of validates_length_of validates_numericality_of
242
+ validates_presence_of validates_size_of validates_with validation_context values_at
243
+ verify_readonly_attribute with_lock with_transaction_returning_status write_attribute
244
+ write_store_attribute
245
+ `.split(/\s+/u).filter((name) => name !== ""));
246
+ const RUBY_TOP_LEVEL_CONSTANTS = new Set(`
247
+ ARGF ARGV AbstractController ActionCable ActionController ActionDispatch ActionMailbox
248
+ ActionMailer ActionPack ActionText ActionView ActiveJob ActiveModel ActiveRecord ActiveStorage
249
+ ActiveSupport Addrinfo ApplicationRecord Arel ArgumentError Array Base64 BasicObject BasicSocket
250
+ BigDecimal BigMath Binding CGI Class ClosedQueueError Comparable Complex Concurrent
251
+ ConditionVariable Crass Cuid Cuid2 Data Date DateAndTime DateTime Delegator DidYouMean Digest Dir
252
+ ENV EOFError ERB Encoding EncodingError Enumerable Enumerator Errno ErrorHighlight Erubi Etc
253
+ Exception FalseClass Fiber FiberError File FileTest FileUtils Float FloatDomainError Forwardable
254
+ FrozenError GC Gem GlobalID Hash HashWithIndifferentAccess I18n IO IOError IPAddr IPSocket
255
+ IndexError Integer Interrupt JSON Kernel KeyError LoadError LocalJumpError Logger Loofah Mail
256
+ Marcel Marshal MatchData Math Method Mime MiniMime Module Monitor MonitorMixin Mutex NameError
257
+ Nanoid Net NilClass NoMatchingPatternError NoMatchingPatternKeyError NoMemoryError NoMethodError
258
+ Nokogiri NotImplementedError Numeric Object ObjectSpace OpenSSL ParseError Pathname Prism
259
+ PrismaDateTime Proc Process Psych Queue Racc Rack Ractor RactorLocalSingleton Rails Rake Random
260
+ Range RangeError Rational RbConfig Refinement Regexp RegexpError Ruby RubyVM RuntimeError SQLite3
261
+ STDERR STDIN STDOUT ScanError ScriptError SecureRandom SecurityError Set Shellwords Signal
262
+ SignalException SignedGlobalID SimpleDelegator SingleForwardable Singleton SizedQueue Socket
263
+ SocketError StandardError StopIteration String StringIO StringScanner Struct Symbol SyntaxError
264
+ SyntaxSuggest SystemCallError SystemExit SystemStackError TCPServer TCPSocket TSort TZInfo
265
+ Tempfile Thread ThreadError ThreadGroup Time Timeout TracePoint Trix TrueClass TypeError UDPSocket
266
+ ULID UNIXServer UNIXSocket URI UnboundMethod UncaughtThrowError UnicodeNormalize Warning WeakRef
267
+ YAML Zeitwerk ZeroDivisionError Zlib
268
+ `.split(/\s+/u).filter((name) => name !== ""));
178
269
  // src/helper/activerecord.ts
179
270
  const RAILS_RESERVED_NAMES = new Set(`abort
180
271
  abstract_class
@@ -912,6 +1003,54 @@ writer_method
912
1003
  yaml_encoder
913
1004
  yaml_tag
914
1005
  yield_self`.split("\n"));
1006
+ /**
1007
+ * The class each model is written as: its name in PascalCase, or where Ruby or Rails already has
1008
+ * a constant of that name at the top level, that name with `Record` after it (`Monitor` is
1009
+ * `MonitorRecord`), numbered on where another model has that one too. Names are compared as the
1010
+ * files Zeitwerk loads them from, so two never share one.
1011
+ *
1012
+ * @param models - Every model of the schema.
1013
+ * @returns The class name of each model, by the model's name.
1014
+ */
1015
+ function activeRecordClassNames(models) {
1016
+ const own = models.map((model) => ({
1017
+ key: model.name,
1018
+ candidate: makePascalCase(model.name)
1019
+ }));
1020
+ const renamed = allocate(own.filter(({ candidate }) => RUBY_TOP_LEVEL_CONSTANTS.has(candidate)).map(({ key, candidate }) => ({
1021
+ key,
1022
+ candidate: `${candidate}Record`
1023
+ })), [...RUBY_TOP_LEVEL_CONSTANTS, ...own.map(({ candidate }) => candidate)], makeSnakeCase);
1024
+ return new Map(own.map(({ key, candidate }) => [key, renamed.get(key) ?? candidate]));
1025
+ }
1026
+ function railsNames(models) {
1027
+ const classNames = activeRecordClassNames(models);
1028
+ const classOf = (modelName) => classNames.get(modelName) ?? makePascalCase(modelName);
1029
+ const associations = new Map(models.map((model) => {
1030
+ const named = relationEnds(model, models).map(({ field }) => ({
1031
+ field,
1032
+ name: makeSnakeCase(field.name)
1033
+ }));
1034
+ const taken = /* @__PURE__ */ new Set([
1035
+ ...ACTIVE_RECORD_INSTANCE_METHODS,
1036
+ ...named.map(({ name }) => name),
1037
+ ...model.fields.filter((f) => f.kind !== "object").map((f) => f.dbName ?? f.name)
1038
+ ]);
1039
+ const renamed = allocate(named.filter(({ name }) => ACTIVE_RECORD_INSTANCE_METHODS.has(name)).map(({ field, name }) => {
1040
+ const target = underscore(classOf(field.type));
1041
+ const conventional = field.isList ? pluralize$1(target) : target;
1042
+ return {
1043
+ key: field.name,
1044
+ candidate: taken.has(conventional) ? `${underscore(classOf(model.name))}_${name}` : conventional
1045
+ };
1046
+ }), [...taken], makeSnakeCase);
1047
+ return [model.name, new Map(named.map(({ field, name }) => [field.name, renamed.get(field.name) ?? name]))];
1048
+ }));
1049
+ return {
1050
+ classOf,
1051
+ associationOf: (modelName, fieldName) => associations.get(modelName)?.get(fieldName) ?? makeSnakeCase(fieldName)
1052
+ };
1053
+ }
915
1054
  function primaryKeyFields(model) {
916
1055
  const idField = model.fields.find((f) => f.isId);
917
1056
  return idField ? [idField.name] : model.primaryKey?.fields ?? [];
@@ -1176,8 +1315,9 @@ function yamlLines(tree, depth) {
1176
1315
  * (`activerecord.errors.models.todo.attributes.title.blank`).
1177
1316
  */
1178
1317
  function activeRecordLocaleFiles(models) {
1318
+ const { classOf, associationOf } = railsNames(models);
1179
1319
  return models.flatMap((model) => {
1180
- const modelKey = makeSnakeCase(model.name);
1320
+ const modelKey = underscore(classOf(model.name));
1181
1321
  const trees = /* @__PURE__ */ new Map();
1182
1322
  const tree = (locale) => {
1183
1323
  const found = trees.get(locale) ?? {};
@@ -1195,7 +1335,7 @@ function activeRecordLocaleFiles(models) {
1195
1335
  ], m.text);
1196
1336
  }
1197
1337
  for (const field of model.fields) {
1198
- const attribute = field.kind === "object" ? makeSnakeCase(field.name) : field.dbName ?? field.name;
1338
+ const attribute = field.kind === "object" ? associationOf(model.name, field.name) : field.dbName ?? field.name;
1199
1339
  for (const call of arCalls(field.documentation, "field").calls) {
1200
1340
  const { validator, messages } = validatorCall(call);
1201
1341
  if (field.kind === "object" && validator !== "name") continue;
@@ -1318,11 +1458,13 @@ function nativeLength(field) {
1318
1458
  function activeRecordModels(models, allModels, enums, provider) {
1319
1459
  const contextModels = allModels ?? models;
1320
1460
  const enumMap = new Map((enums ?? []).map((e) => [e.name, e.values]));
1461
+ const { classOf, associationOf } = railsNames(contextModels);
1321
1462
  return models.map((model) => {
1322
1463
  const associations = getAssociations$5(model, contextModels);
1323
- const className = makePascalCase(model.name);
1464
+ const className = classOf(model.name);
1465
+ const modelSnake = underscore(className);
1324
1466
  const tableName = model.dbName ?? model.name;
1325
- const tableNameLines = tableName === pluralize(makeSnakeCase(model.name)) ? [] : [`self.table_name = "${tableName}"`];
1467
+ const tableNameLines = tableName === pluralize$1(modelSnake) ? [] : [`self.table_name = "${tableName}"`];
1326
1468
  const idField = model.fields.find((f) => f.isId);
1327
1469
  const compositePkColumns = (model.primaryKey?.fields ?? []).map((name) => fieldColumn(model, name));
1328
1470
  const primaryKeyLines = idField ? (idField.dbName ?? idField.name) !== "id" ? [`self.primary_key = "${idField.dbName ?? idField.name}"`] : [] : compositePkColumns.length > 0 ? [`self.primary_key = ${rubyArray(compositePkColumns.map((c) => `"${c}"`))}`] : [];
@@ -1444,26 +1586,28 @@ function activeRecordModels(models, allModels, enums, provider) {
1444
1586
  ].filter((rule) => !own.some(({ validator }) => validator === rule.split(":")[0])), ...own.flatMap(({ option }) => option === null ? [] : [option])];
1445
1587
  return [...rules.length === 0 ? [] : [rubyCall("validates", [`:${f.dbName ?? f.name}`], rules)], ...uniqueness.slice(1).map((rule) => rubyCall("validates", [`:${f.dbName ?? f.name}`], [rule]))];
1446
1588
  });
1447
- const modelSnake = makeSnakeCase(model.name);
1448
1589
  const belongsToLines = associations.belongsTo.map((a) => {
1449
- const name = makeSnakeCase(a.name);
1450
- const conventional = name === makeSnakeCase(a.targetModel) && a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${name}_id` && a.referencesPrimaryKey && a.inverse !== null && !a.inverseIsList && makeSnakeCase(a.inverse) === modelSnake;
1590
+ const name = associationOf(model.name, a.name);
1591
+ const targetClass = classOf(a.targetModel);
1592
+ const inverse = a.inverse === null ? null : associationOf(a.targetModel, a.inverse);
1593
+ const conventional = name === underscore(targetClass) && a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${name}_id` && a.referencesPrimaryKey && inverse !== null && !a.inverseIsList && inverse === modelSnake;
1451
1594
  return rubyCall("belongs_to", [`:${name}`], [
1452
- ...makePascalCase(a.targetModel) === makePascalCase(name) ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1595
+ ...camelize(name) === targetClass ? [] : [`class_name: "${targetClass}"`],
1453
1596
  ...a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${name}_id` ? [] : [foreignKeyOpt(a.foreignKeyColumns)],
1454
1597
  ...primaryKeyOpt(a.primaryKeyColumns, a.referencesPrimaryKey),
1455
1598
  ...a.optional ? ["optional: true"] : [],
1456
- ...a.inverse === null || conventional ? [] : [`inverse_of: :${makeSnakeCase(a.inverse)}`]
1599
+ ...inverse === null || conventional ? [] : [`inverse_of: :${inverse}`]
1457
1600
  ]);
1458
1601
  });
1459
1602
  const hasLines = (macro, list) => list.map((a) => {
1460
- const name = makeSnakeCase(a.name);
1461
- const inverse = makeSnakeCase(a.inverse);
1462
- const conventional = a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${modelSnake}_id` && a.referencesPrimaryKey && inverse === modelSnake && name === (macro === "has_many" ? pluralize(makeSnakeCase(a.targetModel)) : makeSnakeCase(a.targetModel));
1463
- const derivedClass = macro === "has_many" ? name === pluralize(makeSnakeCase(a.targetModel)) : makePascalCase(name) === makePascalCase(a.targetModel);
1603
+ const name = associationOf(model.name, a.name);
1604
+ const inverse = associationOf(a.targetModel, a.inverse);
1605
+ const targetClass = classOf(a.targetModel);
1606
+ const derivedClass = camelize(macro === "has_many" ? singularize(name) : name) === targetClass;
1607
+ const conventional = a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${modelSnake}_id` && a.referencesPrimaryKey && inverse === modelSnake && derivedClass;
1464
1608
  const dependent = DEPENDENT[a.onDelete];
1465
1609
  return rubyCall(macro, [`:${name}`], [
1466
- ...derivedClass ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1610
+ ...derivedClass ? [] : [`class_name: "${targetClass}"`],
1467
1611
  ...a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${modelSnake}_id` ? [] : [foreignKeyOpt(a.foreignKeyColumns)],
1468
1612
  ...primaryKeyOpt(a.primaryKeyColumns, a.referencesPrimaryKey),
1469
1613
  ...conventional ? [] : [`inverse_of: :${inverse}`],
@@ -1473,9 +1617,10 @@ function activeRecordModels(models, allModels, enums, provider) {
1473
1617
  const hasOneLines = hasLines("has_one", associations.hasOne);
1474
1618
  const hasManyLines = hasLines("has_many", associations.hasMany);
1475
1619
  const habtmLines = associations.habtm.map((a) => {
1476
- const name = makeSnakeCase(a.name);
1620
+ const name = associationOf(model.name, a.name);
1621
+ const targetClass = classOf(a.targetModel);
1477
1622
  return rubyCall("has_and_belongs_to_many", [`:${name}`], [
1478
- ...name === pluralize(makeSnakeCase(a.targetModel)) ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1623
+ ...camelize(singularize(name)) === targetClass ? [] : [`class_name: "${targetClass}"`],
1479
1624
  `join_table: "${a.joinTable}"`,
1480
1625
  `foreign_key: "${a.foreignKey}"`,
1481
1626
  `association_foreign_key: "${a.associationForeignKey}"`
@@ -1565,8 +1710,9 @@ end
1565
1710
  return [];
1566
1711
  }
1567
1712
  function activeRecordModelFiles(models, enums, provider) {
1713
+ const classNames = activeRecordClassNames(models);
1568
1714
  return models.map((model) => ({
1569
- fileName: `${makeSnakeCase(model.name)}.rb`,
1715
+ fileName: `${makeSnakeCase(classNames.get(model.name) ?? model.name)}.rb`,
1570
1716
  code: `${activeRecordModels([model], models, enums, provider)}\n`
1571
1717
  })).filter((entry) => entry.code.trim().length > 0);
1572
1718
  }
@@ -1832,7 +1978,7 @@ function prismaConstraintName(base, suffix, limit = IDENTIFIER_LIMIT) {
1832
1978
  const chars = [...base.matchAll(/./gsu)].map(([char]) => char);
1833
1979
  return `${chars.filter((_, index) => utf8Length(chars.slice(0, index + 1).join("")) <= room).join("")}${suffix}`;
1834
1980
  }
1835
- function modelIndexes(model, indexes) {
1981
+ function modelIndexes$1(model, indexes) {
1836
1982
  const own = indexes.filter((index) => index.model === model.name);
1837
1983
  if (own.length > 0) return own;
1838
1984
  const primaryKey = model.primaryKey?.fields ?? model.fields.filter((f) => f.isId).map((f) => f.name);
@@ -2329,7 +2475,7 @@ function makeAtlasForeignKeys(model, models, defaultSchema) {
2329
2475
  }
2330
2476
  function makeAtlasIndexes(model, indexes, dialect) {
2331
2477
  const table = tableNameOf(model);
2332
- return indexes.filter((idx) => idx.model === model.name && idx.type !== "id").map((idx) => {
2478
+ return indexes.filter((idx) => idx.model === model.name && idx.type !== "id" && idx.fields.every((f) => model.fields.some((field) => field.name === f.name))).map((idx) => {
2333
2479
  const colsDb = idx.fields.map((f) => columnDbName(model, f.name));
2334
2480
  const suffix = idx.type === "unique" ? "key" : "idx";
2335
2481
  const name = idx.dbName ?? `${table}_${colsDb.join("_")}_${suffix}`;
@@ -2575,8 +2721,57 @@ const CHOICES_RESERVED = /* @__PURE__ */ new Set([
2575
2721
  "names",
2576
2722
  "mro"
2577
2723
  ]);
2724
+ const STR_METHODS = /* @__PURE__ */ new Set([
2725
+ "capitalize",
2726
+ "casefold",
2727
+ "center",
2728
+ "count",
2729
+ "encode",
2730
+ "endswith",
2731
+ "expandtabs",
2732
+ "find",
2733
+ "format",
2734
+ "format_map",
2735
+ "index",
2736
+ "isalnum",
2737
+ "isalpha",
2738
+ "isascii",
2739
+ "isdecimal",
2740
+ "isdigit",
2741
+ "isidentifier",
2742
+ "islower",
2743
+ "isnumeric",
2744
+ "isprintable",
2745
+ "isspace",
2746
+ "istitle",
2747
+ "isupper",
2748
+ "join",
2749
+ "ljust",
2750
+ "lower",
2751
+ "lstrip",
2752
+ "maketrans",
2753
+ "partition",
2754
+ "removeprefix",
2755
+ "removesuffix",
2756
+ "replace",
2757
+ "rfind",
2758
+ "rindex",
2759
+ "rjust",
2760
+ "rpartition",
2761
+ "rsplit",
2762
+ "rstrip",
2763
+ "split",
2764
+ "splitlines",
2765
+ "startswith",
2766
+ "strip",
2767
+ "swapcase",
2768
+ "title",
2769
+ "translate",
2770
+ "upper",
2771
+ "zfill"
2772
+ ]);
2578
2773
  function enumMemberName(valueName) {
2579
- return PYTHON_KEYWORDS.has(valueName) || CHOICES_RESERVED.has(valueName) ? `${valueName}_` : valueName;
2774
+ return PYTHON_KEYWORDS.has(valueName) || CHOICES_RESERVED.has(valueName) || STR_METHODS.has(valueName) ? `${valueName}_` : valueName;
2580
2775
  }
2581
2776
  function resolveDjangoField(field) {
2582
2777
  const base = prismaTypeToDjangoField(field.type);
@@ -2726,24 +2921,53 @@ function claimName(preferred, taken) {
2726
2921
  taken.add(name);
2727
2922
  return name;
2728
2923
  }
2924
+ const MODULE_NAMES$1 = /* @__PURE__ */ new Set([
2925
+ "models",
2926
+ "timezone",
2927
+ "uuid",
2928
+ "uuid6",
2929
+ "datetime",
2930
+ "date",
2931
+ "time",
2932
+ "utc_today",
2933
+ "utc_time",
2934
+ "uuid4_str",
2935
+ "uuid7_str",
2936
+ "ulid_str",
2937
+ "list",
2938
+ "dict"
2939
+ ]);
2729
2940
  function modelAttrNames(model, m2mTables) {
2730
2941
  const belongsTo = singleColumnBelongsTo(model);
2731
2942
  const fkByScalarName = new Map(belongsTo.map((f) => [f.relationFromFields?.[0], f]));
2732
2943
  const taken = /* @__PURE__ */ new Set(["pk"]);
2733
2944
  const names = /* @__PURE__ */ new Map();
2734
- for (const field of model.fields) {
2945
+ const unresolved = {
2946
+ attr: /* @__PURE__ */ new Map(),
2947
+ helper: /* @__PURE__ */ new Map()
2948
+ };
2949
+ const reads = model.fields.map((field) => {
2950
+ if (field.kind === "object") return field.isList && isDeclaringM2MSide(model, field, m2mTables) ? ["models"] : [];
2951
+ return ["models", ...formatDefaultArgs(model, field, false, unresolved).map((arg) => /^\w+=([a-z_]\w*)/u.exec(arg)?.[1]).filter((name) => name !== void 0)];
2952
+ });
2953
+ for (const [i, field] of model.fields.entries()) {
2954
+ const readLater = new Set(reads.slice(i + 1).flat());
2955
+ const attrFor = (prismaName) => {
2956
+ const attr = djangoAttrName(makeSnakeCase(prismaName));
2957
+ return MODULE_NAMES$1.has(attr) && readLater.has(attr) ? `${attr}_field` : attr;
2958
+ };
2735
2959
  if (field.kind === "object") {
2736
- if (field.isList && isDeclaringM2MSide(model, field, m2mTables)) names.set(field.name, claimName(djangoAttrName(makeSnakeCase(field.name)), taken));
2960
+ if (field.isList && isDeclaringM2MSide(model, field, m2mTables)) names.set(field.name, claimName(attrFor(field.name), taken));
2737
2961
  continue;
2738
2962
  }
2739
2963
  const owner = fkByScalarName.get(field.name);
2740
2964
  if (owner) {
2741
- const attr = claimName(djangoAttrName(makeSnakeCase(owner.name)), taken);
2965
+ const attr = claimName(attrFor(owner.name), taken);
2742
2966
  names.set(owner.name, attr);
2743
2967
  names.set(field.name, attr);
2744
2968
  continue;
2745
2969
  }
2746
- names.set(field.name, claimName(djangoAttrName(makeSnakeCase(field.name)), taken));
2970
+ names.set(field.name, claimName(attrFor(field.name), taken));
2747
2971
  }
2748
2972
  return names;
2749
2973
  }
@@ -2753,7 +2977,8 @@ function resolveNames(models, m2mTables = []) {
2753
2977
  const takenHelpers = /* @__PURE__ */ new Set([
2754
2978
  "uuid4_str",
2755
2979
  "uuid7_str",
2756
- "ulid_str"
2980
+ "ulid_str",
2981
+ ...attr.values()
2757
2982
  ]);
2758
2983
  const helper = /* @__PURE__ */ new Map();
2759
2984
  for (const model of models) for (const field of model.fields) {
@@ -2933,7 +3158,7 @@ function generateScalarField(model, field, isPk, names, provider) {
2933
3158
  const outerArgs = [
2934
3159
  isPk ? "primary_key=True" : null,
2935
3160
  !field.isList && !field.isRequired ? "null=True" : null,
2936
- field.isUnique ? "unique=True" : null,
3161
+ field.isUnique && !isPk ? "unique=True" : null,
2937
3162
  attrName !== columnName ? `db_column=${toPythonString(columnName)}` : null,
2938
3163
  ...defaultArgs,
2939
3164
  emptyStringPk ? "default=None" : null
@@ -2949,11 +3174,11 @@ const ON_DELETE = {
2949
3174
  NoAction: "models.DO_NOTHING",
2950
3175
  SetDefault: "models.SET_DEFAULT"
2951
3176
  };
2952
- function onDeleteFor(field) {
2953
- if (field.relationOnDelete && ON_DELETE[field.relationOnDelete]) return ON_DELETE[field.relationOnDelete];
2954
- return field.isRequired ? "models.RESTRICT" : "models.SET_NULL";
3177
+ function onDeleteFor(relationField, scalarField) {
3178
+ if (relationField.relationOnDelete && ON_DELETE[relationField.relationOnDelete]) return ON_DELETE[relationField.relationOnDelete];
3179
+ return scalarField.isRequired ? "models.RESTRICT" : "models.SET_NULL";
2955
3180
  }
2956
- function generateForeignKeyField(model, relationField, scalarField, allModels, names) {
3181
+ function generateForeignKeyField(model, relationField, scalarField, allModels, names, isPk) {
2957
3182
  const attrName = attrNameOf(names, model, relationField);
2958
3183
  const columnName = fieldColumnName(scalarField);
2959
3184
  const backField = backRelation(relationField, model, allModels);
@@ -2963,16 +3188,18 @@ function generateForeignKeyField(model, relationField, scalarField, allModels, n
2963
3188
  const targetModel = allModels.find((m) => m.name === relationField.type);
2964
3189
  const referencedName = relationField.relationToFields?.[0];
2965
3190
  const referencedField = targetModel?.fields.find((f) => f.name === referencedName);
2966
- const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
3191
+ const targetPk = targetModel ? primaryKeyFields$1(targetModel) : [];
3192
+ const toField = referencedField && targetModel && !(targetPk.length === 1 && targetPk[0] === referencedName) ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
2967
3193
  return ` ${attrName} = models.${ctor}(${[
2968
3194
  target,
2969
- `on_delete=${onDeleteFor(relationField)}`,
3195
+ `on_delete=${onDeleteFor(relationField, scalarField)}`,
2970
3196
  `related_name=${relatedName}`,
2971
3197
  toField,
3198
+ isPk ? "primary_key=True" : null,
2972
3199
  columnName !== `${attrName}_id` ? `db_column=${toPythonString(columnName)}` : null,
2973
- !relationField.isRequired ? "null=True" : null,
3200
+ !scalarField.isRequired ? "null=True" : null,
2974
3201
  ctor === "ForeignKey" ? "db_index=False" : null,
2975
- ...formatDefaultArgs(model, scalarField, false, names)
3202
+ ...formatDefaultArgs(model, scalarField, isPk, names)
2976
3203
  ].filter((a) => a !== null).join(", ")})`;
2977
3204
  }
2978
3205
  function uniqueClassName(preferred, taken) {
@@ -3069,10 +3296,10 @@ function generateMetaLines(model, indexes, names) {
3069
3296
  return fieldObj ? fieldColumnName(fieldObj) : prismaFieldName;
3070
3297
  };
3071
3298
  const uniqueIndexes = indexes.filter((idx) => idx.model === model.name && idx.type === "unique" && !idx.isDefinedOnField);
3072
- const constraints = model.uniqueFields.map((fields) => {
3299
+ const constraints = model.uniqueFields.filter((fields) => coversWrittenFields(model, fields)).map((fields) => {
3073
3300
  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`)})`;
3074
3301
  });
3075
- const indexEntries = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
3302
+ const indexEntries = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext") && coversWrittenFields(model, idx.fields.map((f) => f.name))).map((idx) => {
3076
3303
  const fieldNames = idx.fields.map((f) => {
3077
3304
  const ref = fieldRef(f.name);
3078
3305
  return toPythonString(f.sortOrder === "desc" ? `-${ref}` : ref);
@@ -3092,14 +3319,14 @@ function generateMetaLines(model, indexes, names) {
3092
3319
  ] : [],
3093
3320
  ...indexEntries.length > 0 ? [
3094
3321
  " indexes = [",
3095
- ...indexEntries.map((i) => ` ${i},`),
3322
+ ...[...new Set(indexEntries)].map((i) => ` ${i},`),
3096
3323
  " ]"
3097
3324
  ] : []
3098
3325
  ];
3099
3326
  }
3100
3327
  function compositePkLine(model, names) {
3101
- const pkFields = model.primaryKey?.fields ?? [];
3102
- if (pkFields.length === 0) return null;
3328
+ const pkFields = primaryKeyFields$1(model);
3329
+ if (pkFields.length < 2) return null;
3103
3330
  const belongsTo = singleColumnBelongsTo(model);
3104
3331
  return ` pk = models.CompositePrimaryKey(${pkFields.map((prismaFieldName) => {
3105
3332
  const attr = names.attr.get(nameKey(model.name, prismaFieldName)) ?? prismaFieldName;
@@ -3114,12 +3341,14 @@ function findNameConflicts(models, enums) {
3114
3341
  }
3115
3342
  return [...byEnumClass].filter(([, owners]) => owners.length > 1).map(([className, owners]) => `enums ${owners.join(" and ")} both produce the Python class ${className}. Rename one of them.`);
3116
3343
  }
3117
- function hasPrimaryKey(model) {
3118
- return model.fields.some((f) => f.isId) || (model.primaryKey?.fields.length ?? 0) > 0;
3344
+ function coversWrittenFields(model, fieldNames) {
3345
+ return fieldNames.every((name) => model.fields.some((f) => f.name === name));
3119
3346
  }
3120
3347
  function generateModelBody$1(model, allModels, indexes, m2mTables, names, provider) {
3121
- if (!hasPrimaryKey(model)) return null;
3348
+ const pkFields = primaryKeyFields$1(model);
3349
+ if (pkFields.length === 0) return null;
3122
3350
  const compositePk = compositePkLine(model, names);
3351
+ const singlePk = pkFields.length === 1 ? pkFields[0] : void 0;
3123
3352
  const belongsTo = singleColumnBelongsTo(model);
3124
3353
  const fkByScalarName = new Map(belongsTo.map((f) => [f.relationFromFields?.[0], f]));
3125
3354
  const fieldLines = model.fields.flatMap((field) => {
@@ -3130,9 +3359,9 @@ function generateModelBody$1(model, allModels, indexes, m2mTables, names, provid
3130
3359
  }
3131
3360
  return [];
3132
3361
  }
3362
+ const isPk = field.name === singlePk;
3133
3363
  const owner = fkByScalarName.get(field.name);
3134
- if (owner) return [generateForeignKeyField(model, owner, field, allModels, names)];
3135
- const isPk = field.isId;
3364
+ if (owner) return [generateForeignKeyField(model, owner, field, allModels, names, isPk)];
3136
3365
  return [generateScalarField(model, field, isPk, names, provider)];
3137
3366
  });
3138
3367
  return [
@@ -3148,8 +3377,11 @@ function generateEnumClass(enumDef) {
3148
3377
  }
3149
3378
  function collectGlobalImports$1(models, indexes, provider) {
3150
3379
  const scalarFields = models.flatMap((m) => m.fields.filter((f) => f.kind !== "object"));
3151
- const modelNames = new Set(models.map((m) => m.name));
3152
- const indexClasses = indexes.filter((idx) => modelNames.has(idx.model) && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => postgresIndexClass(idx.algorithm)).filter((ctor) => ctor !== null);
3380
+ const modelsByName = new Map(models.map((m) => [m.name, m]));
3381
+ const indexClasses = indexes.filter((idx) => {
3382
+ const model = modelsByName.get(idx.model);
3383
+ return model !== void 0 && (idx.type === "normal" || idx.type === "fulltext") && coversWrittenFields(model, idx.fields.map((f) => f.name));
3384
+ }).map((idx) => postgresIndexClass(idx.algorithm)).filter((ctor) => ctor !== null);
3153
3385
  const needsUuid = scalarFields.some((f) => uuidDefaultVersion(f) === 4);
3154
3386
  const needsUuid6 = scalarFields.some((f) => uuidDefaultVersion(f) === 7);
3155
3387
  const needsUlid = scalarFields.some((f) => isUlidDefault(f));
@@ -3207,7 +3439,7 @@ function collectGlobalImports$1(models, indexes, provider) {
3207
3439
  // src/generator/django.ts
3208
3440
  function djangoCode(models, enums, indexes, provider = "postgresql") {
3209
3441
  const idx = indexes ?? [];
3210
- const emitted = models.filter((model) => hasPrimaryKey(model));
3442
+ const emitted = models.filter((model) => primaryKeyFields$1(model).length > 0);
3211
3443
  const m2mTables = collectManyToManyTables$1(emitted, enums);
3212
3444
  const names = resolveNames(emitted, m2mTables);
3213
3445
  return `${[
@@ -3401,6 +3633,7 @@ const COLUMN_HELPERS = {
3401
3633
  function createImports() {
3402
3634
  return {
3403
3635
  core: /* @__PURE__ */ new Set(),
3636
+ coreTypes: /* @__PURE__ */ new Set(),
3404
3637
  orm: /* @__PURE__ */ new Set(),
3405
3638
  ext: /* @__PURE__ */ new Map(),
3406
3639
  helpers: /* @__PURE__ */ new Set()
@@ -3440,8 +3673,15 @@ function applyImport(imports, req) {
3440
3673
  }
3441
3674
  function generateImports(imports, provider) {
3442
3675
  const mod = provider === "postgresql" ? "drizzle-orm/pg-core" : provider === "mysql" ? "drizzle-orm/mysql-core" : "drizzle-orm/sqlite-core";
3676
+ const coreNames = [...[...imports.core].map((name) => ({
3677
+ name,
3678
+ text: name
3679
+ })), ...[...imports.coreTypes].map((name) => ({
3680
+ name,
3681
+ text: `type ${name}`
3682
+ }))].toSorted((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3443
3683
  return [
3444
- imports.core.size > 0 ? `import { ${[...imports.core].toSorted().join(", ")} } from '${mod}'` : "",
3684
+ coreNames.length > 0 ? `import { ${coreNames.map((entry) => entry.text).join(", ")} } from '${mod}'` : "",
3445
3685
  imports.orm.size > 0 ? `import { ${[...imports.orm].toSorted().join(", ")} } from 'drizzle-orm'` : "",
3446
3686
  ...[...imports.ext.entries()].map(([pkg, entry]) => {
3447
3687
  return `import ${[entry.default, entry.named.size > 0 ? `{ ${[...entry.named].toSorted().join(", ")} }` : void 0].filter((c) => c !== void 0).join(", ")} from '${pkg}'`;
@@ -3692,7 +3932,7 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
3692
3932
  const columns = model.primaryKey.fields.map((f) => `table.${f}`).join(", ");
3693
3933
  return provider === "mysql" ? `primaryKey({ columns: [${columns}] })` : `primaryKey({ name: '${tableName}_pkey', columns: [${columns}] })`;
3694
3934
  })() : null;
3695
- const indexLines = indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
3935
+ const indexLines = indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext") && idx.fields.every((f) => model.fields.some((field) => field.name === f.name))).map((idx) => {
3696
3936
  const name = idx.dbName ?? constraintName(tableName, idx.fields.map((f) => fieldColumn(model, f.name)), idx.type === "unique" ? "key" : "idx", provider);
3697
3937
  const referenced = provider !== "sqlite" && models.some((m) => m.fields.some((f) => f.type === model.name && f.relationToFields?.join(",") === idx.fields.map((field) => field.name).join(",")));
3698
3938
  const make = idx.type !== "unique" ? "index" : referenced ? "unique" : "uniqueIndex";
@@ -3704,7 +3944,7 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
3704
3944
  return `sql\`\${table.${f.name}}(${prefix})\``;
3705
3945
  }).join(", ")})`;
3706
3946
  });
3707
- const fkLines = model.fields.filter((f) => f.kind === "object" && f.relationFromFields !== void 0 && f.relationFromFields.length > 0 && f.relationToFields !== void 0).map((f) => {
3947
+ const fkLines = model.fields.filter(isForeignKey).map((f) => {
3708
3948
  imports.core.add("foreignKey");
3709
3949
  const target = f.type === model.name ? "table" : resolveVarNameByType(f.type, models);
3710
3950
  const from = f.relationFromFields ?? [];
@@ -3719,6 +3959,19 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
3719
3959
  ].filter((l) => l !== null);
3720
3960
  return all.length > 0 ? all.join(", ") : null;
3721
3961
  }
3962
+ function isForeignKey(field) {
3963
+ return field.kind === "object" && field.relationFromFields !== void 0 && field.relationFromFields.length > 0 && field.relationToFields !== void 0;
3964
+ }
3965
+ function isOnForeignKeyCycle(model, models) {
3966
+ const targets = (name) => models.find((m) => m.name === name)?.fields.filter((f) => isForeignKey(f) && f.type !== name).map((f) => f.type) ?? [];
3967
+ const reaches = (from, seen) => {
3968
+ if (from.includes(model.name)) return true;
3969
+ const next = [...new Set(from.flatMap(targets))].filter((name) => !seen.has(name));
3970
+ return next.length > 0 && reaches(next, /* @__PURE__ */ new Set([...seen, ...next]));
3971
+ };
3972
+ const first = targets(model.name);
3973
+ return reaches(first, new Set(first));
3974
+ }
3722
3975
  function makeTable(model, models, provider, imports, enums, indexes) {
3723
3976
  const tableFunc = provider === "postgresql" ? "pgTable" : provider === "mysql" ? "mysqlTable" : "sqliteTable";
3724
3977
  imports.core.add(tableFunc);
@@ -3726,7 +3979,10 @@ function makeTable(model, models, provider, imports, enums, indexes) {
3726
3979
  const tableName = resolveTableName(model);
3727
3980
  const columns = model.fields.map((field) => makeColumn(field, model, models, provider, imports, enums)).filter((c) => c !== null).join(", ");
3728
3981
  const constraints = makeTableConstraints(model, models, provider, imports, indexes, tableName);
3729
- return constraints ? `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, (table) => [${constraints}])` : `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
3982
+ if (!constraints) return `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
3983
+ const configType = isOnForeignKeyCycle(model, models) ? provider === "postgresql" ? "PgTableExtraConfigValue" : provider === "mysql" ? "MySqlTableExtraConfigValue" : "SQLiteTableExtraConfigValue" : void 0;
3984
+ if (configType) imports.coreTypes.add(configType);
3985
+ return `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, ${configType ? `(table): ${configType}[]` : "(table)"} => [${constraints}])`;
3730
3986
  }
3731
3987
  function joinVarName(relationName) {
3732
3988
  return snakeToCamel(makeSnakeCase(relationName));
@@ -4415,9 +4671,8 @@ function ectoSchemas(models, app, allModels, enums, options = {}) {
4415
4671
  const contextModels = allModels ?? models;
4416
4672
  return models.map((model) => {
4417
4673
  const idField = model.fields.find((f) => f.isId);
4418
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
4674
+ const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
4419
4675
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
4420
- if (!(idField || isCompositePk)) return "";
4421
4676
  const pk = idField ? getPrimaryKeyConfig(idField) : {
4422
4677
  line: "@primary_key false",
4423
4678
  typeSpec: "",
@@ -4502,16 +4757,17 @@ function ectoSchemas(models, app, allModels, enums, options = {}) {
4502
4757
  if (a.references !== "id") opts.push(`references: :${a.references}`);
4503
4758
  return ` belongs_to(:${snakeAssocName}, ${appName}.${makePascalCase(a.targetModel)}, ${opts.join(", ")})`;
4504
4759
  });
4760
+ const namesReferences = (references) => references !== "id" || pk.line === "@primary_key false";
4505
4761
  const hasOneLines = associations.hasOne.map((a) => {
4506
4762
  const snakeFk = makeSnakeCase(a.foreignKey);
4507
4763
  const snakeAssocName = makeSnakeCase(a.name);
4508
- const referencesOpt = a.references === "id" ? "" : `, references: :${a.references}`;
4764
+ const referencesOpt = namesReferences(a.references) ? `, references: :${a.references}` : "";
4509
4765
  return ` has_one(:${snakeAssocName}, ${appName}.${makePascalCase(a.targetModel)}, foreign_key: :${snakeFk}${referencesOpt})`;
4510
4766
  });
4511
4767
  const hasManyLines = associations.hasMany.map((a) => {
4512
4768
  const snakeFk = makeSnakeCase(a.foreignKey);
4513
4769
  const snakeAssocName = makeSnakeCase(a.name);
4514
- const referencesOpt = a.references === "id" ? "" : `, references: :${a.references}`;
4770
+ const referencesOpt = namesReferences(a.references) ? `, references: :${a.references}` : "";
4515
4771
  return ` has_many(:${snakeAssocName}, ${appName}.${makePascalCase(a.targetModel)}, foreign_key: :${snakeFk}${referencesOpt})`;
4516
4772
  });
4517
4773
  const manyToManyLines = associations.manyToMany.map((a) => {
@@ -4811,45 +5067,172 @@ function ecto(options) {
4811
5067
  return yield* emitMany(files, output);
4812
5068
  });
4813
5069
  }
4814
- // src/utils/naming.ts
4815
- /**
4816
- * A Prisma name as a type name: the underscores join words, each word starts in upper case, and a
4817
- * word in capitals throughout (`PENDING`, `ID`) is lower-cased after its first letter; any other
4818
- * casing is the schema author's and is kept (`sku_code` → `SkuCode`, `userID` → `UserID`,
4819
- * `PENDING_REVIEW` → `PendingReview`).
4820
- *
4821
- * @param name - A Prisma model, field or enum value name.
4822
- * @returns The PascalCase name.
4823
- */
4824
- function pascalCase(name) {
4825
- const text = name.split("_").filter((word) => word !== "").map((word) => {
4826
- const rest = word.slice(1);
4827
- return `${word.charAt(0).toUpperCase()}${word === word.toUpperCase() ? rest.toLowerCase() : rest}`;
4828
- }).join("");
4829
- return /^\p{L}/u.test(text) ? text : `_${text}`;
5070
+ // src/utils/humanizer.ts
5071
+ function irregular(singular, plural) {
5072
+ return {
5073
+ plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
5074
+ singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
5075
+ };
5076
+ }
5077
+ function wholeWordIrregular(singular, plural) {
5078
+ return {
5079
+ plural: [`^${singular}$`, plural],
5080
+ singular: [`^${plural}$`, singular]
5081
+ };
5082
+ }
5083
+ const IRREGULARS = [
5084
+ irregular("person", "people"),
5085
+ irregular("man", "men"),
5086
+ irregular("human", "humans"),
5087
+ irregular("child", "children"),
5088
+ irregular("sex", "sexes"),
5089
+ irregular("glove", "gloves"),
5090
+ irregular("move", "moves"),
5091
+ irregular("goose", "geese"),
5092
+ irregular("wave", "waves"),
5093
+ irregular("foot", "feet"),
5094
+ irregular("tooth", "teeth"),
5095
+ irregular("curriculum", "curricula"),
5096
+ irregular("database", "databases"),
5097
+ irregular("zombie", "zombies"),
5098
+ irregular("personnel", "personnel"),
5099
+ irregular("cache", "caches"),
5100
+ wholeWordIrregular("ex", "exes"),
5101
+ wholeWordIrregular("is", "are"),
5102
+ wholeWordIrregular("that", "those"),
5103
+ wholeWordIrregular("this", "these"),
5104
+ wholeWordIrregular("bus", "buses"),
5105
+ wholeWordIrregular("die", "dice"),
5106
+ wholeWordIrregular("tie", "ties")
5107
+ ];
5108
+ const PLURAL_RULES = [
5109
+ ["$", "s"],
5110
+ ["s$", "s"],
5111
+ ["(ax|test)is$", "$1es"],
5112
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
5113
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
5114
+ ["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
5115
+ ["([dti])um$", "$1a"],
5116
+ ["sis$", "ses"],
5117
+ ["(?:([^f])fe|([lr])f)$", "$1$2ves"],
5118
+ ["(hive)$", "$1s"],
5119
+ ["([^aeiouy]|qu)y$", "$1ies"],
5120
+ ["(x|ch|ss|sh)$", "$1es"],
5121
+ ["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
5122
+ ["(^[m|l])ouse$", "$1ice"],
5123
+ ["^(ox)$", "$1en"],
5124
+ ["(quiz)$", "$1zes"],
5125
+ ["(buz|blit|walt)z$", "$1zes"],
5126
+ ["(hoo|lea|loa|thie)f$", "$1ves"],
5127
+ ["(alumn|alg|larv|vertebr)a$", "$1ae"],
5128
+ ["(criteri|phenomen)on$", "$1a"],
5129
+ ...IRREGULARS.map((rule) => rule.plural)
5130
+ ].map(([pattern, replacement]) => ({
5131
+ pattern: new RegExp(pattern, "iu"),
5132
+ replacement
5133
+ }));
5134
+ const SINGULAR_RULES = [
5135
+ ["s$", ""],
5136
+ ["(n)ews$", "$1ews"],
5137
+ ["([dti])a$", "$1um"],
5138
+ ["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
5139
+ ["([^f])ves$", "$1fe"],
5140
+ ["(hive)s$", "$1"],
5141
+ ["(tive)s$", "$1"],
5142
+ ["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
5143
+ ["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
5144
+ ["(s)eries$", "$1eries"],
5145
+ ["(m)ovies$", "$1ovie"],
5146
+ ["(x|ch|ss|sh)es$", "$1"],
5147
+ ["(^[m|l])ice$", "$1ouse"],
5148
+ ["(?<!^[a-z])(o)es$", "$1"],
5149
+ ["(shoe)s$", "$1"],
5150
+ ["(cris|ax|test)es$", "$1is"],
5151
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
5152
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
5153
+ ["^(ox)en", "$1"],
5154
+ ["(matr|d)ices$", "$1ix"],
5155
+ ["(vert|ind)ices$", "$1ex"],
5156
+ ["(quiz)zes$", "$1"],
5157
+ ["(buz|blit|walt)zes$", "$1z"],
5158
+ ["(alumn|alg|larv|vertebr)ae$", "$1a"],
5159
+ ["(criteri|phenomen)a$", "$1on"],
5160
+ ["([b|r|c]ook|room|smooth)ies$", "$1ie"],
5161
+ ...IRREGULARS.map((rule) => rule.singular)
5162
+ ].map(([pattern, replacement]) => ({
5163
+ pattern: new RegExp(pattern, "iu"),
5164
+ replacement
5165
+ }));
5166
+ const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
5167
+ "staff",
5168
+ "training",
5169
+ "equipment",
5170
+ "information",
5171
+ "corn",
5172
+ "milk",
5173
+ "rice",
5174
+ "money",
5175
+ "species",
5176
+ "series",
5177
+ "fish",
5178
+ "sheep",
5179
+ "deer",
5180
+ "aircraft",
5181
+ "oz",
5182
+ "tsp",
5183
+ "tbsp",
5184
+ "ml",
5185
+ "l",
5186
+ "water",
5187
+ "waters",
5188
+ "semen",
5189
+ "sperm",
5190
+ "bison",
5191
+ "grass",
5192
+ "hair",
5193
+ "mud",
5194
+ "elk",
5195
+ "luggage",
5196
+ "moose",
5197
+ "offspring",
5198
+ "salmon",
5199
+ "shrimp",
5200
+ "someone",
5201
+ "swine",
5202
+ "trout",
5203
+ "tuna",
5204
+ "corps",
5205
+ "scissors",
5206
+ "means",
5207
+ "mail",
5208
+ "metadata"
5209
+ ]);
5210
+ function isUpperCaseLetter(char) {
5211
+ return char !== char.toLowerCase() && char === char.toUpperCase();
5212
+ }
5213
+ function isLowerCaseLetter(char) {
5214
+ return char !== char.toUpperCase() && char === char.toLowerCase();
5215
+ }
5216
+ function applyRules(rules, word) {
5217
+ if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
5218
+ const rule = rules.findLast((candidate) => candidate.pattern.test(word));
5219
+ if (rule === void 0) return null;
5220
+ const result = word.replace(rule.pattern, rule.replacement);
5221
+ const first = result.charAt(0);
5222
+ return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
4830
5223
  }
4831
5224
  /**
4832
- * The first of `candidate`, `candidate1`, `candidate2`, ... that is free — the numbering
4833
- * `dotnet ef dbcontext scaffold` gives names that collide, which the other generators follow too.
5225
+ * Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
5226
+ * is returned as it is.
4834
5227
  *
4835
- * @param candidate - The preferred name.
4836
- * @param isTaken - Whether a name is already in use.
4837
- * @returns A free name.
5228
+ * @param word - The word to pluralize.
5229
+ * @returns The plural form Humanizer 2.14.1 gives.
4838
5230
  */
4839
- function uniqueName(candidate, isTaken) {
4840
- if (!isTaken(candidate)) return candidate;
4841
- for (let index = 1; index <= 1e4; index += 1) if (!isTaken(`${candidate}${index}`)) return `${candidate}${index}`;
4842
- return candidate;
4843
- }
4844
- function allocate(candidates, reserved, fold) {
4845
- const names = /* @__PURE__ */ new Map();
4846
- const taken = new Set(reserved.map(fold));
4847
- for (const { key, candidate } of candidates) {
4848
- const name = uniqueName(candidate, (one) => taken.has(fold(one)));
4849
- names.set(key, name);
4850
- taken.add(fold(name));
4851
- }
4852
- return names;
5231
+ function pluralize(word) {
5232
+ const result = applyRules(PLURAL_RULES, word);
5233
+ const asSingular = applyRules(SINGULAR_RULES, word);
5234
+ const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
5235
+ return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
4853
5236
  }
4854
5237
  function typeRef(fullName) {
4855
5238
  return `T|${fullName}`;
@@ -5131,7 +5514,7 @@ function planNames$1(models, enums, fileClasses, options) {
5131
5514
  ], (name) => name)
5132
5515
  };
5133
5516
  }
5134
- function className(names, model) {
5517
+ function className$1(names, model) {
5135
5518
  return names.classes.get(model.name) ?? model.name;
5136
5519
  }
5137
5520
  function enumName$1(names, name) {
@@ -5144,7 +5527,7 @@ function generatedRef(names, name) {
5144
5527
  return `${names.namespace}.${name}`;
5145
5528
  }
5146
5529
  function modelType(names, model) {
5147
- return typeRef(generatedRef(names, className(names, model)));
5530
+ return typeRef(generatedRef(names, className$1(names, model)));
5148
5531
  }
5149
5532
  function mapping$1(clr, isValueType, facets = [], elementStoreType = null, temporal = null) {
5150
5533
  return {
@@ -5523,7 +5906,7 @@ function enumConverters(plan) {
5523
5906
  * @returns The plan the file writers take.
5524
5907
  */
5525
5908
  function planEfCore(datamodel, options) {
5526
- const indexesOf = (model) => modelIndexes(model, datamodel.indexes ?? []);
5909
+ const indexesOf = (model) => modelIndexes$1(model, datamodel.indexes ?? []).filter((index) => index.fields.every((f) => model.fields.some((field) => field.name === f.name)));
5527
5910
  const schema = {
5528
5911
  provider: options.provider,
5529
5912
  models: datamodel.models,
@@ -5566,7 +5949,7 @@ function memberType(plan, field) {
5566
5949
  if (field.isList || !field.isRequired) return null;
5567
5950
  if (field.kind === "object") {
5568
5951
  const target = plan.models.find((m) => m.name === field.type);
5569
- return target ? generatedRef(plan.names, className(plan.names, target)) : null;
5952
+ return target ? generatedRef(plan.names, className$1(plan.names, target)) : null;
5570
5953
  }
5571
5954
  return /^\0T\|([^\0]+)\0$/u.exec(fieldPlan(plan, field).clr.clr)?.[1] ?? null;
5572
5955
  }
@@ -5590,7 +5973,7 @@ function entityProperty$1(plan, model, field) {
5590
5973
  * @returns The file, as `{ fileName, code }`.
5591
5974
  */
5592
5975
  function entityFile$1(plan, model) {
5593
- const name = className(plan.names, model);
5976
+ const name = className$1(plan.names, model);
5594
5977
  const fields = model.fields.filter((f) => f.kind !== "unsupported");
5595
5978
  const body = [
5596
5979
  `public partial class ${name}`,
@@ -9555,7 +9938,7 @@ function planExposed(datamodel, options) {
9555
9938
  const views = viewNames(blocks);
9556
9939
  const models = datamodel.models.filter((m) => !views.has(m.name));
9557
9940
  const conditions = indexConditions(blocks);
9558
- const indexes = new Map(models.map((m) => [m.name, modelIndexes(m, datamodel.indexes ?? []).map((index) => {
9941
+ const indexes = new Map(models.map((m) => [m.name, modelIndexes$1(m, datamodel.indexes ?? []).map((index) => {
9559
9942
  const condition = conditions.find((c) => c.model === m.name && c.unique === (index.type === "unique") && c.dbName === index.dbName && isSameList(c.fields, fieldNames(index)));
9560
9943
  return condition ? {
9561
9944
  type: index.type,
@@ -11278,7 +11661,7 @@ function dateTimeGoType(field) {
11278
11661
  const element = nativeName === "Date" ? "Date" : nativeName === "Time" || nativeName === "Timetz" ? "TimeOfDay" : "DateTime";
11279
11662
  return field.isList ? `${element}List` : element;
11280
11663
  }
11281
- function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider) {
11664
+ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider, fieldName = goFieldName(field.name)) {
11282
11665
  const columnName = field.dbName ?? field.name;
11283
11666
  const isUuidDefault = isFunctionDefault(field.default) && field.default.name === "uuid";
11284
11667
  const isUlidDefault = isFunctionDefault(field.default) && field.default.name === "ulid";
@@ -11300,8 +11683,7 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, pr
11300
11683
  return provider === "sqlite" ? `'${iso.replace("Z", "+00:00")}'` : `'${iso.slice(0, 10)} ${iso.slice(11, 23)}'`;
11301
11684
  })();
11302
11685
  const defaultVal = dbGeneratedExpr ?? dateTimeDefault ?? ((!isPk || isCompositePk) && !isNowDefault && !field.isUpdatedAt ? enumMappedDefault ?? formatGoDefault(field.default, field.type, field.kind) : null);
11303
- const fieldName = goFieldName(field.name);
11304
- const isDateTime = isDateTimeScalar(field);
11686
+ const isTracked = isDateTimeScalar(field) || ["Int", "BigInt"].includes(field.type);
11305
11687
  return `\`gorm:"${[
11306
11688
  `column:${columnName}`,
11307
11689
  isPk ? "primaryKey" : null,
@@ -11313,8 +11695,8 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, pr
11313
11695
  isDateTimeList(field) ? `type:${nativeType ?? "timestamp(3)"}[]` : includeNativeType ? `type:${nativeType}` : null,
11314
11696
  field.isList && field.kind !== "object" && !isDateTimeList(field) ? "serializer:json" : null,
11315
11697
  defaultVal !== null ? `default:${defaultVal}` : null,
11316
- isDateTime && fieldName === "CreatedAt" ? "autoCreateTime:false" : null,
11317
- isDateTime && fieldName === "UpdatedAt" ? "autoUpdateTime:false" : null,
11698
+ isTracked && fieldName === "CreatedAt" ? "autoCreateTime:false" : null,
11699
+ isTracked && fieldName === "UpdatedAt" ? "autoUpdateTime:false" : null,
11318
11700
  field.isRequired && !isPk ? "not null" : null
11319
11701
  ].filter((p) => p !== null).join(";")}" json:"${columnName}"\``;
11320
11702
  }
@@ -11392,6 +11774,22 @@ function goFieldName(name) {
11392
11774
  const pascal = splitGoWords(name).join("");
11393
11775
  return GENERATED_METHOD_NAMES.has(pascal) ? `${pascal}_` : pascal;
11394
11776
  }
11777
+ /**
11778
+ * The Go name of each field of a model. Two fields can become one name (`createdAt` beside the
11779
+ * `created_at` an OAuth provider returns, both `CreatedAt`): the first declared keeps it and the
11780
+ * other is numbered (`CreatedAt1`), its `column:` tag still naming its own column. Scalars are
11781
+ * named before relations, so a relation never moves a column's field.
11782
+ */
11783
+ function goFieldNames(model) {
11784
+ return allocate([...model.fields.filter((f) => f.kind !== "object"), ...model.fields.filter((f) => f.kind === "object")].map((f) => ({
11785
+ key: f.name,
11786
+ candidate: goFieldName(f.name)
11787
+ })), [], (name) => name);
11788
+ }
11789
+ function goFieldNameIn(models, modelName, fieldName) {
11790
+ const model = models.find((m) => m.name === modelName);
11791
+ return (model ? goFieldNames(model).get(fieldName) : void 0) ?? goFieldName(fieldName);
11792
+ }
11395
11793
  function goModelName(name) {
11396
11794
  return splitGoWords(name).join("");
11397
11795
  }
@@ -11423,9 +11821,9 @@ function createdTimeExpr(field) {
11423
11821
  const at = new Date(field.default);
11424
11822
  return `time.Date(${at.getUTCFullYear()}, ${at.getUTCMonth() + 1}, ${at.getUTCDate()}, ${at.getUTCHours()}, ${at.getUTCMinutes()}, ${at.getUTCSeconds()}, ${at.getUTCMilliseconds() * 1e6}, time.UTC)`;
11425
11823
  }
11426
- function generateBeforeCreateHook(model) {
11824
+ function generateBeforeCreateHook(model, names) {
11427
11825
  const assignments = model.fields.flatMap((field) => {
11428
- const fieldName = goFieldName(field.name);
11826
+ const fieldName = names.get(field.name) ?? goFieldName(field.name);
11429
11827
  const idExpr = field.kind === "scalar" && field.type === "String" && !field.isList ? generatedIdExpr$1(field) : null;
11430
11828
  if (idExpr !== null) return field.isRequired ? [
11431
11829
  `\tif m.${fieldName} == "" {`,
@@ -11461,7 +11859,7 @@ function generateBeforeCreateHook(model) {
11461
11859
  "}"
11462
11860
  ];
11463
11861
  }
11464
- function generateBeforeUpdateHook(model) {
11862
+ function generateBeforeUpdateHook(model, names) {
11465
11863
  const stamped = model.fields.filter((field) => isDateTimeScalar(field) && field.isUpdatedAt);
11466
11864
  if (stamped.length === 0) return [];
11467
11865
  return [
@@ -11469,7 +11867,7 @@ function generateBeforeUpdateHook(model) {
11469
11867
  `func (*${goModelName(model.name)}) BeforeUpdate(tx *gorm.DB) error {`,
11470
11868
  " now := tx.NowFunc().UTC().Truncate(time.Millisecond)",
11471
11869
  ...stamped.flatMap((field) => {
11472
- const fieldName = goFieldName(field.name);
11870
+ const fieldName = names.get(field.name) ?? goFieldName(field.name);
11473
11871
  return [
11474
11872
  `\tif !tx.Statement.Changed("${fieldName}") {`,
11475
11873
  `\t\ttx.Statement.SetColumn("${fieldName}", ${field.isRequired ? "" : "&"}${dateTimeGoType(field)}{Time: now})`,
@@ -11480,8 +11878,7 @@ function generateBeforeUpdateHook(model) {
11480
11878
  "}"
11481
11879
  ];
11482
11880
  }
11483
- function generateStructField(field, isPk, isCompositePk, compositeIndexTags, enums, provider) {
11484
- const fieldName = goFieldName(field.name);
11881
+ function generateStructField(field, fieldName, isPk, isCompositePk, compositeIndexTags, enums, provider) {
11485
11882
  const def = field.default;
11486
11883
  const hasNonZeroDefault = field.kind === "scalar" && !isPk && [
11487
11884
  "Int",
@@ -11495,7 +11892,7 @@ function generateStructField(field, isPk, isCompositePk, compositeIndexTags, enu
11495
11892
  return [
11496
11893
  fieldName,
11497
11894
  isDateTimeList(field) ? dateTimeGoType(field) : field.isList ? `[]${field.kind === "enum" ? "string" : prismaTypeToGoType(field.type, true)}` : isDateTimeScalar(field) ? `${field.isRequired ? "" : "*"}${dateTimeGoType(field)}` : scalarType,
11498
- buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider)
11895
+ buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums, provider, fieldName)
11499
11896
  ];
11500
11897
  }
11501
11898
  function needsReferencesTag(references) {
@@ -11515,16 +11912,18 @@ function constraintTag(onDelete, onUpdate) {
11515
11912
  function buildRelationTag(parts) {
11516
11913
  return `\`gorm:"${parts.join(";")}"\``;
11517
11914
  }
11518
- function generateRelationFields(model, associations) {
11915
+ function generateRelationFields(model, allModels, associations) {
11916
+ const of = (modelName) => (name) => goFieldNameIn(allModels, modelName, name);
11917
+ const own = of(model.name);
11519
11918
  const belongsToLines = associations.belongsTo.map((assoc) => {
11520
- const fieldName = goFieldName(assoc.name);
11521
- const fkFieldName = assoc.foreignKeys.map(goFieldName).join(",");
11522
- const refsFieldName = assoc.referencesList.map(goFieldName).join(",");
11919
+ const fieldName = own(assoc.name);
11920
+ const fkFieldName = assoc.foreignKeys.map(own).join(",");
11921
+ const refsFieldName = assoc.referencesList.map(of(assoc.targetModel)).join(",");
11523
11922
  const isComposite = assoc.foreignKeys.length > 1;
11524
11923
  const isAmbiguous = fieldName !== goModelName(assoc.targetModel) || associations.belongsTo.filter((a) => a.targetModel === assoc.targetModel).length > 1;
11525
11924
  const isGuessed = fkFieldName === `${fieldName}${refsFieldName}`;
11526
11925
  const tagParts = [isAmbiguous || isComposite || !isGuessed ? `foreignKey:${fkFieldName}` : null, isComposite || needsReferencesTag(assoc.references) ? `references:${refsFieldName}` : null].filter((p) => p !== null);
11527
- const targetType = assoc.targetModel === model.name ? `*${goModelName(assoc.targetModel)}` : goModelName(assoc.targetModel);
11926
+ const targetType = `*${goModelName(assoc.targetModel)}`;
11528
11927
  return tagParts.length > 0 ? [
11529
11928
  fieldName,
11530
11929
  targetType,
@@ -11533,35 +11932,35 @@ function generateRelationFields(model, associations) {
11533
11932
  });
11534
11933
  const hasManyLines = associations.hasMany.map((assoc) => {
11535
11934
  const tagParts = [
11536
- `foreignKey:${assoc.foreignKeys.map(goFieldName).join(",")}`,
11537
- ...assoc.foreignKeys.length > 1 || needsReferencesTag(assoc.references) ? [`references:${assoc.referencesList.map(goFieldName).join(",")}`] : [],
11935
+ `foreignKey:${assoc.foreignKeys.map(of(assoc.targetModel)).join(",")}`,
11936
+ ...assoc.foreignKeys.length > 1 || needsReferencesTag(assoc.references) ? [`references:${assoc.referencesList.map(own).join(",")}`] : [],
11538
11937
  ...[constraintTag(assoc.onDelete, assoc.onUpdate)].filter((c) => c !== null)
11539
11938
  ];
11540
11939
  return [
11541
- goFieldName(assoc.name),
11940
+ own(assoc.name),
11542
11941
  `[]${goModelName(assoc.targetModel)}`,
11543
11942
  buildRelationTag(tagParts)
11544
11943
  ];
11545
11944
  });
11546
11945
  const hasOneLines = associations.hasOne.map((assoc) => {
11547
11946
  const tagParts = [
11548
- `foreignKey:${assoc.foreignKeys.map(goFieldName).join(",")}`,
11549
- ...assoc.foreignKeys.length > 1 || needsReferencesTag(assoc.references) ? [`references:${assoc.referencesList.map(goFieldName).join(",")}`] : [],
11947
+ `foreignKey:${assoc.foreignKeys.map(of(assoc.targetModel)).join(",")}`,
11948
+ ...assoc.foreignKeys.length > 1 || needsReferencesTag(assoc.references) ? [`references:${assoc.referencesList.map(own).join(",")}`] : [],
11550
11949
  ...[constraintTag(assoc.onDelete, assoc.onUpdate)].filter((c) => c !== null)
11551
11950
  ];
11552
11951
  return [
11553
- goFieldName(assoc.name),
11952
+ own(assoc.name),
11554
11953
  `*${goModelName(assoc.targetModel)}`,
11555
11954
  buildRelationTag(tagParts)
11556
11955
  ];
11557
11956
  });
11558
11957
  const manyToManyLines = associations.manyToMany.map((assoc) => {
11559
11958
  const joinTable = `_${assoc.relationName}`;
11560
- const [own, related] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
11959
+ const [ownColumn, related] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
11561
11960
  return [
11562
- goFieldName(assoc.name),
11961
+ own(assoc.name),
11563
11962
  `[]${goModelName(assoc.targetModel)}`,
11564
- `\`gorm:"many2many:${joinTable};joinForeignKey:${own};joinReferences:${related}"\``
11963
+ `\`gorm:"many2many:${joinTable};joinForeignKey:${ownColumn};joinReferences:${related}"\``
11565
11964
  ];
11566
11965
  });
11567
11966
  return [
@@ -11604,18 +12003,19 @@ function alignFields(rows) {
11604
12003
  }
11605
12004
  function generateModelStruct(model, allModels, enums, indexes, provider) {
11606
12005
  const idField = model.fields.find((f) => f.isId);
11607
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
12006
+ const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
11608
12007
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
11609
- if (!(idField || isCompositePk)) return null;
11610
12008
  const associations = getAssociations$2(model, allModels);
11611
12009
  const compositeTagMap = collectCompositeIndexTags(model, indexes);
11612
12010
  const tableName = model.dbName ?? model.name;
11613
- const fieldLines = model.fields.filter((f) => f.kind !== "object").map((field) => {
12011
+ const scalarFields = model.fields.filter((f) => f.kind !== "object");
12012
+ const names = goFieldNames(model);
12013
+ const fieldLines = scalarFields.map((field) => {
11614
12014
  const isPk = field.isId || compositePkFieldNames.has(field.name);
11615
12015
  const fieldIndexTags = compositeTagMap.get(field.name) ?? [];
11616
- return generateStructField(field, isPk, isCompositePk, fieldIndexTags, enums, provider);
12016
+ return generateStructField(field, names.get(field.name) ?? goFieldName(field.name), isPk, isCompositePk, fieldIndexTags, enums, provider);
11617
12017
  });
11618
- const relationLines = generateRelationFields(model, associations);
12018
+ const relationLines = generateRelationFields(model, allModels, associations);
11619
12019
  const tableNameMethod = [
11620
12020
  "",
11621
12021
  `func (${goModelName(model.name)}) TableName() string {`,
@@ -11627,8 +12027,8 @@ function generateModelStruct(model, allModels, enums, indexes, provider) {
11627
12027
  ...alignFields([...fieldLines, ...relationLines]),
11628
12028
  "}",
11629
12029
  ...tableNameMethod,
11630
- ...generateBeforeCreateHook(model),
11631
- ...generateBeforeUpdateHook(model)
12030
+ ...generateBeforeCreateHook(model, names),
12031
+ ...generateBeforeUpdateHook(model, names)
11632
12032
  ].join("\n");
11633
12033
  }
11634
12034
  function hasImplicitManyToMany(models) {
@@ -11935,7 +12335,7 @@ function formatImports(groups) {
11935
12335
  // src/generator/gorm.ts
11936
12336
  function generateGormModels(models, enums, indexes, packageName = "model", provider) {
11937
12337
  const idx = indexes ?? [];
11938
- const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider)).filter((body) => body !== null);
12338
+ const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider));
11939
12339
  return [
11940
12340
  `package ${packageName}`,
11941
12341
  ...formatImports(collectImports(models)),
@@ -12833,6 +13233,87 @@ function rustFieldIdent(snake) {
12833
13233
  derivedColumn: snake
12834
13234
  };
12835
13235
  }
13236
+ /**
13237
+ * The module a model, an enum or a join table is written as: its name in snake_case, a raw
13238
+ * identifier where that is a Rust keyword, in a file named without the `r#`.
13239
+ *
13240
+ * @example
13241
+ * ```rust
13242
+ * pub mod r#type; // type.rs
13243
+ * use super::r#type::Type;
13244
+ * ```
13245
+ */
13246
+ function rustModule(name) {
13247
+ const { ident } = rustFieldIdent(makeSnakeCase(name));
13248
+ return {
13249
+ ident,
13250
+ file: `${ident.startsWith("r#") ? ident.slice(2) : ident}.rs`
13251
+ };
13252
+ }
13253
+ /**
13254
+ * The Rust name of each scalar field of a model, the column sea-orm derives from it and the
13255
+ * `Column` variant DeriveEntityModel makes of it. Two fields can become one name in snake_case
13256
+ * (`createdAt` beside the `created_at` an OAuth provider returns): the one already written that
13257
+ * way keeps it, and the other is numbered (`created_at1`, variant `CreatedAt1`), which
13258
+ * `column_name` maps back to its own column.
13259
+ */
13260
+ function seaOrmFieldNames(model) {
13261
+ const candidates = model.fields.filter((f) => f.kind !== "object").map((f) => ({
13262
+ key: f.name,
13263
+ candidate: makeSnakeCase(f.name)
13264
+ }));
13265
+ const names = allocate([...candidates.filter((c) => c.candidate === c.key), ...candidates.filter((c) => c.candidate !== c.key)], [], (name) => name);
13266
+ return new Map(candidates.map(({ key, candidate }) => {
13267
+ const name = names.get(key) ?? candidate;
13268
+ return [key, {
13269
+ ...rustFieldIdent(name),
13270
+ variant: makePascalCase(name)
13271
+ }];
13272
+ }));
13273
+ }
13274
+ function columnVariant(models, modelName, fieldName) {
13275
+ const model = models.find((m) => m.name === modelName);
13276
+ return (model ? seaOrmFieldNames(model).get(fieldName)?.variant : void 0) ?? makePascalCase(fieldName);
13277
+ }
13278
+ /**
13279
+ * A method chain on a relation followed by `suffix`, laid out as rustfmt lays it out: on one
13280
+ * line while it fits in 100 columns and, with more than one call, the chain takes no more than
13281
+ * 60 (`chain_width`); otherwise one call per line under the path. Where the path alone does not
13282
+ * fit, rustfmt leaves the line as it is.
13283
+ *
13284
+ * @example
13285
+ * ```rust
13286
+ * Relation::Author.def()
13287
+ * super::block_version_to_resource::Relation::BlockVersion
13288
+ * .def()
13289
+ * .rev(),
13290
+ * ```
13291
+ */
13292
+ function relationChain(indent, path, calls, suffix) {
13293
+ const line = `${indent}${path}${calls.join("")}${suffix}`;
13294
+ const fits = line.length <= 100 && (calls.length === 1 || `${path}${calls.join("")}`.length <= 60);
13295
+ const broken = [`${indent}${path}`, ...calls.map((call, i) => `${indent} ${call}${i === calls.length - 1 ? suffix : ""}`)];
13296
+ return fits || broken.some((part) => part.length > 100) ? line : broken.join("\n");
13297
+ }
13298
+ /**
13299
+ * The body of `via()`: the relation from the join table back to this model, in `Some`, which
13300
+ * rustfmt opens onto lines of its own when the chain inside is broken.
13301
+ *
13302
+ * @example
13303
+ * ```rust
13304
+ * Some(super::post_to_tag::Relation::Post.def().rev())
13305
+ * Some(
13306
+ * super::block_version_to_resource::Relation::BlockVersion
13307
+ * .def()
13308
+ * .rev(),
13309
+ * )
13310
+ * ```
13311
+ */
13312
+ function viaBody(path) {
13313
+ const line = ` Some(${path}.def().rev())`;
13314
+ const inner = relationChain(" ", path, [".def()", ".rev()"], ",");
13315
+ return inner.includes("\n") ? ` Some(\n${inner}\n )` : line;
13316
+ }
12836
13317
  function resolveSeaOrmColumnType(field) {
12837
13318
  if (!field.nativeType) return null;
12838
13319
  const [nativeName, nativeArgs] = field.nativeType;
@@ -13029,7 +13510,7 @@ function generateEnum(e, serde = {}) {
13029
13510
  "}"
13030
13511
  ].join("\n");
13031
13512
  }
13032
- function generateRelationEnum(_model, associations) {
13513
+ function generateRelationEnum(model, associations, allModels) {
13033
13514
  if (!(associations.belongsTo.length > 0 || associations.hasMany.length > 0 || associations.hasOne.length > 0)) return ["#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]", "pub enum Relation {}"].join("\n");
13034
13515
  const variants = [];
13035
13516
  const targetCount = /* @__PURE__ */ new Map();
@@ -13041,9 +13522,11 @@ function generateRelationEnum(_model, associations) {
13041
13522
  const isAmbiguous = (targetModel) => (targetCount.get(targetModel) ?? 0) > 1;
13042
13523
  for (const assoc of associations.belongsTo) {
13043
13524
  const variantName = makePascalCase(assoc.name);
13044
- const targetModule = makeSnakeCase(assoc.targetModel);
13045
- const fromCol = assoc.foreignKeys.length > 1 ? `(${assoc.foreignKeys.map((c) => `Column::${makePascalCase(c)}`).join(", ")})` : `Column::${makePascalCase(assoc.foreignKey)}`;
13046
- const toCol = assoc.referencesList.length > 1 ? `(${assoc.referencesList.map((c) => `super::${targetModule}::Column::${makePascalCase(c)}`).join(", ")})` : `super::${targetModule}::Column::${makePascalCase(assoc.references)}`;
13525
+ const targetModule = rustModule(assoc.targetModel).ident;
13526
+ const own = (c) => `Column::${columnVariant(allModels, model.name, c)}`;
13527
+ const target = (c) => `super::${targetModule}::Column::${columnVariant(allModels, assoc.targetModel, c)}`;
13528
+ const fromCol = assoc.foreignKeys.length > 1 ? `(${assoc.foreignKeys.map(own).join(", ")})` : own(assoc.foreignKey);
13529
+ const toCol = assoc.referencesList.length > 1 ? `(${assoc.referencesList.map(target).join(", ")})` : target(assoc.references);
13047
13530
  const actions = [assoc.onUpdate ? `on_update = "${assoc.onUpdate}"` : null, assoc.onDelete ? `on_delete = "${assoc.onDelete}"` : null].filter((l) => l !== null);
13048
13531
  const attribute = seaOrmAttribute(" ", [
13049
13532
  `belongs_to = "super::${targetModule}::Entity"`,
@@ -13055,14 +13538,14 @@ function generateRelationEnum(_model, associations) {
13055
13538
  }
13056
13539
  for (const assoc of associations.hasMany) {
13057
13540
  const variantName = makePascalCase(assoc.name);
13058
- const targetModule = makeSnakeCase(assoc.targetModel);
13059
- const attribute = seaOrmAttribute(" ", [`has_many = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${makePascalCase(assoc.references)}"`, `to = "super::${targetModule}::Column::${makePascalCase(assoc.foreignKey)}"`] : []]);
13541
+ const targetModule = rustModule(assoc.targetModel).ident;
13542
+ const attribute = seaOrmAttribute(" ", [`has_many = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${columnVariant(allModels, model.name, assoc.references)}"`, `to = "super::${targetModule}::Column::${columnVariant(allModels, assoc.targetModel, assoc.foreignKey)}"`] : []]);
13060
13543
  variants.push(`${attribute}\n ${variantName},`);
13061
13544
  }
13062
13545
  for (const assoc of associations.hasOne) {
13063
13546
  const variantName = makePascalCase(assoc.name);
13064
- const targetModule = makeSnakeCase(assoc.targetModel);
13065
- const attribute = seaOrmAttribute(" ", [`has_one = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${makePascalCase(assoc.references)}"`, `to = "super::${targetModule}::Column::${makePascalCase(assoc.foreignKey)}"`] : []]);
13547
+ const targetModule = rustModule(assoc.targetModel).ident;
13548
+ const attribute = seaOrmAttribute(" ", [`has_one = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${columnVariant(allModels, model.name, assoc.references)}"`, `to = "super::${targetModule}::Column::${columnVariant(allModels, assoc.targetModel, assoc.foreignKey)}"`] : []]);
13066
13549
  variants.push(`${attribute}\n ${variantName},`);
13067
13550
  }
13068
13551
  return [
@@ -13078,11 +13561,10 @@ function generateRelatedImpls(model, associations) {
13078
13561
  for (const assoc of associations.belongsTo) {
13079
13562
  if (emittedTargets.has(assoc.targetModel)) continue;
13080
13563
  emittedTargets.add(assoc.targetModel);
13081
- const targetModule = makeSnakeCase(assoc.targetModel);
13082
13564
  impls.push([
13083
- relatedImplHeader(targetModule),
13565
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13084
13566
  " fn to() -> RelationDef {",
13085
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13567
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13086
13568
  " }",
13087
13569
  "}"
13088
13570
  ].join("\n"));
@@ -13090,11 +13572,10 @@ function generateRelatedImpls(model, associations) {
13090
13572
  for (const assoc of associations.hasMany) {
13091
13573
  if (emittedTargets.has(assoc.targetModel)) continue;
13092
13574
  emittedTargets.add(assoc.targetModel);
13093
- const targetModule = makeSnakeCase(assoc.targetModel);
13094
13575
  impls.push([
13095
- relatedImplHeader(targetModule),
13576
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13096
13577
  " fn to() -> RelationDef {",
13097
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13578
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13098
13579
  " }",
13099
13580
  "}"
13100
13581
  ].join("\n"));
@@ -13102,18 +13583,17 @@ function generateRelatedImpls(model, associations) {
13102
13583
  for (const assoc of associations.hasOne) {
13103
13584
  if (emittedTargets.has(assoc.targetModel)) continue;
13104
13585
  emittedTargets.add(assoc.targetModel);
13105
- const targetModule = makeSnakeCase(assoc.targetModel);
13106
13586
  impls.push([
13107
- relatedImplHeader(targetModule),
13587
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13108
13588
  " fn to() -> RelationDef {",
13109
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13589
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13110
13590
  " }",
13111
13591
  "}"
13112
13592
  ].join("\n"));
13113
13593
  }
13114
13594
  for (const assoc of associations.manyToMany) {
13115
13595
  if (assoc.targetModel === model.name) {
13116
- const junctionModule = makeSnakeCase(assoc.relationName);
13596
+ const junctionModule = rustModule(assoc.relationName).ident;
13117
13597
  const [own, other] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
13118
13598
  impls.push([
13119
13599
  `pub struct ${makePascalCase(assoc.name)}Link;`,
@@ -13124,8 +13604,8 @@ function generateRelatedImpls(model, associations) {
13124
13604
  "",
13125
13605
  " fn link(&self) -> Vec<RelationDef> {",
13126
13606
  " vec![",
13127
- ` super::${junctionModule}::Relation::${own}.def().rev(),`,
13128
- ` super::${junctionModule}::Relation::${other}.def(),`,
13607
+ relationChain(" ", `super::${junctionModule}::Relation::${own}`, [".def()", ".rev()"], ","),
13608
+ relationChain(" ", `super::${junctionModule}::Relation::${other}`, [".def()"], ","),
13129
13609
  " ]",
13130
13610
  " }",
13131
13611
  "}"
@@ -13134,17 +13614,17 @@ function generateRelatedImpls(model, associations) {
13134
13614
  }
13135
13615
  if (emittedTargets.has(assoc.targetModel)) continue;
13136
13616
  emittedTargets.add(assoc.targetModel);
13137
- const targetModule = makeSnakeCase(assoc.targetModel);
13138
- const junctionModule = makeSnakeCase(assoc.relationName);
13617
+ const targetModule = rustModule(assoc.targetModel).ident;
13618
+ const junctionModule = rustModule(assoc.relationName).ident;
13139
13619
  const junctionRelToTarget = makePascalCase(assoc.targetModel);
13140
13620
  const junctionRelToSelf = makePascalCase(model.name);
13141
13621
  impls.push([
13142
13622
  relatedImplHeader(targetModule),
13143
13623
  " fn to() -> RelationDef {",
13144
- ` super::${junctionModule}::Relation::${junctionRelToTarget}.def()`,
13624
+ relationChain(" ", `super::${junctionModule}::Relation::${junctionRelToTarget}`, [".def()"], ""),
13145
13625
  " }",
13146
13626
  " fn via() -> Option<RelationDef> {",
13147
- ` Some(super::${junctionModule}::Relation::${junctionRelToSelf}.def().rev())`,
13627
+ viaBody(`super::${junctionModule}::Relation::${junctionRelToSelf}`),
13148
13628
  " }",
13149
13629
  "}"
13150
13630
  ].join("\n"));
@@ -13152,21 +13632,21 @@ function generateRelatedImpls(model, associations) {
13152
13632
  return impls;
13153
13633
  }
13154
13634
  function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13155
- const idField = model.fields.find((f) => f.isId);
13156
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
13157
- const isCompositePk = !idField && compositePkFieldNames.size > 0;
13158
- if (!(idField || isCompositePk)) return "";
13635
+ const primaryKey = new Set(primaryKeyFields$1(model));
13636
+ const isCompositePk = primaryKey.size > 1;
13637
+ if (primaryKey.size === 0) return "";
13159
13638
  const tableName = model.dbName ?? model.name;
13160
13639
  const associations = getAssociations$1(model, allModels);
13161
13640
  const enumNames = new Set(enums.map((e) => e.name));
13641
+ const fieldNames = seaOrmFieldNames(model);
13162
13642
  const scalarFields = model.fields.filter((f) => f.kind !== "object");
13163
13643
  const fieldLines = [];
13164
13644
  const stampLines = [];
13165
13645
  let stampsNow = false;
13166
13646
  let stampsOnInsert = false;
13167
13647
  for (const field of scalarFields) {
13168
- const isPk = field.isId || compositePkFieldNames.has(field.name);
13169
- const { ident: fieldName, derivedColumn } = rustFieldIdent(makeSnakeCase(field.name));
13648
+ const isPk = primaryKey.has(field.name);
13649
+ const { ident: fieldName, derivedColumn } = fieldNames.get(field.name) ?? rustFieldIdent(makeSnakeCase(field.name));
13170
13650
  const attrs = buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums);
13171
13651
  const nativeOverride = rustTypeForNative(field, provider);
13172
13652
  const elemType = enumNames.has(field.type) ? field.type : nativeOverride ?? prismaTypeToRustType(field.type, true);
@@ -13189,9 +13669,12 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13189
13669
  const assignment = ` self.${fieldName} = Set(${field.isRequired ? value : `Some(${value})`});`;
13190
13670
  stampLines.push(...condition, assignment.length <= 100 || ` self.${fieldName} =`.length > 99 ? assignment : ` self.${fieldName} =\n ${assignment.trimStart().slice(`self.${fieldName} = `.length)}`, " }");
13191
13671
  }
13192
- const relationEnum = generateRelationEnum(model, associations);
13672
+ const relationEnum = generateRelationEnum(model, associations, allModels);
13193
13673
  const relatedImpls = generateRelatedImpls(model, associations);
13194
- const superImports = [...new Set(scalarFields.flatMap((f) => enumNames.has(f.type) ? [f.type] : f.type === "DateTime" && provider === "sqlite" ? ["PrismaDateTime"] : []))].map((name) => `use super::${makeSnakeCase(name)}::${name};`).toSorted();
13674
+ const superImports = [...new Set(scalarFields.flatMap((f) => enumNames.has(f.type) ? [f.type] : f.type === "DateTime" && provider === "sqlite" ? ["PrismaDateTime"] : []))].map((name) => ({
13675
+ module: rustModule(name).ident,
13676
+ name
13677
+ })).toSorted((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0).map(({ module, name }) => `use super::${module}::${name};`);
13195
13678
  const generatedIdFields = scalarFields.filter((f) => f.type === "String" && !f.isList && generatedIdExpr(f) !== null);
13196
13679
  const useLines = [
13197
13680
  ...superImports,
@@ -13204,7 +13687,7 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13204
13687
  " fn new() -> Self {",
13205
13688
  " Self {",
13206
13689
  ...generatedIdFields.map((field) => {
13207
- const { ident } = rustFieldIdent(makeSnakeCase(field.name));
13690
+ const { ident } = fieldNames.get(field.name) ?? rustFieldIdent(makeSnakeCase(field.name));
13208
13691
  const generate = generatedIdExpr(field) ?? "";
13209
13692
  const value = field.isRequired ? generate : `Some(${generate})`;
13210
13693
  const n = ident.length;
@@ -13265,8 +13748,8 @@ function pkRustType(modelName, models) {
13265
13748
  function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde = {}) {
13266
13749
  const [sortedLeft, sortedRight] = leftModel < rightModel ? [leftModel, rightModel] : [rightModel, leftModel];
13267
13750
  const tableName = `_${relationName}`;
13268
- const leftModule = makeSnakeCase(sortedLeft);
13269
- const rightModule = makeSnakeCase(sortedRight);
13751
+ const leftModule = rustModule(sortedLeft).ident;
13752
+ const rightModule = rustModule(sortedRight).ident;
13270
13753
  const isSelf = sortedLeft === sortedRight;
13271
13754
  const leftFk = isSelf ? "a" : `${makeSnakeCase(sortedLeft)}_id`;
13272
13755
  const rightFk = isSelf ? "b" : `${makeSnakeCase(sortedRight)}_id`;
@@ -13399,7 +13882,10 @@ function generateModRs(moduleNames) {
13399
13882
  return `${moduleNames.map((m) => `pub mod ${m};`).join("\n")}\n`;
13400
13883
  }
13401
13884
  function generatePreludeRs(models) {
13402
- return `${models.map((m) => `pub use super::${makeSnakeCase(m.name)}::Entity as ${m.name};`).toSorted().join("\n")}\n`;
13885
+ return `${models.map((m) => ({
13886
+ module: rustModule(m.name).ident,
13887
+ name: m.name
13888
+ })).toSorted((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0).map(({ module, name }) => name === "Entity" ? `pub use super::${module}::Entity;` : `pub use super::${module}::Entity as ${name};`).join("\n")}\n`;
13403
13889
  }
13404
13890
  function collectM2MPairs(models) {
13405
13891
  const pairs = models.flatMap((model) => getAssociations$1(model, models).manyToMany.map((assoc) => {
@@ -13422,8 +13908,8 @@ function collectM2MPairs(models) {
13422
13908
  function seaOrmFiles(models, enums, serde = {}, provider) {
13423
13909
  const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
13424
13910
  const enumFiles = enums.map((e) => ({
13425
- fileName: `${makeSnakeCase(e.name)}.rs`,
13426
- moduleName: makeSnakeCase(e.name),
13911
+ fileName: rustModule(e.name).file,
13912
+ moduleName: rustModule(e.name).ident,
13427
13913
  code: [
13428
13914
  ...useLines,
13429
13915
  "",
@@ -13431,23 +13917,26 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
13431
13917
  ""
13432
13918
  ].join("\n")
13433
13919
  }));
13434
- const entityFiles = models.map((model) => ({
13435
- fileName: `${makeSnakeCase(model.name)}.rs`,
13436
- moduleName: makeSnakeCase(model.name),
13920
+ const entities = models.map((model) => ({
13921
+ model,
13922
+ fileName: rustModule(model.name).file,
13923
+ moduleName: rustModule(model.name).ident,
13437
13924
  code: generateEntityFile(model, models, enums, serde, provider)
13438
13925
  })).filter((entry) => entry.code.trim().length > 0);
13439
- const m2mFiles = collectM2MPairs(models).map((pair) => {
13440
- const moduleName = makeSnakeCase(pair.relationName);
13441
- return {
13442
- fileName: `${moduleName}.rs`,
13443
- moduleName,
13444
- code: generateM2MEntity(pair.left, pair.right, pair.relationName, models, serde)
13445
- };
13446
- });
13926
+ const entityFiles = entities.map(({ fileName, moduleName, code }) => ({
13927
+ fileName,
13928
+ moduleName,
13929
+ code
13930
+ }));
13931
+ const m2mFiles = collectM2MPairs(models).map((pair) => ({
13932
+ fileName: rustModule(pair.relationName).file,
13933
+ moduleName: rustModule(pair.relationName).ident,
13934
+ code: generateM2MEntity(pair.left, pair.right, pair.relationName, models, serde)
13935
+ }));
13447
13936
  const preludeEntry = {
13448
13937
  fileName: "prelude.rs",
13449
13938
  moduleName: "prelude",
13450
- code: generatePreludeRs(models)
13939
+ code: generatePreludeRs(entities.map(({ model }) => model))
13451
13940
  };
13452
13941
  const prismaDateTimeFiles = provider === "sqlite" && models.some((m) => m.fields.some((f) => f.type === "DateTime")) ? [{
13453
13942
  fileName: "prisma_date_time.rs",
@@ -13463,7 +13952,10 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
13463
13952
  ];
13464
13953
  const modEntry = {
13465
13954
  fileName: "mod.rs",
13466
- code: generateModRs(allEntries.map((e) => e.moduleName).toSorted())
13955
+ code: generateModRs(allEntries.map((e) => e.moduleName).toSorted((a, b) => {
13956
+ const [x, y] = [a.replace(/^r#/u, ""), b.replace(/^r#/u, "")];
13957
+ return x < y ? -1 : x > y ? 1 : 0;
13958
+ }))
13467
13959
  };
13468
13960
  return [...allEntries.map(({ fileName, code }) => ({
13469
13961
  fileName,
@@ -13576,8 +14068,87 @@ const DECLARATIVE_RESERVED = /* @__PURE__ */ new Set([
13576
14068
  "metadata",
13577
14069
  "registry"
13578
14070
  ]);
14071
+ const MODULE_NAMES = /* @__PURE__ */ new Set([
14072
+ "bool",
14073
+ "bytes",
14074
+ "compiles",
14075
+ "date",
14076
+ "datetime",
14077
+ "dict",
14078
+ "float",
14079
+ "func",
14080
+ "int",
14081
+ "list",
14082
+ "mapped_column",
14083
+ "relationship",
14084
+ "str",
14085
+ "text",
14086
+ "time_type",
14087
+ "timezone",
14088
+ "utc_now",
14089
+ "uuid6",
14090
+ "uuid_mod"
14091
+ ]);
14092
+ const MODULE_CLASSES = /* @__PURE__ */ new Set([
14093
+ "Any",
14094
+ "Base",
14095
+ "BigInteger",
14096
+ "BindParameter",
14097
+ "Boolean",
14098
+ "Column",
14099
+ "ColumnElement",
14100
+ "Date",
14101
+ "DateTime",
14102
+ "DecimalType",
14103
+ "DeclarativeBase",
14104
+ "Dialect",
14105
+ "Double",
14106
+ "Enum",
14107
+ "Float",
14108
+ "ForeignKey",
14109
+ "ForeignKeyConstraint",
14110
+ "Index",
14111
+ "Integer",
14112
+ "Jsonb",
14113
+ "LargeBinary",
14114
+ "Mapped",
14115
+ "MetaData",
14116
+ "Numeric",
14117
+ "Optional",
14118
+ "PrimaryKeyConstraint",
14119
+ "SmallInteger",
14120
+ "String",
14121
+ "Table",
14122
+ "Text",
14123
+ "Time",
14124
+ "TypeDecorator",
14125
+ "UtcDateTime",
14126
+ "UtcDateTimeTz",
14127
+ "UtcTimestamp",
14128
+ "Uuid",
14129
+ "Xml"
14130
+ ]);
13579
14131
  function pythonAttrName(columnName) {
13580
- return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) ? `${columnName}_` : columnName;
14132
+ return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) || MODULE_NAMES.has(columnName) ? `${columnName}_` : columnName;
14133
+ }
14134
+ /**
14135
+ * The attribute a field of `model` is mapped to: its name in snake_case, made safe by
14136
+ * `pythonAttrName`. Where two fields come to one name (`createdAt` and `created_at`), the one
14137
+ * already written in snake_case keeps it and the other is numbered, its column named apart.
14138
+ */
14139
+ function attributeName(model, fieldName) {
14140
+ const candidates = (model?.fields ?? []).map((f) => ({
14141
+ key: f.name,
14142
+ candidate: pythonAttrName(makeSnakeCase(f.name))
14143
+ }));
14144
+ return allocate([...candidates.filter((c) => c.candidate === c.key), ...candidates.filter((c) => c.candidate !== c.key)], [], (name) => name).get(fieldName) ?? pythonAttrName(makeSnakeCase(fieldName));
14145
+ }
14146
+ function className(modelName) {
14147
+ const name = makePascalCase(modelName);
14148
+ return MODULE_CLASSES.has(name) ? `${name}_` : name;
14149
+ }
14150
+ function modelIndexes(model, indexes) {
14151
+ return indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext") && idx.fields.every((f) => model.fields.some((mf) => mf.name === f.name)));
13581
14152
  }
13582
14153
  function plainType(type, provider) {
13583
14154
  switch (type) {
@@ -13749,19 +14320,24 @@ function getAssociations(model, allModels) {
13749
14320
  continue;
13750
14321
  }
13751
14322
  const fkField = end.inverse;
13752
- const foreignKey = fkField.relationFromFields?.[0] ?? "";
14323
+ const foreignKeys = fkField.relationFromFields ?? [];
14324
+ const foreignKey = foreignKeys[0] ?? "";
13753
14325
  const { onDelete } = referentialActions(fkField);
13754
14326
  if (end.kind === "hasMany") hasMany.push({
13755
14327
  name: field.name,
13756
14328
  targetModel: field.type,
14329
+ inverse: fkField,
13757
14330
  foreignKey,
14331
+ foreignKeys,
13758
14332
  isList: true,
13759
14333
  onDelete
13760
14334
  });
13761
14335
  else hasOne.push({
13762
14336
  name: field.name,
13763
14337
  targetModel: field.type,
14338
+ inverse: fkField,
13764
14339
  foreignKey,
14340
+ foreignKeys,
13765
14341
  isList: false,
13766
14342
  optional: !field.isRequired,
13767
14343
  onDelete
@@ -13925,11 +14501,10 @@ function usesUtcDateTime(models) {
13925
14501
  "DateTime"
13926
14502
  ].includes(f.nativeType?.[0] ?? "")));
13927
14503
  }
13928
- function needsForeignKeysParam(targetModel, assocs) {
13929
- return assocs.filter((a) => a.targetModel === targetModel).length > 1;
13930
- }
13931
- function foreignKeyEnds(model) {
13932
- return model.fields.filter((f) => f.kind === "object" && (f.relationFromFields ?? []).length > 0).map((f) => ({ targetModel: f.type }));
14504
+ function needsForeignKeysParam(modelName, targetModelName, allModels) {
14505
+ const keysTo = (from, to) => (allModels.find((m) => m.name === from)?.fields ?? []).filter((f) => f.kind === "object" && f.type === to && (f.relationFromFields ?? []).length > 0).length;
14506
+ const back = modelName === targetModelName ? 0 : keysTo(targetModelName, modelName);
14507
+ return keysTo(modelName, targetModelName) + back > 1;
13933
14508
  }
13934
14509
  function findBackPopulates(targetModelName, sourceModelName, foreignKey, allModels, sourceFieldName) {
13935
14510
  const targetModel = allModels.find((m) => m.name === targetModelName);
@@ -13944,15 +14519,37 @@ function findBackPopulates(targetModelName, sourceModelName, foreignKey, allMode
13944
14519
  if (f.relationFromFields?.includes(foreignKey)) return true;
13945
14520
  return sourceModel ? sourceModel.fields.some((sf) => sf.relationName === f.relationName && sf.relationFromFields?.includes(foreignKey)) : false;
13946
14521
  });
13947
- return pythonAttrName(makeSnakeCase(backField ? backField.name : sourceModelName));
14522
+ return backField ? attributeName(targetModel, backField.name) : pythonAttrName(makeSnakeCase(sourceModelName));
13948
14523
  }
13949
14524
  function findM2MBackPopulates(targetModelName, sourceModelName, sourceFieldName, relationName, allModels) {
13950
- const backField = allModels.find((m) => m.name === targetModelName)?.fields.find((f) => f.kind === "object" && f.type === sourceModelName && f.relationName === relationName && !(targetModelName === sourceModelName && f.name === sourceFieldName));
13951
- return pythonAttrName(makeSnakeCase(backField ? backField.name : sourceModelName));
14525
+ const targetModel = allModels.find((m) => m.name === targetModelName);
14526
+ const backField = targetModel?.fields.find((f) => f.kind === "object" && f.type === sourceModelName && f.relationName === relationName && !(targetModelName === sourceModelName && f.name === sourceFieldName));
14527
+ return backField ? attributeName(targetModel, backField.name) : pythonAttrName(makeSnakeCase(sourceModelName));
13952
14528
  }
13953
- function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, tableName) {
14529
+ /**
14530
+ * The `overlaps=` of a relationship that writes the foreign key `relation` holds (the many-to-one
14531
+ * itself or the collection on the other side): every other relationship that writes one of the
14532
+ * same columns. A composite key that shares a column with another relation
14533
+ * (`[projectId, environment]` beside `projectId`) has two relationships copying the column, which
14534
+ * SQLAlchemy warns of unless each names the others. The pair of a back_populates is left out, as
14535
+ * SQLAlchemy leaves it.
14536
+ *
14537
+ * @example
14538
+ * ```python
14539
+ * environment_ref: Mapped[Optional["ProjectEnvironment"]] = relationship(overlaps="database_configs,project", back_populates="database_configs")
14540
+ * ```
14541
+ */
14542
+ function overlapsClause(holdingModelName, relation, allModels) {
14543
+ const holding = allModels.find((m) => m.name === holdingModelName);
14544
+ const keys = relation.relationFromFields ?? [];
14545
+ const names = (holding?.fields ?? []).flatMap((f) => f.kind === "object" && f.name !== relation.name && (f.relationFromFields ?? []).some((key) => keys.includes(key)) ? [attributeName(holding, f.name), findBackPopulates(f.type, holdingModelName, f.relationFromFields?.[0] ?? "", allModels, f.name)] : []);
14546
+ const sorted = [...new Set(names)].toSorted();
14547
+ return sorted.length > 0 ? `overlaps="${sorted.join(",")}", ` : "";
14548
+ }
14549
+ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, model, isMapperKey) {
14550
+ const tableName = model.dbName ?? model.name;
13954
14551
  const columnName = field.dbName ?? field.name;
13955
- const attrName = pythonAttrName(makeSnakeCase(field.name));
14552
+ const attrName = attributeName(model, field.name);
13956
14553
  const elemPythonType = field.kind === "enum" ? "str" : pythonTypeForNative(field);
13957
14554
  const pythonType = field.isList ? `list[${elemPythonType}]` : elemPythonType;
13958
14555
  const typeHint = field.isList || field.isRequired ? pythonType : `Optional[${pythonType}]`;
@@ -14007,12 +14604,12 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, pro
14007
14604
  if (!hasNowDefault) colArgs.push(`default=${utcNow}`);
14008
14605
  colArgs.push(`onupdate=${utcNow}`);
14009
14606
  }
14010
- if (colArgs.length === 0) return ` ${attrName}: Mapped[${typeHint}]`;
14607
+ if (colArgs.length === 0 && !isMapperKey) return ` ${attrName}: Mapped[${typeHint}]`;
14011
14608
  return ` ${attrName}: Mapped[${typeHint}] = mapped_column(${colArgs.join(", ")})`;
14012
14609
  }
14013
14610
  function generateTableArgs(model, allModels, indexes, provider) {
14014
14611
  const tableName = model.dbName ?? model.name;
14015
- const indexConstraints = indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
14612
+ const indexConstraints = modelIndexes(model, indexes).map((idx) => {
14016
14613
  const columns = idx.fields.map((f) => fieldColumn(model, f.name));
14017
14614
  const unique = idx.type === "unique";
14018
14615
  const name = idx.dbName ?? constraintName(tableName, columns, unique ? "key" : "idx", provider);
@@ -14053,63 +14650,74 @@ function deleteClause(onDelete) {
14053
14650
  }
14054
14651
  function generateBelongsToRelationships(associations, model, allModels) {
14055
14652
  return associations.belongsTo.map((assoc) => {
14056
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14057
- const snakeFk = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14653
+ const snakeName = attributeName(model, assoc.name);
14058
14654
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14059
- const fkClause = needsForeignKeysParam(assoc.targetModel, associations.belongsTo) ? `foreign_keys=[${snakeFk}], ` : "";
14060
- const pkField = model.fields.find((f) => f.isId);
14061
- const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${pythonAttrName(makeSnakeCase(pkField.name))}], ` : "";
14062
- return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
14655
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=[${assoc.foreignKeys.map((fk) => attributeName(model, fk)).join(", ")}], ` : "";
14656
+ const identity = primaryKeyFields$1(model);
14657
+ const remoteClause = assoc.targetModel === model.name && identity.length > 0 ? `remote_side=[${identity.map((name) => attributeName(model, name)).join(", ")}], ` : "";
14658
+ const target = className(assoc.targetModel);
14659
+ const mappedType = assoc.optional ? `Optional["${target}"]` : `"${target}"`;
14660
+ const relation = model.fields.find((f) => f.name === assoc.name);
14661
+ return ` ${snakeName}: Mapped[${mappedType}] = relationship(${remoteClause}${fkClause}${relation ? overlapsClause(model.name, relation, allModels) : ""}back_populates="${backPop}")`;
14063
14662
  });
14064
14663
  }
14664
+ function inverseForeignKeys(targetModelName, foreignKeys, allModels) {
14665
+ const targetModel = allModels.find((m) => m.name === targetModelName);
14666
+ const columns = foreignKeys.map((fk) => `${className(targetModelName)}.${attributeName(targetModel, fk)}`);
14667
+ return columns.length === 1 ? `"${columns.join("")}"` : `"[${columns.join(", ")}]"`;
14668
+ }
14065
14669
  function generateHasManyRelationships(associations, model, allModels) {
14066
14670
  return associations.hasMany.map((assoc) => {
14067
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14671
+ const snakeName = attributeName(model, assoc.name);
14068
14672
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14069
- const targetModel = allModels.find((m) => m.name === assoc.targetModel);
14070
- const needsFkParam = targetModel ? needsForeignKeysParam(model.name, foreignKeyEnds(targetModel)) : false;
14071
- const targetFkSnake = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14072
- const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
14073
- return ` ${snakeName}: Mapped[list["${makePascalCase(assoc.targetModel)}"]] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14673
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=${inverseForeignKeys(assoc.targetModel, assoc.foreignKeys, allModels)}, ` : "";
14674
+ const overlaps = overlapsClause(assoc.targetModel, assoc.inverse, allModels);
14675
+ return ` ${snakeName}: Mapped[list["${className(assoc.targetModel)}"]] = relationship(${fkClause}${deleteClause(assoc.onDelete)}${overlaps}back_populates="${backPop}")`;
14074
14676
  });
14075
14677
  }
14076
14678
  function generateHasOneRelationships(associations, model, allModels) {
14077
14679
  return associations.hasOne.map((assoc) => {
14078
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14680
+ const snakeName = attributeName(model, assoc.name);
14079
14681
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14080
- const targetModel = allModels.find((m) => m.name === assoc.targetModel);
14081
- const needsFkParam = targetModel ? needsForeignKeysParam(model.name, foreignKeyEnds(targetModel)) : false;
14082
- const targetFkSnake = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14083
- const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
14084
- return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14682
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=${inverseForeignKeys(assoc.targetModel, assoc.foreignKeys, allModels)}, ` : "";
14683
+ const target = className(assoc.targetModel);
14684
+ const mappedType = assoc.optional ? `Optional["${target}"]` : `"${target}"`;
14685
+ const overlaps = overlapsClause(assoc.targetModel, assoc.inverse, allModels);
14686
+ return ` ${snakeName}: Mapped[${mappedType}] = relationship(${fkClause}${deleteClause(assoc.onDelete)}${overlaps}back_populates="${backPop}")`;
14085
14687
  });
14086
14688
  }
14087
14689
  function generateManyToManyRelationships(associations, model, allModels, m2mTables) {
14088
14690
  return associations.manyToMany.map((assoc) => {
14089
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14691
+ const snakeName = attributeName(model, assoc.name);
14090
14692
  const backPop = findM2MBackPopulates(assoc.targetModel, model.name, assoc.name, assoc.relationName, allModels);
14091
14693
  const secondaryVar = m2mTables.find((t) => t.relationName === assoc.relationName)?.varName ?? makeSnakeCase(assoc.relationName);
14092
14694
  const pkField = model.fields.find((f) => f.isId);
14093
14695
  const other = model.fields.find((f) => f.kind === "object" && f.relationName === assoc.relationName && f.name !== assoc.name);
14094
14696
  const [own, far] = other && other.name < assoc.name ? ["B", "A"] : ["A", "B"];
14095
- const pk = `${makePascalCase(model.name)}.${pythonAttrName(makeSnakeCase(pkField?.name ?? "id"))}`;
14697
+ const pk = `${className(model.name)}.${attributeName(model, pkField?.name ?? "id")}`;
14096
14698
  const joinClause = assoc.targetModel === model.name && other ? `primaryjoin=lambda: ${pk} == ${secondaryVar}.c.${own}, secondaryjoin=lambda: ${pk} == ${secondaryVar}.c.${far}, ` : "";
14097
- return ` ${snakeName}: Mapped[list["${makePascalCase(assoc.targetModel)}"]] = relationship(secondary=${secondaryVar}, ${joinClause}back_populates="${backPop}")`;
14699
+ return ` ${snakeName}: Mapped[list["${className(assoc.targetModel)}"]] = relationship(secondary=${secondaryVar}, ${joinClause}back_populates="${backPop}")`;
14098
14700
  });
14099
14701
  }
14100
14702
  function generateModelBody(model, allModels, enums, indexes, m2mTables, provider) {
14101
14703
  const idField = model.fields.find((f) => f.isId);
14102
14704
  const compositePkFieldNames = new Set(model.primaryKey?.fields);
14103
- const isCompositePk = !idField && compositePkFieldNames.size > 0;
14104
- if (!(idField || isCompositePk)) return null;
14705
+ const identity = primaryKeyFields$1(model);
14706
+ if (identity.length === 0) return null;
14105
14707
  const associations = getAssociations(model, allModels);
14106
14708
  const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
14107
14709
  const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
14108
14710
  const tableName = model.dbName ?? model.name;
14109
- const columnLines = model.fields.filter((f) => f.kind !== "object").map((field) => {
14110
- return generateColumn(field, field.isId || compositePkFieldNames.has(field.name), belongsToFkFields.has(field.name), associations, allModels, enumMap, provider, tableName);
14711
+ const scalarFields = model.fields.filter((f) => f.kind !== "object");
14712
+ const isKeyless = !idField && !model.primaryKey;
14713
+ const columnLines = scalarFields.map((field) => {
14714
+ const isPk = field.isId || compositePkFieldNames.has(field.name);
14715
+ const isFk = belongsToFkFields.has(field.name);
14716
+ const isMapperKey = isKeyless && identity.includes(field.name);
14717
+ return generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, model, isMapperKey);
14111
14718
  });
14112
14719
  const tableArgsLines = generateTableArgs(model, allModels, indexes, provider);
14720
+ const mapperArgsLines = isKeyless ? ["", ` __mapper_args__ = {"primary_key": [${identity.map((name) => attributeName(model, name)).join(", ")}]}`] : [];
14113
14721
  const relationLines = [
14114
14722
  ...generateBelongsToRelationships(associations, model, allModels),
14115
14723
  ...generateHasManyRelationships(associations, model, allModels),
@@ -14118,11 +14726,12 @@ function generateModelBody(model, allModels, enums, indexes, m2mTables, provider
14118
14726
  ];
14119
14727
  const hasRelations = relationLines.length > 0;
14120
14728
  return [
14121
- `class ${makePascalCase(model.name)}(Base):`,
14729
+ `class ${className(model.name)}(Base):`,
14122
14730
  ` __tablename__ = "${tableName}"`,
14123
14731
  "",
14124
14732
  ...columnLines,
14125
14733
  ...tableArgsLines,
14734
+ ...mapperArgsLines,
14126
14735
  ...hasRelations ? [""] : [],
14127
14736
  ...relationLines
14128
14737
  ].join("\n");
@@ -14169,7 +14778,7 @@ function collectGlobalImports(models, _enums, indexes, m2mTables, provider) {
14169
14778
  }
14170
14779
  if (getAssociations(model, models).belongsTo.length > 0) saImports.add("ForeignKey");
14171
14780
  if (model.fields.some((f) => f.kind === "object" && (f.relationFromFields?.length ?? 0) > 1)) saImports.add("ForeignKeyConstraint");
14172
- if (indexes.some((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext"))) saImports.add("Index");
14781
+ if (modelIndexes(model, indexes).length > 0) saImports.add("Index");
14173
14782
  }
14174
14783
  if (m2mTables.length > 0) {
14175
14784
  saImports.add("Column");