hekireki 0.40.0 → 0.42.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 (86) 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 +6 -7
  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-CVNnCHYf.js → bin-CW-vHdsl.js} +931 -386
  26. package/dist/{discover-BJMo8i2-.js → discover-Dyzb_7x-.js} +1 -1
  27. package/dist/{emit-C4CeSye3.js → emit-CbBm_I0C.js} +1 -1
  28. package/dist/{migrate-BhCE-YSd.js → migrate-B-EMC7CC.js} +3 -3
  29. package/dist/{plan-D9axVHFD.js → plan-DVBOCKsd.js} +4 -4
  30. package/dist/{prisma-model-DFq7AQgV.js → prisma-model-D98BBcmY.js} +12 -1
  31. package/dist/{run-Be-2eG1y.js → run-BKHmqvBJ.js} +5 -5
  32. package/dist/{schema-CfxnFLAw.js → schema-BRtObhQG.js} +1 -1
  33. package/dist/{sql-FGRCF9o4.js → sql-BYvD2bjK.js} +2 -2
  34. package/dist/{start-9gS-ABI-.js → start-KD0RjI3H.js} +324 -820
  35. package/dist/studio/assets/{chip-5pFaNmwL.js → chip-Yqg0IG0j.js} +1 -1
  36. package/dist/studio/assets/client-C-v3Paav.js +2 -0
  37. package/dist/studio/assets/{code-block-B1wLRka8.js → code-block-CPMTXPBi.js} +1 -1
  38. package/dist/studio/assets/confirm-dialog-CKCkchiq.js +1 -0
  39. package/dist/studio/assets/{copy-DvJVuM56.js → copy-BwEVZZV_.js} +1 -1
  40. package/dist/studio/assets/{copy-button-D4zjbBc-.js → copy-button-jDpd_nhT.js} +1 -1
  41. package/dist/studio/assets/{dist-DEp-MbCs.js → dist-gV8lABSq.js} +1 -1
  42. package/dist/studio/assets/{docs-Cg9xqNoX.js → docs-CXORFY0Y.js} +1 -1
  43. package/dist/studio/assets/{enums._name-BhNYpcT7.js → enums._name-BUBU_WMt.js} +1 -1
  44. package/dist/studio/assets/field-icon-C1wSRFKO.js +55 -0
  45. package/dist/studio/assets/{hooks-vFvEnsyJ.js → hooks-DXskM7gG.js} +2 -2
  46. package/dist/studio/assets/index-Dn9oYAy5.css +2 -0
  47. package/dist/studio/assets/index-DzCcMC-d.js +15 -0
  48. package/dist/studio/assets/labels-B5gZ2suK.js +2 -0
  49. package/dist/studio/assets/{lazyRouteComponent-TkAX4iEA.js → lazyRouteComponent-8L8QSEt_.js} +1 -1
  50. package/dist/studio/assets/lu-CuC8O-Qz.js +7 -0
  51. package/dist/studio/assets/marked-text-B27DfhKS.js +3 -0
  52. package/dist/studio/assets/models._name-CQFgPD0T.js +1 -0
  53. package/dist/studio/assets/{monaco-BoT_UVCW.js → monaco-CMwienx7.js} +1 -1
  54. package/dist/studio/assets/{monaco-DFkSQFp9.js → monaco-DRYJTcJl.js} +1 -1
  55. package/dist/studio/assets/{not-found-CTsERB3d.js → not-found-69Bz9b3p.js} +1 -1
  56. package/dist/studio/assets/{prisma-DZMNzXN7.js → prisma-1nDx08Wb.js} +1 -1
  57. package/dist/studio/assets/result-table-0P18Nywh.js +1 -0
  58. package/dist/studio/assets/routes-Bl7HRpBJ.js +1 -0
  59. package/dist/studio/assets/{schema-gate-CXYSsT5T.js → schema-gate-BmKFmHnL.js} +1 -1
  60. package/dist/studio/assets/schema-view-BEdx0cC2.js +9 -0
  61. package/dist/studio/assets/sql-GBZZtEKI.js +6 -0
  62. package/dist/studio/assets/table-UZ-Yt-OH.js +1 -0
  63. package/dist/studio/assets/tabs-BpZ0hh1V.js +1 -0
  64. package/dist/studio/assets/useFormValidation-CC75L7h9.js +1 -0
  65. package/dist/studio/assets/{useMatch-wXiBv0wx.js → useMatch-BF6XlF2m.js} +1 -1
  66. package/dist/studio/assets/useMultipleSelectionState-zIKA_ZNd.js +1 -0
  67. package/dist/studio/index.html +10 -11
  68. package/package.json +16 -16
  69. package/dist/studio/assets/client-Cn44j_II.js +0 -2
  70. package/dist/studio/assets/confirm-dialog-C84-yLfM.js +0 -1
  71. package/dist/studio/assets/field-icon-j33Axyq4.js +0 -55
  72. package/dist/studio/assets/index-6aoNJjln.css +0 -2
  73. package/dist/studio/assets/index-Cjy--gYX.js +0 -11
  74. package/dist/studio/assets/labels-Db1CHOpt.js +0 -2
  75. package/dist/studio/assets/lu-CUfSReIi.js +0 -7
  76. package/dist/studio/assets/marked-text-BNzjDVlk.js +0 -3
  77. package/dist/studio/assets/models._name-BgiyfSuj.js +0 -1
  78. package/dist/studio/assets/result-table-zFoiQlAu.js +0 -1
  79. package/dist/studio/assets/routes-Dpy0uL8H.js +0 -1
  80. package/dist/studio/assets/schema-view-wADoyIFc.js +0 -9
  81. package/dist/studio/assets/search-field-Dshrbbug.js +0 -5
  82. package/dist/studio/assets/sql-0uoTjX3O.js +0 -6
  83. package/dist/studio/assets/table-5cZklaSq.js +0 -1
  84. package/dist/studio/assets/tabs-B7UQa0vf.js +0 -1
  85. package/dist/studio/assets/useFormValidation-D0dsTzOi.js +0 -1
  86. package/dist/studio/assets/useMultipleSelectionState-CyThblbT.js +0 -1
@@ -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();
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;
177
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}`;
@@ -2726,24 +2872,53 @@ function claimName(preferred, taken) {
2726
2872
  taken.add(name);
2727
2873
  return name;
2728
2874
  }
2875
+ const MODULE_NAMES$1 = /* @__PURE__ */ new Set([
2876
+ "models",
2877
+ "timezone",
2878
+ "uuid",
2879
+ "uuid6",
2880
+ "datetime",
2881
+ "date",
2882
+ "time",
2883
+ "utc_today",
2884
+ "utc_time",
2885
+ "uuid4_str",
2886
+ "uuid7_str",
2887
+ "ulid_str",
2888
+ "list",
2889
+ "dict"
2890
+ ]);
2729
2891
  function modelAttrNames(model, m2mTables) {
2730
2892
  const belongsTo = singleColumnBelongsTo(model);
2731
2893
  const fkByScalarName = new Map(belongsTo.map((f) => [f.relationFromFields?.[0], f]));
2732
2894
  const taken = /* @__PURE__ */ new Set(["pk"]);
2733
2895
  const names = /* @__PURE__ */ new Map();
2734
- for (const field of model.fields) {
2896
+ const unresolved = {
2897
+ attr: /* @__PURE__ */ new Map(),
2898
+ helper: /* @__PURE__ */ new Map()
2899
+ };
2900
+ const reads = model.fields.map((field) => {
2901
+ if (field.kind === "object") return field.isList && isDeclaringM2MSide(model, field, m2mTables) ? ["models"] : [];
2902
+ return ["models", ...formatDefaultArgs(model, field, false, unresolved).map((arg) => /^\w+=([a-z_]\w*)/u.exec(arg)?.[1]).filter((name) => name !== void 0)];
2903
+ });
2904
+ for (const [i, field] of model.fields.entries()) {
2905
+ const readLater = new Set(reads.slice(i + 1).flat());
2906
+ const attrFor = (prismaName) => {
2907
+ const attr = djangoAttrName(makeSnakeCase(prismaName));
2908
+ return MODULE_NAMES$1.has(attr) && readLater.has(attr) ? `${attr}_field` : attr;
2909
+ };
2735
2910
  if (field.kind === "object") {
2736
- if (field.isList && isDeclaringM2MSide(model, field, m2mTables)) names.set(field.name, claimName(djangoAttrName(makeSnakeCase(field.name)), taken));
2911
+ if (field.isList && isDeclaringM2MSide(model, field, m2mTables)) names.set(field.name, claimName(attrFor(field.name), taken));
2737
2912
  continue;
2738
2913
  }
2739
2914
  const owner = fkByScalarName.get(field.name);
2740
2915
  if (owner) {
2741
- const attr = claimName(djangoAttrName(makeSnakeCase(owner.name)), taken);
2916
+ const attr = claimName(attrFor(owner.name), taken);
2742
2917
  names.set(owner.name, attr);
2743
2918
  names.set(field.name, attr);
2744
2919
  continue;
2745
2920
  }
2746
- names.set(field.name, claimName(djangoAttrName(makeSnakeCase(field.name)), taken));
2921
+ names.set(field.name, claimName(attrFor(field.name), taken));
2747
2922
  }
2748
2923
  return names;
2749
2924
  }
@@ -2753,7 +2928,8 @@ function resolveNames(models, m2mTables = []) {
2753
2928
  const takenHelpers = /* @__PURE__ */ new Set([
2754
2929
  "uuid4_str",
2755
2930
  "uuid7_str",
2756
- "ulid_str"
2931
+ "ulid_str",
2932
+ ...attr.values()
2757
2933
  ]);
2758
2934
  const helper = /* @__PURE__ */ new Map();
2759
2935
  for (const model of models) for (const field of model.fields) {
@@ -2933,7 +3109,7 @@ function generateScalarField(model, field, isPk, names, provider) {
2933
3109
  const outerArgs = [
2934
3110
  isPk ? "primary_key=True" : null,
2935
3111
  !field.isList && !field.isRequired ? "null=True" : null,
2936
- field.isUnique ? "unique=True" : null,
3112
+ field.isUnique && !isPk ? "unique=True" : null,
2937
3113
  attrName !== columnName ? `db_column=${toPythonString(columnName)}` : null,
2938
3114
  ...defaultArgs,
2939
3115
  emptyStringPk ? "default=None" : null
@@ -2953,7 +3129,7 @@ function onDeleteFor(field) {
2953
3129
  if (field.relationOnDelete && ON_DELETE[field.relationOnDelete]) return ON_DELETE[field.relationOnDelete];
2954
3130
  return field.isRequired ? "models.RESTRICT" : "models.SET_NULL";
2955
3131
  }
2956
- function generateForeignKeyField(model, relationField, scalarField, allModels, names) {
3132
+ function generateForeignKeyField(model, relationField, scalarField, allModels, names, isPk) {
2957
3133
  const attrName = attrNameOf(names, model, relationField);
2958
3134
  const columnName = fieldColumnName(scalarField);
2959
3135
  const backField = backRelation(relationField, model, allModels);
@@ -2963,16 +3139,18 @@ function generateForeignKeyField(model, relationField, scalarField, allModels, n
2963
3139
  const targetModel = allModels.find((m) => m.name === relationField.type);
2964
3140
  const referencedName = relationField.relationToFields?.[0];
2965
3141
  const referencedField = targetModel?.fields.find((f) => f.name === referencedName);
2966
- const toField = referencedField && !referencedField.isId && targetModel ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
3142
+ const targetPk = targetModel ? primaryKeyFields$1(targetModel) : [];
3143
+ const toField = referencedField && targetModel && !(targetPk.length === 1 && targetPk[0] === referencedName) ? `to_field=${toPythonString(attrNameOf(names, targetModel, referencedField))}` : null;
2967
3144
  return ` ${attrName} = models.${ctor}(${[
2968
3145
  target,
2969
3146
  `on_delete=${onDeleteFor(relationField)}`,
2970
3147
  `related_name=${relatedName}`,
2971
3148
  toField,
3149
+ isPk ? "primary_key=True" : null,
2972
3150
  columnName !== `${attrName}_id` ? `db_column=${toPythonString(columnName)}` : null,
2973
3151
  !relationField.isRequired ? "null=True" : null,
2974
3152
  ctor === "ForeignKey" ? "db_index=False" : null,
2975
- ...formatDefaultArgs(model, scalarField, false, names)
3153
+ ...formatDefaultArgs(model, scalarField, isPk, names)
2976
3154
  ].filter((a) => a !== null).join(", ")})`;
2977
3155
  }
2978
3156
  function uniqueClassName(preferred, taken) {
@@ -3069,10 +3247,10 @@ function generateMetaLines(model, indexes, names) {
3069
3247
  return fieldObj ? fieldColumnName(fieldObj) : prismaFieldName;
3070
3248
  };
3071
3249
  const uniqueIndexes = indexes.filter((idx) => idx.model === model.name && idx.type === "unique" && !idx.isDefinedOnField);
3072
- const constraints = model.uniqueFields.map((fields) => {
3250
+ const constraints = model.uniqueFields.filter((fields) => coversWrittenFields(model, fields)).map((fields) => {
3073
3251
  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
3252
  });
3075
- const indexEntries = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
3253
+ 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
3254
  const fieldNames = idx.fields.map((f) => {
3077
3255
  const ref = fieldRef(f.name);
3078
3256
  return toPythonString(f.sortOrder === "desc" ? `-${ref}` : ref);
@@ -3098,8 +3276,8 @@ function generateMetaLines(model, indexes, names) {
3098
3276
  ];
3099
3277
  }
3100
3278
  function compositePkLine(model, names) {
3101
- const pkFields = model.primaryKey?.fields ?? [];
3102
- if (pkFields.length === 0) return null;
3279
+ const pkFields = primaryKeyFields$1(model);
3280
+ if (pkFields.length < 2) return null;
3103
3281
  const belongsTo = singleColumnBelongsTo(model);
3104
3282
  return ` pk = models.CompositePrimaryKey(${pkFields.map((prismaFieldName) => {
3105
3283
  const attr = names.attr.get(nameKey(model.name, prismaFieldName)) ?? prismaFieldName;
@@ -3114,12 +3292,14 @@ function findNameConflicts(models, enums) {
3114
3292
  }
3115
3293
  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
3294
  }
3117
- function hasPrimaryKey(model) {
3118
- return model.fields.some((f) => f.isId) || (model.primaryKey?.fields.length ?? 0) > 0;
3295
+ function coversWrittenFields(model, fieldNames) {
3296
+ return fieldNames.every((name) => model.fields.some((f) => f.name === name));
3119
3297
  }
3120
3298
  function generateModelBody$1(model, allModels, indexes, m2mTables, names, provider) {
3121
- if (!hasPrimaryKey(model)) return null;
3299
+ const pkFields = primaryKeyFields$1(model);
3300
+ if (pkFields.length === 0) return null;
3122
3301
  const compositePk = compositePkLine(model, names);
3302
+ const singlePk = pkFields.length === 1 ? pkFields[0] : void 0;
3123
3303
  const belongsTo = singleColumnBelongsTo(model);
3124
3304
  const fkByScalarName = new Map(belongsTo.map((f) => [f.relationFromFields?.[0], f]));
3125
3305
  const fieldLines = model.fields.flatMap((field) => {
@@ -3130,9 +3310,9 @@ function generateModelBody$1(model, allModels, indexes, m2mTables, names, provid
3130
3310
  }
3131
3311
  return [];
3132
3312
  }
3313
+ const isPk = field.name === singlePk;
3133
3314
  const owner = fkByScalarName.get(field.name);
3134
- if (owner) return [generateForeignKeyField(model, owner, field, allModels, names)];
3135
- const isPk = field.isId;
3315
+ if (owner) return [generateForeignKeyField(model, owner, field, allModels, names, isPk)];
3136
3316
  return [generateScalarField(model, field, isPk, names, provider)];
3137
3317
  });
3138
3318
  return [
@@ -3148,8 +3328,11 @@ function generateEnumClass(enumDef) {
3148
3328
  }
3149
3329
  function collectGlobalImports$1(models, indexes, provider) {
3150
3330
  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);
3331
+ const modelsByName = new Map(models.map((m) => [m.name, m]));
3332
+ const indexClasses = indexes.filter((idx) => {
3333
+ const model = modelsByName.get(idx.model);
3334
+ return model !== void 0 && (idx.type === "normal" || idx.type === "fulltext") && coversWrittenFields(model, idx.fields.map((f) => f.name));
3335
+ }).map((idx) => postgresIndexClass(idx.algorithm)).filter((ctor) => ctor !== null);
3153
3336
  const needsUuid = scalarFields.some((f) => uuidDefaultVersion(f) === 4);
3154
3337
  const needsUuid6 = scalarFields.some((f) => uuidDefaultVersion(f) === 7);
3155
3338
  const needsUlid = scalarFields.some((f) => isUlidDefault(f));
@@ -3207,7 +3390,7 @@ function collectGlobalImports$1(models, indexes, provider) {
3207
3390
  // src/generator/django.ts
3208
3391
  function djangoCode(models, enums, indexes, provider = "postgresql") {
3209
3392
  const idx = indexes ?? [];
3210
- const emitted = models.filter((model) => hasPrimaryKey(model));
3393
+ const emitted = models.filter((model) => primaryKeyFields$1(model).length > 0);
3211
3394
  const m2mTables = collectManyToManyTables$1(emitted, enums);
3212
3395
  const names = resolveNames(emitted, m2mTables);
3213
3396
  return `${[
@@ -3401,6 +3584,7 @@ const COLUMN_HELPERS = {
3401
3584
  function createImports() {
3402
3585
  return {
3403
3586
  core: /* @__PURE__ */ new Set(),
3587
+ coreTypes: /* @__PURE__ */ new Set(),
3404
3588
  orm: /* @__PURE__ */ new Set(),
3405
3589
  ext: /* @__PURE__ */ new Map(),
3406
3590
  helpers: /* @__PURE__ */ new Set()
@@ -3440,8 +3624,15 @@ function applyImport(imports, req) {
3440
3624
  }
3441
3625
  function generateImports(imports, provider) {
3442
3626
  const mod = provider === "postgresql" ? "drizzle-orm/pg-core" : provider === "mysql" ? "drizzle-orm/mysql-core" : "drizzle-orm/sqlite-core";
3627
+ const coreNames = [...[...imports.core].map((name) => ({
3628
+ name,
3629
+ text: name
3630
+ })), ...[...imports.coreTypes].map((name) => ({
3631
+ name,
3632
+ text: `type ${name}`
3633
+ }))].toSorted((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3443
3634
  return [
3444
- imports.core.size > 0 ? `import { ${[...imports.core].toSorted().join(", ")} } from '${mod}'` : "",
3635
+ coreNames.length > 0 ? `import { ${coreNames.map((entry) => entry.text).join(", ")} } from '${mod}'` : "",
3445
3636
  imports.orm.size > 0 ? `import { ${[...imports.orm].toSorted().join(", ")} } from 'drizzle-orm'` : "",
3446
3637
  ...[...imports.ext.entries()].map(([pkg, entry]) => {
3447
3638
  return `import ${[entry.default, entry.named.size > 0 ? `{ ${[...entry.named].toSorted().join(", ")} }` : void 0].filter((c) => c !== void 0).join(", ")} from '${pkg}'`;
@@ -3619,10 +3810,16 @@ function resolveDefaultValue(field, provider, enums) {
3619
3810
  chain: `.default(sql\`${dflt}\`)`,
3620
3811
  imports: [SQL_IMPORT]
3621
3812
  };
3622
- if (fieldType === "DateTime") return {
3623
- chain: `.default(new Date(${tsString(dflt)}))`,
3624
- imports: []
3625
- };
3813
+ if (fieldType === "DateTime") {
3814
+ if (provider === "sqlite") return {
3815
+ chain: `.default(sql\`'${new Date(dflt).toISOString().replace("Z", "+00:00")}'\`)`,
3816
+ imports: [SQL_IMPORT]
3817
+ };
3818
+ return {
3819
+ chain: `.default(new Date(${tsString(dflt)}))`,
3820
+ imports: []
3821
+ };
3822
+ }
3626
3823
  if (fieldType === "Json") return {
3627
3824
  chain: `.default(${dflt})`,
3628
3825
  imports: []
@@ -3683,9 +3880,10 @@ function makeColumn(field, model, models, provider, imports, enums) {
3683
3880
  function makeTableConstraints(model, models, provider, imports, indexes, tableName) {
3684
3881
  const pkLine = model.primaryKey ? (() => {
3685
3882
  imports.core.add("primaryKey");
3686
- return `primaryKey({ name: '${tableName}_pkey', columns: [${model.primaryKey.fields.map((f) => `table.${f}`).join(", ")}] })`;
3883
+ const columns = model.primaryKey.fields.map((f) => `table.${f}`).join(", ");
3884
+ return provider === "mysql" ? `primaryKey({ columns: [${columns}] })` : `primaryKey({ name: '${tableName}_pkey', columns: [${columns}] })`;
3687
3885
  })() : null;
3688
- const indexLines = indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
3886
+ 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) => {
3689
3887
  const name = idx.dbName ?? constraintName(tableName, idx.fields.map((f) => fieldColumn(model, f.name)), idx.type === "unique" ? "key" : "idx", provider);
3690
3888
  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(",")));
3691
3889
  const make = idx.type !== "unique" ? "index" : referenced ? "unique" : "uniqueIndex";
@@ -3697,7 +3895,7 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
3697
3895
  return `sql\`\${table.${f.name}}(${prefix})\``;
3698
3896
  }).join(", ")})`;
3699
3897
  });
3700
- const fkLines = model.fields.filter((f) => f.kind === "object" && f.relationFromFields !== void 0 && f.relationFromFields.length > 0 && f.relationToFields !== void 0).map((f) => {
3898
+ const fkLines = model.fields.filter(isForeignKey).map((f) => {
3701
3899
  imports.core.add("foreignKey");
3702
3900
  const target = f.type === model.name ? "table" : resolveVarNameByType(f.type, models);
3703
3901
  const from = f.relationFromFields ?? [];
@@ -3712,6 +3910,19 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
3712
3910
  ].filter((l) => l !== null);
3713
3911
  return all.length > 0 ? all.join(", ") : null;
3714
3912
  }
3913
+ function isForeignKey(field) {
3914
+ return field.kind === "object" && field.relationFromFields !== void 0 && field.relationFromFields.length > 0 && field.relationToFields !== void 0;
3915
+ }
3916
+ function isOnForeignKeyCycle(model, models) {
3917
+ const targets = (name) => models.find((m) => m.name === name)?.fields.filter((f) => isForeignKey(f) && f.type !== name).map((f) => f.type) ?? [];
3918
+ const reaches = (from, seen) => {
3919
+ if (from.includes(model.name)) return true;
3920
+ const next = [...new Set(from.flatMap(targets))].filter((name) => !seen.has(name));
3921
+ return next.length > 0 && reaches(next, /* @__PURE__ */ new Set([...seen, ...next]));
3922
+ };
3923
+ const first = targets(model.name);
3924
+ return reaches(first, new Set(first));
3925
+ }
3715
3926
  function makeTable(model, models, provider, imports, enums, indexes) {
3716
3927
  const tableFunc = provider === "postgresql" ? "pgTable" : provider === "mysql" ? "mysqlTable" : "sqliteTable";
3717
3928
  imports.core.add(tableFunc);
@@ -3719,7 +3930,10 @@ function makeTable(model, models, provider, imports, enums, indexes) {
3719
3930
  const tableName = resolveTableName(model);
3720
3931
  const columns = model.fields.map((field) => makeColumn(field, model, models, provider, imports, enums)).filter((c) => c !== null).join(", ");
3721
3932
  const constraints = makeTableConstraints(model, models, provider, imports, indexes, tableName);
3722
- return constraints ? `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, (table) => [${constraints}])` : `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
3933
+ if (!constraints) return `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
3934
+ const configType = isOnForeignKeyCycle(model, models) ? provider === "postgresql" ? "PgTableExtraConfigValue" : provider === "mysql" ? "MySqlTableExtraConfigValue" : "SQLiteTableExtraConfigValue" : void 0;
3935
+ if (configType) imports.coreTypes.add(configType);
3936
+ return `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, ${configType ? `(table): ${configType}[]` : "(table)"} => [${constraints}])`;
3723
3937
  }
3724
3938
  function joinVarName(relationName) {
3725
3939
  return snakeToCamel(makeSnakeCase(relationName));
@@ -3762,68 +3976,93 @@ function makeM2MJoinTables(models, provider, imports) {
3762
3976
  return `export const ${joinVarName(pair.relationName)} = ${tableFunc}('${tableName}', { ${columns.join(", ")} }, (table) => [${constraints.join(", ")}])`;
3763
3977
  });
3764
3978
  }
3765
- function makeM2MJoinRelations(models, imports) {
3766
- const pairs = implicitJoinTables(models);
3767
- if (pairs.length > 0) imports.orm.add("relations");
3768
- return pairs.map((pair) => {
3769
- const varName = joinVarName(pair.relationName);
3770
- const leftVar = resolveVarNameByType(pair.left, models);
3771
- const rightVar = resolveVarNameByType(pair.right, models);
3772
- const leftPk = models.find((m) => m.name === pair.left)?.fields.find((f) => f.isId);
3773
- const rightPk = models.find((m) => m.name === pair.right)?.fields.find((f) => f.isId);
3774
- const leftKey = uncapitalizeName(pair.left);
3775
- const isSelf = pair.left === pair.right;
3776
- const rightKey = isSelf ? `${uncapitalizeName(pair.right)}_` : uncapitalizeName(pair.right);
3777
- const aName = isSelf ? `, relationName: '${pair.relationName}_A'` : "";
3778
- const bName = isSelf ? `, relationName: '${pair.relationName}_B'` : "";
3779
- return `export const ${varName}Relations = relations(${varName}, ({ one }) => ({ ${leftKey}: one(${leftVar}, { fields: [${varName}.A], references: [${leftVar}.${leftPk?.name ?? "id"}]${aName} }), ${rightKey}: one(${rightVar}, { fields: [${varName}.B], references: [${rightVar}.${rightPk?.name ?? "id"}]${bName} }) }))`;
3780
- });
3781
- }
3782
3979
  function uncapitalizeName(name) {
3783
3980
  const camel = snakeToCamel(makeSnakeCase(name));
3784
3981
  return camel.charAt(0).toLowerCase() + camel.slice(1);
3785
3982
  }
3983
+ function columnRefs(tableVar, columns) {
3984
+ const refs = columns.map((column) => `r.${tableVar}.${column}`);
3985
+ return refs.length > 1 ? `[${refs.join(", ")}]` : refs.join(", ");
3986
+ }
3987
+ function keyName(modelName, models) {
3988
+ return models.find((m) => m.name === modelName)?.fields.find((f) => f.isId)?.name ?? "id";
3989
+ }
3990
+ function call(options) {
3991
+ return options.length > 0 ? `({ ${options.join(", ")} })` : "()";
3992
+ }
3993
+ /**
3994
+ * One relation. The end that holds the foreign key names its columns and, where Prisma requires
3995
+ * the relation, `optional: false`; the other end of a one-to-one names them the other way round,
3996
+ * and the list end is `r.many.<table>()`, which drizzle pairs with the `one` through the alias
3997
+ * where a model has two relations to one table. An implicit many-to-many reads the join table
3998
+ * with `through` from both ends, so neither is inferred.
3999
+ */
3786
4000
  function makeRelationField(field, model, models, relFields) {
3787
4001
  const targetVar = resolveVarNameByType(field.type, models);
3788
4002
  const modelVar = resolveVarName(model);
3789
- const needsAlias = relFields.filter((f) => f.type === field.type).length > 1 && field.relationName;
4003
+ const alias = relFields.filter((f) => f.type === field.type).length > 1 && field.relationName ? [`alias: '${field.relationName}'`] : [];
3790
4004
  if (field.relationFromFields && field.relationFromFields.length > 0) {
3791
- const fromCols = field.relationFromFields.map((c) => `${modelVar}.${c}`).join(", ");
3792
- const toCols = (field.relationToFields && field.relationToFields.length > 0 ? field.relationToFields : ["id"]).map((c) => `${targetVar}.${c}`).join(", ");
3793
- const configParts = [
3794
- `fields: [${fromCols}]`,
3795
- `references: [${toCols}]`,
3796
- needsAlias ? `relationName: '${field.relationName}'` : ""
3797
- ].filter(Boolean);
3798
- return `${field.name}: one(${targetVar}, { ${configParts.join(", ")} })`;
4005
+ const toFields = field.relationToFields && field.relationToFields.length > 0 ? field.relationToFields : ["id"];
4006
+ return `${field.name}: r.one.${targetVar}${call([
4007
+ `from: ${columnRefs(modelVar, field.relationFromFields)}`,
4008
+ `to: ${columnRefs(targetVar, toFields)}`,
4009
+ ...field.isRequired ? ["optional: false"] : [],
4010
+ ...alias
4011
+ ])}`;
3799
4012
  }
3800
4013
  if (field.isList) {
3801
4014
  if (isImplicitManyToMany(field, model, models)) {
3802
4015
  const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
3803
- const relationName = field.relationName ?? `${left}To${right}`;
4016
+ const joinVar = joinVarName(field.relationName ?? `${left}To${right}`);
3804
4017
  const inverse = backRelation(field, model, models);
3805
- if (model.name === field.type && inverse) {
3806
- const column = isJoinSideA(field, model, inverse) ? "A" : "B";
3807
- return `${field.name}: many(${joinVarName(relationName)}, { relationName: '${relationName}_${column}' })`;
3808
- }
3809
- return `${field.name}: many(${joinVarName(relationName)})`;
4018
+ const [own, other] = inverse && isJoinSideA(field, model, inverse) ? ["A", "B"] : ["B", "A"];
4019
+ return `${field.name}: r.many.${targetVar}${call([`from: r.${modelVar}.${keyName(model.name, models)}.through(r.${joinVar}.${own})`, `to: r.${targetVar}.${keyName(field.type, models)}.through(r.${joinVar}.${other})`])}`;
3810
4020
  }
3811
- return needsAlias ? `${field.name}: many(${targetVar}, { relationName: '${field.relationName}' })` : `${field.name}: many(${targetVar})`;
4021
+ return `${field.name}: r.many.${targetVar}${call(alias)}`;
4022
+ }
4023
+ const inverse = backRelation(field, model, models);
4024
+ if (inverse?.relationFromFields && inverse.relationFromFields.length > 0) {
4025
+ const fromFields = inverse.relationToFields && inverse.relationToFields.length > 0 ? inverse.relationToFields : ["id"];
4026
+ return `${field.name}: r.one.${targetVar}${call([
4027
+ `from: ${columnRefs(modelVar, fromFields)}`,
4028
+ `to: ${columnRefs(targetVar, inverse.relationFromFields)}`,
4029
+ ...alias
4030
+ ])}`;
3812
4031
  }
3813
- return `${field.name}: one(${targetVar})`;
4032
+ return `${field.name}: r.one.${targetVar}${call(alias)}`;
3814
4033
  }
4034
+ /**
4035
+ * The relations as drizzle 1.0 reads them: one `defineRelations` over every table, the
4036
+ * join tables of the implicit many-to-many relations included, keyed by the table's variable.
4037
+ *
4038
+ * @example
4039
+ * ```ts
4040
+ * export const relations = defineRelations({ user, post }, (r) => ({
4041
+ * user: { posts: r.many.post() },
4042
+ * post: { author: r.one.user({ from: r.post.userId, to: r.user.id, optional: false }) },
4043
+ * }))
4044
+ * ```
4045
+ */
3815
4046
  function makeRelations$1(models, imports) {
3816
4047
  const modelsWithRels = models.filter((model) => model.fields.some((f) => f.kind === "object"));
3817
4048
  if (modelsWithRels.length === 0) return [];
3818
- imports.orm.add("relations");
3819
- return modelsWithRels.map((model) => {
4049
+ imports.orm.add("defineRelations");
4050
+ const pairs = implicitJoinTables(models);
4051
+ const tables = [...models.map((model) => resolveVarName(model)), ...pairs.map((pair) => joinVarName(pair.relationName))];
4052
+ const entries = [...modelsWithRels.map((model) => {
3820
4053
  const relFields = model.fields.filter((f) => f.kind === "object");
3821
4054
  const fieldLines = relFields.map((field) => makeRelationField(field, model, models, relFields)).join(", ");
3822
- const modelVar = resolveVarName(model);
3823
- const needsOne = relFields.some((f) => (f.relationFromFields?.length ?? 0) > 0 || !f.isList);
3824
- const needsMany = relFields.some((f) => f.isList && (f.relationFromFields?.length ?? 0) === 0);
3825
- return `export const ${modelVar}Relations = relations(${modelVar}, ({ ${[needsOne ? "one" : "", needsMany ? "many" : ""].filter(Boolean).join(", ")} }) => ({ ${fieldLines} }))`;
3826
- });
4055
+ return `${resolveVarName(model)}: { ${fieldLines} }`;
4056
+ }), ...pairs.map((pair) => {
4057
+ const joinVar = joinVarName(pair.relationName);
4058
+ const isSelf = pair.left === pair.right;
4059
+ return `${joinVar}: { ${["A", "B"].map((column) => {
4060
+ const modelName = column === "A" ? pair.left : pair.right;
4061
+ const key = uncapitalizeName(modelName);
4062
+ return `${isSelf && column === "B" ? `${key}_` : key}: r.one.${resolveVarNameByType(modelName, models)}({ from: r.${joinVar}.${column}, to: r.${resolveVarNameByType(modelName, models)}.${keyName(modelName, models)}, optional: false })`;
4063
+ }).join(", ")} }`;
4064
+ })];
4065
+ return [`export const relations = defineRelations({ ${tables.join(", ")} }, (r) => ({ ${entries.join(", ")} }))`];
3827
4066
  }
3828
4067
  // src/generator/drizzle.ts
3829
4068
  function drizzleSchema(datamodel, provider, indexes) {
@@ -3831,10 +4070,9 @@ function drizzleSchema(datamodel, provider, indexes) {
3831
4070
  const imports = createImports();
3832
4071
  const enumLines = makeEnumDeclarations$1(datamodel.models, datamodel.enums, db, imports);
3833
4072
  const tableLines = [...datamodel.models.map((model) => makeTable(model, datamodel.models, db, imports, datamodel.enums, indexes)), ...makeM2MJoinTables(datamodel.models, db, imports)];
3834
- const relationsLines = [...makeRelations$1(datamodel.models, imports), ...makeM2MJoinRelations(datamodel.models, imports)];
4073
+ const relationsLines = makeRelations$1(datamodel.models, imports);
3835
4074
  const enumLinesWithGap = enumLines.flatMap((line, i) => i < enumLines.length - 1 ? [line, ""] : [line]);
3836
4075
  const tableLinesWithGap = tableLines.flatMap((line, i) => i < tableLines.length - 1 ? [line, ""] : [line]);
3837
- const relationsLinesWithGap = relationsLines.flatMap((line, i) => i < relationsLines.length - 1 ? [line, ""] : [line]);
3838
4076
  const columnHelpers = makeColumnHelpers(imports);
3839
4077
  return [
3840
4078
  generateImports(imports, db),
@@ -3842,7 +4080,7 @@ function drizzleSchema(datamodel, provider, indexes) {
3842
4080
  ...columnHelpers.flatMap((helper) => [helper, ""]),
3843
4081
  ...enumLinesWithGap.length > 0 ? [...enumLinesWithGap, ""] : [],
3844
4082
  ...tableLinesWithGap,
3845
- ...relationsLinesWithGap.length > 0 ? ["", ...relationsLinesWithGap] : []
4083
+ ...relationsLines.length > 0 ? ["", ...relationsLines] : []
3846
4084
  ].join("\n");
3847
4085
  }
3848
4086
  function parsePrismaProvider(raw) {
@@ -4384,9 +4622,8 @@ function ectoSchemas(models, app, allModels, enums, options = {}) {
4384
4622
  const contextModels = allModels ?? models;
4385
4623
  return models.map((model) => {
4386
4624
  const idField = model.fields.find((f) => f.isId);
4387
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
4625
+ const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
4388
4626
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
4389
- if (!(idField || isCompositePk)) return "";
4390
4627
  const pk = idField ? getPrimaryKeyConfig(idField) : {
4391
4628
  line: "@primary_key false",
4392
4629
  typeSpec: "",
@@ -4762,63 +4999,190 @@ function relationMode(blocks) {
4762
4999
  return match ? [prismaString(match[1] ?? "")] : [];
4763
5000
  })[0] ?? "foreignKeys";
4764
5001
  }
4765
- // src/core/ecto.ts
4766
- function ecto(options) {
4767
- return Effect.gen(function* () {
4768
- const output = yield* requireOutput(options, "Hekireki-Ecto");
4769
- const problems = ectoProblems(options.dmmf.datamodel.models);
4770
- if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Ecto cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
4771
- const app = options.generator.config?.app ?? "MyApp";
4772
- const enums = options.dmmf.datamodel.enums;
4773
- const blocks = prismaBlocks(options.datamodel);
4774
- const files = ectoSchemaFiles(options.dmmf.datamodel.models, app, enums, {
4775
- provider: options.datasources[0]?.activeProvider,
4776
- indexes: options.dmmf.datamodel.indexes,
4777
- foreignKeyNames: relationMaps(blocks),
4778
- relationMode: relationMode(blocks)
4779
- });
4780
- return yield* emitMany(files, output);
4781
- });
5002
+ // src/core/ecto.ts
5003
+ function ecto(options) {
5004
+ return Effect.gen(function* () {
5005
+ const output = yield* requireOutput(options, "Hekireki-Ecto");
5006
+ const problems = ectoProblems(options.dmmf.datamodel.models);
5007
+ if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-Ecto cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
5008
+ const app = options.generator.config?.app ?? "MyApp";
5009
+ const enums = options.dmmf.datamodel.enums;
5010
+ const blocks = prismaBlocks(options.datamodel);
5011
+ const files = ectoSchemaFiles(options.dmmf.datamodel.models, app, enums, {
5012
+ provider: options.datasources[0]?.activeProvider,
5013
+ indexes: options.dmmf.datamodel.indexes,
5014
+ foreignKeyNames: relationMaps(blocks),
5015
+ relationMode: relationMode(blocks)
5016
+ });
5017
+ return yield* emitMany(files, output);
5018
+ });
5019
+ }
5020
+ // src/utils/humanizer.ts
5021
+ function irregular(singular, plural) {
5022
+ return {
5023
+ plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
5024
+ singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
5025
+ };
5026
+ }
5027
+ function wholeWordIrregular(singular, plural) {
5028
+ return {
5029
+ plural: [`^${singular}$`, plural],
5030
+ singular: [`^${plural}$`, singular]
5031
+ };
5032
+ }
5033
+ const IRREGULARS = [
5034
+ irregular("person", "people"),
5035
+ irregular("man", "men"),
5036
+ irregular("human", "humans"),
5037
+ irregular("child", "children"),
5038
+ irregular("sex", "sexes"),
5039
+ irregular("glove", "gloves"),
5040
+ irregular("move", "moves"),
5041
+ irregular("goose", "geese"),
5042
+ irregular("wave", "waves"),
5043
+ irregular("foot", "feet"),
5044
+ irregular("tooth", "teeth"),
5045
+ irregular("curriculum", "curricula"),
5046
+ irregular("database", "databases"),
5047
+ irregular("zombie", "zombies"),
5048
+ irregular("personnel", "personnel"),
5049
+ irregular("cache", "caches"),
5050
+ wholeWordIrregular("ex", "exes"),
5051
+ wholeWordIrregular("is", "are"),
5052
+ wholeWordIrregular("that", "those"),
5053
+ wholeWordIrregular("this", "these"),
5054
+ wholeWordIrregular("bus", "buses"),
5055
+ wholeWordIrregular("die", "dice"),
5056
+ wholeWordIrregular("tie", "ties")
5057
+ ];
5058
+ const PLURAL_RULES = [
5059
+ ["$", "s"],
5060
+ ["s$", "s"],
5061
+ ["(ax|test)is$", "$1es"],
5062
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
5063
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
5064
+ ["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
5065
+ ["([dti])um$", "$1a"],
5066
+ ["sis$", "ses"],
5067
+ ["(?:([^f])fe|([lr])f)$", "$1$2ves"],
5068
+ ["(hive)$", "$1s"],
5069
+ ["([^aeiouy]|qu)y$", "$1ies"],
5070
+ ["(x|ch|ss|sh)$", "$1es"],
5071
+ ["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
5072
+ ["(^[m|l])ouse$", "$1ice"],
5073
+ ["^(ox)$", "$1en"],
5074
+ ["(quiz)$", "$1zes"],
5075
+ ["(buz|blit|walt)z$", "$1zes"],
5076
+ ["(hoo|lea|loa|thie)f$", "$1ves"],
5077
+ ["(alumn|alg|larv|vertebr)a$", "$1ae"],
5078
+ ["(criteri|phenomen)on$", "$1a"],
5079
+ ...IRREGULARS.map((rule) => rule.plural)
5080
+ ].map(([pattern, replacement]) => ({
5081
+ pattern: new RegExp(pattern, "iu"),
5082
+ replacement
5083
+ }));
5084
+ const SINGULAR_RULES = [
5085
+ ["s$", ""],
5086
+ ["(n)ews$", "$1ews"],
5087
+ ["([dti])a$", "$1um"],
5088
+ ["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
5089
+ ["([^f])ves$", "$1fe"],
5090
+ ["(hive)s$", "$1"],
5091
+ ["(tive)s$", "$1"],
5092
+ ["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
5093
+ ["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
5094
+ ["(s)eries$", "$1eries"],
5095
+ ["(m)ovies$", "$1ovie"],
5096
+ ["(x|ch|ss|sh)es$", "$1"],
5097
+ ["(^[m|l])ice$", "$1ouse"],
5098
+ ["(?<!^[a-z])(o)es$", "$1"],
5099
+ ["(shoe)s$", "$1"],
5100
+ ["(cris|ax|test)es$", "$1is"],
5101
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
5102
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
5103
+ ["^(ox)en", "$1"],
5104
+ ["(matr|d)ices$", "$1ix"],
5105
+ ["(vert|ind)ices$", "$1ex"],
5106
+ ["(quiz)zes$", "$1"],
5107
+ ["(buz|blit|walt)zes$", "$1z"],
5108
+ ["(alumn|alg|larv|vertebr)ae$", "$1a"],
5109
+ ["(criteri|phenomen)a$", "$1on"],
5110
+ ["([b|r|c]ook|room|smooth)ies$", "$1ie"],
5111
+ ...IRREGULARS.map((rule) => rule.singular)
5112
+ ].map(([pattern, replacement]) => ({
5113
+ pattern: new RegExp(pattern, "iu"),
5114
+ replacement
5115
+ }));
5116
+ const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
5117
+ "staff",
5118
+ "training",
5119
+ "equipment",
5120
+ "information",
5121
+ "corn",
5122
+ "milk",
5123
+ "rice",
5124
+ "money",
5125
+ "species",
5126
+ "series",
5127
+ "fish",
5128
+ "sheep",
5129
+ "deer",
5130
+ "aircraft",
5131
+ "oz",
5132
+ "tsp",
5133
+ "tbsp",
5134
+ "ml",
5135
+ "l",
5136
+ "water",
5137
+ "waters",
5138
+ "semen",
5139
+ "sperm",
5140
+ "bison",
5141
+ "grass",
5142
+ "hair",
5143
+ "mud",
5144
+ "elk",
5145
+ "luggage",
5146
+ "moose",
5147
+ "offspring",
5148
+ "salmon",
5149
+ "shrimp",
5150
+ "someone",
5151
+ "swine",
5152
+ "trout",
5153
+ "tuna",
5154
+ "corps",
5155
+ "scissors",
5156
+ "means",
5157
+ "mail",
5158
+ "metadata"
5159
+ ]);
5160
+ function isUpperCaseLetter(char) {
5161
+ return char !== char.toLowerCase() && char === char.toUpperCase();
5162
+ }
5163
+ function isLowerCaseLetter(char) {
5164
+ return char !== char.toUpperCase() && char === char.toLowerCase();
4782
5165
  }
4783
- // src/utils/naming.ts
4784
- /**
4785
- * A Prisma name as a type name: the underscores join words, each word starts in upper case, and a
4786
- * word in capitals throughout (`PENDING`, `ID`) is lower-cased after its first letter; any other
4787
- * casing is the schema author's and is kept (`sku_code` → `SkuCode`, `userID` → `UserID`,
4788
- * `PENDING_REVIEW` → `PendingReview`).
4789
- *
4790
- * @param name - A Prisma model, field or enum value name.
4791
- * @returns The PascalCase name.
4792
- */
4793
- function pascalCase(name) {
4794
- const text = name.split("_").filter((word) => word !== "").map((word) => {
4795
- const rest = word.slice(1);
4796
- return `${word.charAt(0).toUpperCase()}${word === word.toUpperCase() ? rest.toLowerCase() : rest}`;
4797
- }).join("");
4798
- return /^\p{L}/u.test(text) ? text : `_${text}`;
5166
+ function applyRules(rules, word) {
5167
+ if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
5168
+ const rule = rules.findLast((candidate) => candidate.pattern.test(word));
5169
+ if (rule === void 0) return null;
5170
+ const result = word.replace(rule.pattern, rule.replacement);
5171
+ const first = result.charAt(0);
5172
+ return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
4799
5173
  }
4800
5174
  /**
4801
- * The first of `candidate`, `candidate1`, `candidate2`, ... that is free — the numbering
4802
- * `dotnet ef dbcontext scaffold` gives names that collide, which the other generators follow too.
5175
+ * Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
5176
+ * is returned as it is.
4803
5177
  *
4804
- * @param candidate - The preferred name.
4805
- * @param isTaken - Whether a name is already in use.
4806
- * @returns A free name.
5178
+ * @param word - The word to pluralize.
5179
+ * @returns The plural form Humanizer 2.14.1 gives.
4807
5180
  */
4808
- function uniqueName(candidate, isTaken) {
4809
- if (!isTaken(candidate)) return candidate;
4810
- for (let index = 1; index <= 1e4; index += 1) if (!isTaken(`${candidate}${index}`)) return `${candidate}${index}`;
4811
- return candidate;
4812
- }
4813
- function allocate(candidates, reserved, fold) {
4814
- const names = /* @__PURE__ */ new Map();
4815
- const taken = new Set(reserved.map(fold));
4816
- for (const { key, candidate } of candidates) {
4817
- const name = uniqueName(candidate, (one) => taken.has(fold(one)));
4818
- names.set(key, name);
4819
- taken.add(fold(name));
4820
- }
4821
- return names;
5181
+ function pluralize(word) {
5182
+ const result = applyRules(PLURAL_RULES, word);
5183
+ const asSingular = applyRules(SINGULAR_RULES, word);
5184
+ const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
5185
+ return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
4822
5186
  }
4823
5187
  function typeRef(fullName) {
4824
5188
  return `T|${fullName}`;
@@ -5100,7 +5464,7 @@ function planNames$1(models, enums, fileClasses, options) {
5100
5464
  ], (name) => name)
5101
5465
  };
5102
5466
  }
5103
- function className(names, model) {
5467
+ function className$1(names, model) {
5104
5468
  return names.classes.get(model.name) ?? model.name;
5105
5469
  }
5106
5470
  function enumName$1(names, name) {
@@ -5113,7 +5477,7 @@ function generatedRef(names, name) {
5113
5477
  return `${names.namespace}.${name}`;
5114
5478
  }
5115
5479
  function modelType(names, model) {
5116
- return typeRef(generatedRef(names, className(names, model)));
5480
+ return typeRef(generatedRef(names, className$1(names, model)));
5117
5481
  }
5118
5482
  function mapping$1(clr, isValueType, facets = [], elementStoreType = null, temporal = null) {
5119
5483
  return {
@@ -5492,7 +5856,7 @@ function enumConverters(plan) {
5492
5856
  * @returns The plan the file writers take.
5493
5857
  */
5494
5858
  function planEfCore(datamodel, options) {
5495
- const indexesOf = (model) => modelIndexes(model, datamodel.indexes ?? []);
5859
+ const indexesOf = (model) => modelIndexes$1(model, datamodel.indexes ?? []).filter((index) => index.fields.every((f) => model.fields.some((field) => field.name === f.name)));
5496
5860
  const schema = {
5497
5861
  provider: options.provider,
5498
5862
  models: datamodel.models,
@@ -5535,7 +5899,7 @@ function memberType(plan, field) {
5535
5899
  if (field.isList || !field.isRequired) return null;
5536
5900
  if (field.kind === "object") {
5537
5901
  const target = plan.models.find((m) => m.name === field.type);
5538
- return target ? generatedRef(plan.names, className(plan.names, target)) : null;
5902
+ return target ? generatedRef(plan.names, className$1(plan.names, target)) : null;
5539
5903
  }
5540
5904
  return /^\0T\|([^\0]+)\0$/u.exec(fieldPlan(plan, field).clr.clr)?.[1] ?? null;
5541
5905
  }
@@ -5559,7 +5923,7 @@ function entityProperty$1(plan, model, field) {
5559
5923
  * @returns The file, as `{ fileName, code }`.
5560
5924
  */
5561
5925
  function entityFile$1(plan, model) {
5562
- const name = className(plan.names, model);
5926
+ const name = className$1(plan.names, model);
5563
5927
  const fields = model.fields.filter((f) => f.kind !== "unsupported");
5564
5928
  const body = [
5565
5929
  `public partial class ${name}`,
@@ -9524,7 +9888,7 @@ function planExposed(datamodel, options) {
9524
9888
  const views = viewNames(blocks);
9525
9889
  const models = datamodel.models.filter((m) => !views.has(m.name));
9526
9890
  const conditions = indexConditions(blocks);
9527
- const indexes = new Map(models.map((m) => [m.name, modelIndexes(m, datamodel.indexes ?? []).map((index) => {
9891
+ const indexes = new Map(models.map((m) => [m.name, modelIndexes$1(m, datamodel.indexes ?? []).map((index) => {
9528
9892
  const condition = conditions.find((c) => c.model === m.name && c.unique === (index.type === "unique") && c.dbName === index.dbName && isSameList(c.fields, fieldNames(index)));
9529
9893
  return condition ? {
9530
9894
  type: index.type,
@@ -11484,7 +11848,7 @@ function constraintTag(onDelete, onUpdate) {
11484
11848
  function buildRelationTag(parts) {
11485
11849
  return `\`gorm:"${parts.join(";")}"\``;
11486
11850
  }
11487
- function generateRelationFields(model, associations) {
11851
+ function generateRelationFields(associations) {
11488
11852
  const belongsToLines = associations.belongsTo.map((assoc) => {
11489
11853
  const fieldName = goFieldName(assoc.name);
11490
11854
  const fkFieldName = assoc.foreignKeys.map(goFieldName).join(",");
@@ -11493,7 +11857,7 @@ function generateRelationFields(model, associations) {
11493
11857
  const isAmbiguous = fieldName !== goModelName(assoc.targetModel) || associations.belongsTo.filter((a) => a.targetModel === assoc.targetModel).length > 1;
11494
11858
  const isGuessed = fkFieldName === `${fieldName}${refsFieldName}`;
11495
11859
  const tagParts = [isAmbiguous || isComposite || !isGuessed ? `foreignKey:${fkFieldName}` : null, isComposite || needsReferencesTag(assoc.references) ? `references:${refsFieldName}` : null].filter((p) => p !== null);
11496
- const targetType = assoc.targetModel === model.name ? `*${goModelName(assoc.targetModel)}` : goModelName(assoc.targetModel);
11860
+ const targetType = `*${goModelName(assoc.targetModel)}`;
11497
11861
  return tagParts.length > 0 ? [
11498
11862
  fieldName,
11499
11863
  targetType,
@@ -11573,9 +11937,8 @@ function alignFields(rows) {
11573
11937
  }
11574
11938
  function generateModelStruct(model, allModels, enums, indexes, provider) {
11575
11939
  const idField = model.fields.find((f) => f.isId);
11576
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
11940
+ const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
11577
11941
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
11578
- if (!(idField || isCompositePk)) return null;
11579
11942
  const associations = getAssociations$2(model, allModels);
11580
11943
  const compositeTagMap = collectCompositeIndexTags(model, indexes);
11581
11944
  const tableName = model.dbName ?? model.name;
@@ -11584,7 +11947,7 @@ function generateModelStruct(model, allModels, enums, indexes, provider) {
11584
11947
  const fieldIndexTags = compositeTagMap.get(field.name) ?? [];
11585
11948
  return generateStructField(field, isPk, isCompositePk, fieldIndexTags, enums, provider);
11586
11949
  });
11587
- const relationLines = generateRelationFields(model, associations);
11950
+ const relationLines = generateRelationFields(associations);
11588
11951
  const tableNameMethod = [
11589
11952
  "",
11590
11953
  `func (${goModelName(model.name)}) TableName() string {`,
@@ -11904,7 +12267,7 @@ function formatImports(groups) {
11904
12267
  // src/generator/gorm.ts
11905
12268
  function generateGormModels(models, enums, indexes, packageName = "model", provider) {
11906
12269
  const idx = indexes ?? [];
11907
- const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider)).filter((body) => body !== null);
12270
+ const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider));
11908
12271
  return [
11909
12272
  `package ${packageName}`,
11910
12273
  ...formatImports(collectImports(models)),
@@ -12802,6 +13165,87 @@ function rustFieldIdent(snake) {
12802
13165
  derivedColumn: snake
12803
13166
  };
12804
13167
  }
13168
+ /**
13169
+ * The module a model, an enum or a join table is written as: its name in snake_case, a raw
13170
+ * identifier where that is a Rust keyword, in a file named without the `r#`.
13171
+ *
13172
+ * @example
13173
+ * ```rust
13174
+ * pub mod r#type; // type.rs
13175
+ * use super::r#type::Type;
13176
+ * ```
13177
+ */
13178
+ function rustModule(name) {
13179
+ const { ident } = rustFieldIdent(makeSnakeCase(name));
13180
+ return {
13181
+ ident,
13182
+ file: `${ident.startsWith("r#") ? ident.slice(2) : ident}.rs`
13183
+ };
13184
+ }
13185
+ /**
13186
+ * The Rust name of each scalar field of a model, the column sea-orm derives from it and the
13187
+ * `Column` variant DeriveEntityModel makes of it. Two fields can become one name in snake_case
13188
+ * (`createdAt` beside the `created_at` an OAuth provider returns): the one already written that
13189
+ * way keeps it, and the other is numbered (`created_at1`, variant `CreatedAt1`), which
13190
+ * `column_name` maps back to its own column.
13191
+ */
13192
+ function seaOrmFieldNames(model) {
13193
+ const candidates = model.fields.filter((f) => f.kind !== "object").map((f) => ({
13194
+ key: f.name,
13195
+ candidate: makeSnakeCase(f.name)
13196
+ }));
13197
+ const names = allocate([...candidates.filter((c) => c.candidate === c.key), ...candidates.filter((c) => c.candidate !== c.key)], [], (name) => name);
13198
+ return new Map(candidates.map(({ key, candidate }) => {
13199
+ const name = names.get(key) ?? candidate;
13200
+ return [key, {
13201
+ ...rustFieldIdent(name),
13202
+ variant: makePascalCase(name)
13203
+ }];
13204
+ }));
13205
+ }
13206
+ function columnVariant(models, modelName, fieldName) {
13207
+ const model = models.find((m) => m.name === modelName);
13208
+ return (model ? seaOrmFieldNames(model).get(fieldName)?.variant : void 0) ?? makePascalCase(fieldName);
13209
+ }
13210
+ /**
13211
+ * A method chain on a relation followed by `suffix`, laid out as rustfmt lays it out: on one
13212
+ * line while it fits in 100 columns and, with more than one call, the chain takes no more than
13213
+ * 60 (`chain_width`); otherwise one call per line under the path. Where the path alone does not
13214
+ * fit, rustfmt leaves the line as it is.
13215
+ *
13216
+ * @example
13217
+ * ```rust
13218
+ * Relation::Author.def()
13219
+ * super::block_version_to_resource::Relation::BlockVersion
13220
+ * .def()
13221
+ * .rev(),
13222
+ * ```
13223
+ */
13224
+ function relationChain(indent, path, calls, suffix) {
13225
+ const line = `${indent}${path}${calls.join("")}${suffix}`;
13226
+ const fits = line.length <= 100 && (calls.length === 1 || `${path}${calls.join("")}`.length <= 60);
13227
+ const broken = [`${indent}${path}`, ...calls.map((call, i) => `${indent} ${call}${i === calls.length - 1 ? suffix : ""}`)];
13228
+ return fits || broken.some((part) => part.length > 100) ? line : broken.join("\n");
13229
+ }
13230
+ /**
13231
+ * The body of `via()`: the relation from the join table back to this model, in `Some`, which
13232
+ * rustfmt opens onto lines of its own when the chain inside is broken.
13233
+ *
13234
+ * @example
13235
+ * ```rust
13236
+ * Some(super::post_to_tag::Relation::Post.def().rev())
13237
+ * Some(
13238
+ * super::block_version_to_resource::Relation::BlockVersion
13239
+ * .def()
13240
+ * .rev(),
13241
+ * )
13242
+ * ```
13243
+ */
13244
+ function viaBody(path) {
13245
+ const line = ` Some(${path}.def().rev())`;
13246
+ const inner = relationChain(" ", path, [".def()", ".rev()"], ",");
13247
+ return inner.includes("\n") ? ` Some(\n${inner}\n )` : line;
13248
+ }
12805
13249
  function resolveSeaOrmColumnType(field) {
12806
13250
  if (!field.nativeType) return null;
12807
13251
  const [nativeName, nativeArgs] = field.nativeType;
@@ -12998,7 +13442,7 @@ function generateEnum(e, serde = {}) {
12998
13442
  "}"
12999
13443
  ].join("\n");
13000
13444
  }
13001
- function generateRelationEnum(_model, associations) {
13445
+ function generateRelationEnum(model, associations, allModels) {
13002
13446
  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");
13003
13447
  const variants = [];
13004
13448
  const targetCount = /* @__PURE__ */ new Map();
@@ -13010,9 +13454,11 @@ function generateRelationEnum(_model, associations) {
13010
13454
  const isAmbiguous = (targetModel) => (targetCount.get(targetModel) ?? 0) > 1;
13011
13455
  for (const assoc of associations.belongsTo) {
13012
13456
  const variantName = makePascalCase(assoc.name);
13013
- const targetModule = makeSnakeCase(assoc.targetModel);
13014
- const fromCol = assoc.foreignKeys.length > 1 ? `(${assoc.foreignKeys.map((c) => `Column::${makePascalCase(c)}`).join(", ")})` : `Column::${makePascalCase(assoc.foreignKey)}`;
13015
- const toCol = assoc.referencesList.length > 1 ? `(${assoc.referencesList.map((c) => `super::${targetModule}::Column::${makePascalCase(c)}`).join(", ")})` : `super::${targetModule}::Column::${makePascalCase(assoc.references)}`;
13457
+ const targetModule = rustModule(assoc.targetModel).ident;
13458
+ const own = (c) => `Column::${columnVariant(allModels, model.name, c)}`;
13459
+ const target = (c) => `super::${targetModule}::Column::${columnVariant(allModels, assoc.targetModel, c)}`;
13460
+ const fromCol = assoc.foreignKeys.length > 1 ? `(${assoc.foreignKeys.map(own).join(", ")})` : own(assoc.foreignKey);
13461
+ const toCol = assoc.referencesList.length > 1 ? `(${assoc.referencesList.map(target).join(", ")})` : target(assoc.references);
13016
13462
  const actions = [assoc.onUpdate ? `on_update = "${assoc.onUpdate}"` : null, assoc.onDelete ? `on_delete = "${assoc.onDelete}"` : null].filter((l) => l !== null);
13017
13463
  const attribute = seaOrmAttribute(" ", [
13018
13464
  `belongs_to = "super::${targetModule}::Entity"`,
@@ -13024,14 +13470,14 @@ function generateRelationEnum(_model, associations) {
13024
13470
  }
13025
13471
  for (const assoc of associations.hasMany) {
13026
13472
  const variantName = makePascalCase(assoc.name);
13027
- const targetModule = makeSnakeCase(assoc.targetModel);
13028
- const attribute = seaOrmAttribute(" ", [`has_many = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${makePascalCase(assoc.references)}"`, `to = "super::${targetModule}::Column::${makePascalCase(assoc.foreignKey)}"`] : []]);
13473
+ const targetModule = rustModule(assoc.targetModel).ident;
13474
+ 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)}"`] : []]);
13029
13475
  variants.push(`${attribute}\n ${variantName},`);
13030
13476
  }
13031
13477
  for (const assoc of associations.hasOne) {
13032
13478
  const variantName = makePascalCase(assoc.name);
13033
- const targetModule = makeSnakeCase(assoc.targetModel);
13034
- const attribute = seaOrmAttribute(" ", [`has_one = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${makePascalCase(assoc.references)}"`, `to = "super::${targetModule}::Column::${makePascalCase(assoc.foreignKey)}"`] : []]);
13479
+ const targetModule = rustModule(assoc.targetModel).ident;
13480
+ 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)}"`] : []]);
13035
13481
  variants.push(`${attribute}\n ${variantName},`);
13036
13482
  }
13037
13483
  return [
@@ -13047,11 +13493,10 @@ function generateRelatedImpls(model, associations) {
13047
13493
  for (const assoc of associations.belongsTo) {
13048
13494
  if (emittedTargets.has(assoc.targetModel)) continue;
13049
13495
  emittedTargets.add(assoc.targetModel);
13050
- const targetModule = makeSnakeCase(assoc.targetModel);
13051
13496
  impls.push([
13052
- relatedImplHeader(targetModule),
13497
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13053
13498
  " fn to() -> RelationDef {",
13054
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13499
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13055
13500
  " }",
13056
13501
  "}"
13057
13502
  ].join("\n"));
@@ -13059,11 +13504,10 @@ function generateRelatedImpls(model, associations) {
13059
13504
  for (const assoc of associations.hasMany) {
13060
13505
  if (emittedTargets.has(assoc.targetModel)) continue;
13061
13506
  emittedTargets.add(assoc.targetModel);
13062
- const targetModule = makeSnakeCase(assoc.targetModel);
13063
13507
  impls.push([
13064
- relatedImplHeader(targetModule),
13508
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13065
13509
  " fn to() -> RelationDef {",
13066
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13510
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13067
13511
  " }",
13068
13512
  "}"
13069
13513
  ].join("\n"));
@@ -13071,18 +13515,17 @@ function generateRelatedImpls(model, associations) {
13071
13515
  for (const assoc of associations.hasOne) {
13072
13516
  if (emittedTargets.has(assoc.targetModel)) continue;
13073
13517
  emittedTargets.add(assoc.targetModel);
13074
- const targetModule = makeSnakeCase(assoc.targetModel);
13075
13518
  impls.push([
13076
- relatedImplHeader(targetModule),
13519
+ relatedImplHeader(rustModule(assoc.targetModel).ident),
13077
13520
  " fn to() -> RelationDef {",
13078
- ` Relation::${makePascalCase(assoc.name)}.def()`,
13521
+ relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
13079
13522
  " }",
13080
13523
  "}"
13081
13524
  ].join("\n"));
13082
13525
  }
13083
13526
  for (const assoc of associations.manyToMany) {
13084
13527
  if (assoc.targetModel === model.name) {
13085
- const junctionModule = makeSnakeCase(assoc.relationName);
13528
+ const junctionModule = rustModule(assoc.relationName).ident;
13086
13529
  const [own, other] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
13087
13530
  impls.push([
13088
13531
  `pub struct ${makePascalCase(assoc.name)}Link;`,
@@ -13093,8 +13536,8 @@ function generateRelatedImpls(model, associations) {
13093
13536
  "",
13094
13537
  " fn link(&self) -> Vec<RelationDef> {",
13095
13538
  " vec![",
13096
- ` super::${junctionModule}::Relation::${own}.def().rev(),`,
13097
- ` super::${junctionModule}::Relation::${other}.def(),`,
13539
+ relationChain(" ", `super::${junctionModule}::Relation::${own}`, [".def()", ".rev()"], ","),
13540
+ relationChain(" ", `super::${junctionModule}::Relation::${other}`, [".def()"], ","),
13098
13541
  " ]",
13099
13542
  " }",
13100
13543
  "}"
@@ -13103,17 +13546,17 @@ function generateRelatedImpls(model, associations) {
13103
13546
  }
13104
13547
  if (emittedTargets.has(assoc.targetModel)) continue;
13105
13548
  emittedTargets.add(assoc.targetModel);
13106
- const targetModule = makeSnakeCase(assoc.targetModel);
13107
- const junctionModule = makeSnakeCase(assoc.relationName);
13549
+ const targetModule = rustModule(assoc.targetModel).ident;
13550
+ const junctionModule = rustModule(assoc.relationName).ident;
13108
13551
  const junctionRelToTarget = makePascalCase(assoc.targetModel);
13109
13552
  const junctionRelToSelf = makePascalCase(model.name);
13110
13553
  impls.push([
13111
13554
  relatedImplHeader(targetModule),
13112
13555
  " fn to() -> RelationDef {",
13113
- ` super::${junctionModule}::Relation::${junctionRelToTarget}.def()`,
13556
+ relationChain(" ", `super::${junctionModule}::Relation::${junctionRelToTarget}`, [".def()"], ""),
13114
13557
  " }",
13115
13558
  " fn via() -> Option<RelationDef> {",
13116
- ` Some(super::${junctionModule}::Relation::${junctionRelToSelf}.def().rev())`,
13559
+ viaBody(`super::${junctionModule}::Relation::${junctionRelToSelf}`),
13117
13560
  " }",
13118
13561
  "}"
13119
13562
  ].join("\n"));
@@ -13121,21 +13564,21 @@ function generateRelatedImpls(model, associations) {
13121
13564
  return impls;
13122
13565
  }
13123
13566
  function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13124
- const idField = model.fields.find((f) => f.isId);
13125
- const compositePkFieldNames = new Set(model.primaryKey?.fields);
13126
- const isCompositePk = !idField && compositePkFieldNames.size > 0;
13127
- if (!(idField || isCompositePk)) return "";
13567
+ const primaryKey = new Set(primaryKeyFields$1(model));
13568
+ const isCompositePk = primaryKey.size > 1;
13569
+ if (primaryKey.size === 0) return "";
13128
13570
  const tableName = model.dbName ?? model.name;
13129
13571
  const associations = getAssociations$1(model, allModels);
13130
13572
  const enumNames = new Set(enums.map((e) => e.name));
13573
+ const fieldNames = seaOrmFieldNames(model);
13131
13574
  const scalarFields = model.fields.filter((f) => f.kind !== "object");
13132
13575
  const fieldLines = [];
13133
13576
  const stampLines = [];
13134
13577
  let stampsNow = false;
13135
13578
  let stampsOnInsert = false;
13136
13579
  for (const field of scalarFields) {
13137
- const isPk = field.isId || compositePkFieldNames.has(field.name);
13138
- const { ident: fieldName, derivedColumn } = rustFieldIdent(makeSnakeCase(field.name));
13580
+ const isPk = primaryKey.has(field.name);
13581
+ const { ident: fieldName, derivedColumn } = fieldNames.get(field.name) ?? rustFieldIdent(makeSnakeCase(field.name));
13139
13582
  const attrs = buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums);
13140
13583
  const nativeOverride = rustTypeForNative(field, provider);
13141
13584
  const elemType = enumNames.has(field.type) ? field.type : nativeOverride ?? prismaTypeToRustType(field.type, true);
@@ -13158,9 +13601,12 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13158
13601
  const assignment = ` self.${fieldName} = Set(${field.isRequired ? value : `Some(${value})`});`;
13159
13602
  stampLines.push(...condition, assignment.length <= 100 || ` self.${fieldName} =`.length > 99 ? assignment : ` self.${fieldName} =\n ${assignment.trimStart().slice(`self.${fieldName} = `.length)}`, " }");
13160
13603
  }
13161
- const relationEnum = generateRelationEnum(model, associations);
13604
+ const relationEnum = generateRelationEnum(model, associations, allModels);
13162
13605
  const relatedImpls = generateRelatedImpls(model, associations);
13163
- 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();
13606
+ const superImports = [...new Set(scalarFields.flatMap((f) => enumNames.has(f.type) ? [f.type] : f.type === "DateTime" && provider === "sqlite" ? ["PrismaDateTime"] : []))].map((name) => ({
13607
+ module: rustModule(name).ident,
13608
+ name
13609
+ })).toSorted((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0).map(({ module, name }) => `use super::${module}::${name};`);
13164
13610
  const generatedIdFields = scalarFields.filter((f) => f.type === "String" && !f.isList && generatedIdExpr(f) !== null);
13165
13611
  const useLines = [
13166
13612
  ...superImports,
@@ -13173,7 +13619,7 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
13173
13619
  " fn new() -> Self {",
13174
13620
  " Self {",
13175
13621
  ...generatedIdFields.map((field) => {
13176
- const { ident } = rustFieldIdent(makeSnakeCase(field.name));
13622
+ const { ident } = fieldNames.get(field.name) ?? rustFieldIdent(makeSnakeCase(field.name));
13177
13623
  const generate = generatedIdExpr(field) ?? "";
13178
13624
  const value = field.isRequired ? generate : `Some(${generate})`;
13179
13625
  const n = ident.length;
@@ -13234,8 +13680,8 @@ function pkRustType(modelName, models) {
13234
13680
  function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde = {}) {
13235
13681
  const [sortedLeft, sortedRight] = leftModel < rightModel ? [leftModel, rightModel] : [rightModel, leftModel];
13236
13682
  const tableName = `_${relationName}`;
13237
- const leftModule = makeSnakeCase(sortedLeft);
13238
- const rightModule = makeSnakeCase(sortedRight);
13683
+ const leftModule = rustModule(sortedLeft).ident;
13684
+ const rightModule = rustModule(sortedRight).ident;
13239
13685
  const isSelf = sortedLeft === sortedRight;
13240
13686
  const leftFk = isSelf ? "a" : `${makeSnakeCase(sortedLeft)}_id`;
13241
13687
  const rightFk = isSelf ? "b" : `${makeSnakeCase(sortedRight)}_id`;
@@ -13368,7 +13814,10 @@ function generateModRs(moduleNames) {
13368
13814
  return `${moduleNames.map((m) => `pub mod ${m};`).join("\n")}\n`;
13369
13815
  }
13370
13816
  function generatePreludeRs(models) {
13371
- return `${models.map((m) => `pub use super::${makeSnakeCase(m.name)}::Entity as ${m.name};`).toSorted().join("\n")}\n`;
13817
+ return `${models.map((m) => ({
13818
+ module: rustModule(m.name).ident,
13819
+ name: m.name
13820
+ })).toSorted((a, b) => a.module < b.module ? -1 : a.module > b.module ? 1 : 0).map(({ module, name }) => `pub use super::${module}::Entity as ${name};`).join("\n")}\n`;
13372
13821
  }
13373
13822
  function collectM2MPairs(models) {
13374
13823
  const pairs = models.flatMap((model) => getAssociations$1(model, models).manyToMany.map((assoc) => {
@@ -13391,8 +13840,8 @@ function collectM2MPairs(models) {
13391
13840
  function seaOrmFiles(models, enums, serde = {}, provider) {
13392
13841
  const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
13393
13842
  const enumFiles = enums.map((e) => ({
13394
- fileName: `${makeSnakeCase(e.name)}.rs`,
13395
- moduleName: makeSnakeCase(e.name),
13843
+ fileName: rustModule(e.name).file,
13844
+ moduleName: rustModule(e.name).ident,
13396
13845
  code: [
13397
13846
  ...useLines,
13398
13847
  "",
@@ -13400,23 +13849,26 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
13400
13849
  ""
13401
13850
  ].join("\n")
13402
13851
  }));
13403
- const entityFiles = models.map((model) => ({
13404
- fileName: `${makeSnakeCase(model.name)}.rs`,
13405
- moduleName: makeSnakeCase(model.name),
13852
+ const entities = models.map((model) => ({
13853
+ model,
13854
+ fileName: rustModule(model.name).file,
13855
+ moduleName: rustModule(model.name).ident,
13406
13856
  code: generateEntityFile(model, models, enums, serde, provider)
13407
13857
  })).filter((entry) => entry.code.trim().length > 0);
13408
- const m2mFiles = collectM2MPairs(models).map((pair) => {
13409
- const moduleName = makeSnakeCase(pair.relationName);
13410
- return {
13411
- fileName: `${moduleName}.rs`,
13412
- moduleName,
13413
- code: generateM2MEntity(pair.left, pair.right, pair.relationName, models, serde)
13414
- };
13415
- });
13858
+ const entityFiles = entities.map(({ fileName, moduleName, code }) => ({
13859
+ fileName,
13860
+ moduleName,
13861
+ code
13862
+ }));
13863
+ const m2mFiles = collectM2MPairs(models).map((pair) => ({
13864
+ fileName: rustModule(pair.relationName).file,
13865
+ moduleName: rustModule(pair.relationName).ident,
13866
+ code: generateM2MEntity(pair.left, pair.right, pair.relationName, models, serde)
13867
+ }));
13416
13868
  const preludeEntry = {
13417
13869
  fileName: "prelude.rs",
13418
13870
  moduleName: "prelude",
13419
- code: generatePreludeRs(models)
13871
+ code: generatePreludeRs(entities.map(({ model }) => model))
13420
13872
  };
13421
13873
  const prismaDateTimeFiles = provider === "sqlite" && models.some((m) => m.fields.some((f) => f.type === "DateTime")) ? [{
13422
13874
  fileName: "prisma_date_time.rs",
@@ -13432,7 +13884,10 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
13432
13884
  ];
13433
13885
  const modEntry = {
13434
13886
  fileName: "mod.rs",
13435
- code: generateModRs(allEntries.map((e) => e.moduleName).toSorted())
13887
+ code: generateModRs(allEntries.map((e) => e.moduleName).toSorted((a, b) => {
13888
+ const [x, y] = [a.replace(/^r#/u, ""), b.replace(/^r#/u, "")];
13889
+ return x < y ? -1 : x > y ? 1 : 0;
13890
+ }))
13436
13891
  };
13437
13892
  return [...allEntries.map(({ fileName, code }) => ({
13438
13893
  fileName,
@@ -13545,8 +14000,87 @@ const DECLARATIVE_RESERVED = /* @__PURE__ */ new Set([
13545
14000
  "metadata",
13546
14001
  "registry"
13547
14002
  ]);
14003
+ const MODULE_NAMES = /* @__PURE__ */ new Set([
14004
+ "bool",
14005
+ "bytes",
14006
+ "compiles",
14007
+ "date",
14008
+ "datetime",
14009
+ "dict",
14010
+ "float",
14011
+ "func",
14012
+ "int",
14013
+ "list",
14014
+ "mapped_column",
14015
+ "relationship",
14016
+ "str",
14017
+ "text",
14018
+ "time_type",
14019
+ "timezone",
14020
+ "utc_now",
14021
+ "uuid6",
14022
+ "uuid_mod"
14023
+ ]);
14024
+ const MODULE_CLASSES = /* @__PURE__ */ new Set([
14025
+ "Any",
14026
+ "Base",
14027
+ "BigInteger",
14028
+ "BindParameter",
14029
+ "Boolean",
14030
+ "Column",
14031
+ "ColumnElement",
14032
+ "Date",
14033
+ "DateTime",
14034
+ "DecimalType",
14035
+ "DeclarativeBase",
14036
+ "Dialect",
14037
+ "Double",
14038
+ "Enum",
14039
+ "Float",
14040
+ "ForeignKey",
14041
+ "ForeignKeyConstraint",
14042
+ "Index",
14043
+ "Integer",
14044
+ "Jsonb",
14045
+ "LargeBinary",
14046
+ "Mapped",
14047
+ "MetaData",
14048
+ "Numeric",
14049
+ "Optional",
14050
+ "PrimaryKeyConstraint",
14051
+ "SmallInteger",
14052
+ "String",
14053
+ "Table",
14054
+ "Text",
14055
+ "Time",
14056
+ "TypeDecorator",
14057
+ "UtcDateTime",
14058
+ "UtcDateTimeTz",
14059
+ "UtcTimestamp",
14060
+ "Uuid",
14061
+ "Xml"
14062
+ ]);
13548
14063
  function pythonAttrName(columnName) {
13549
- return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) ? `${columnName}_` : columnName;
14064
+ return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) || MODULE_NAMES.has(columnName) ? `${columnName}_` : columnName;
14065
+ }
14066
+ /**
14067
+ * The attribute a field of `model` is mapped to: its name in snake_case, made safe by
14068
+ * `pythonAttrName`. Where two fields come to one name (`createdAt` and `created_at`), the one
14069
+ * already written in snake_case keeps it and the other is numbered, its column named apart.
14070
+ */
14071
+ function attributeName(model, fieldName) {
14072
+ const candidates = (model?.fields ?? []).map((f) => ({
14073
+ key: f.name,
14074
+ candidate: pythonAttrName(makeSnakeCase(f.name))
14075
+ }));
14076
+ return allocate([...candidates.filter((c) => c.candidate === c.key), ...candidates.filter((c) => c.candidate !== c.key)], [], (name) => name).get(fieldName) ?? pythonAttrName(makeSnakeCase(fieldName));
14077
+ }
14078
+ function className(modelName) {
14079
+ const name = makePascalCase(modelName);
14080
+ return MODULE_CLASSES.has(name) ? `${name}_` : name;
14081
+ }
14082
+ function modelIndexes(model, indexes) {
14083
+ 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)));
13550
14084
  }
13551
14085
  function plainType(type, provider) {
13552
14086
  switch (type) {
@@ -13718,12 +14252,14 @@ function getAssociations(model, allModels) {
13718
14252
  continue;
13719
14253
  }
13720
14254
  const fkField = end.inverse;
13721
- const foreignKey = fkField.relationFromFields?.[0] ?? "";
14255
+ const foreignKeys = fkField.relationFromFields ?? [];
14256
+ const foreignKey = foreignKeys[0] ?? "";
13722
14257
  const { onDelete } = referentialActions(fkField);
13723
14258
  if (end.kind === "hasMany") hasMany.push({
13724
14259
  name: field.name,
13725
14260
  targetModel: field.type,
13726
14261
  foreignKey,
14262
+ foreignKeys,
13727
14263
  isList: true,
13728
14264
  onDelete
13729
14265
  });
@@ -13731,6 +14267,7 @@ function getAssociations(model, allModels) {
13731
14267
  name: field.name,
13732
14268
  targetModel: field.type,
13733
14269
  foreignKey,
14270
+ foreignKeys,
13734
14271
  isList: false,
13735
14272
  optional: !field.isRequired,
13736
14273
  onDelete
@@ -13894,11 +14431,10 @@ function usesUtcDateTime(models) {
13894
14431
  "DateTime"
13895
14432
  ].includes(f.nativeType?.[0] ?? "")));
13896
14433
  }
13897
- function needsForeignKeysParam(targetModel, assocs) {
13898
- return assocs.filter((a) => a.targetModel === targetModel).length > 1;
13899
- }
13900
- function foreignKeyEnds(model) {
13901
- return model.fields.filter((f) => f.kind === "object" && (f.relationFromFields ?? []).length > 0).map((f) => ({ targetModel: f.type }));
14434
+ function needsForeignKeysParam(modelName, targetModelName, allModels) {
14435
+ const keysTo = (from, to) => (allModels.find((m) => m.name === from)?.fields ?? []).filter((f) => f.kind === "object" && f.type === to && (f.relationFromFields ?? []).length > 0).length;
14436
+ const back = modelName === targetModelName ? 0 : keysTo(targetModelName, modelName);
14437
+ return keysTo(modelName, targetModelName) + back > 1;
13902
14438
  }
13903
14439
  function findBackPopulates(targetModelName, sourceModelName, foreignKey, allModels, sourceFieldName) {
13904
14440
  const targetModel = allModels.find((m) => m.name === targetModelName);
@@ -13913,15 +14449,17 @@ function findBackPopulates(targetModelName, sourceModelName, foreignKey, allMode
13913
14449
  if (f.relationFromFields?.includes(foreignKey)) return true;
13914
14450
  return sourceModel ? sourceModel.fields.some((sf) => sf.relationName === f.relationName && sf.relationFromFields?.includes(foreignKey)) : false;
13915
14451
  });
13916
- return pythonAttrName(makeSnakeCase(backField ? backField.name : sourceModelName));
14452
+ return backField ? attributeName(targetModel, backField.name) : pythonAttrName(makeSnakeCase(sourceModelName));
13917
14453
  }
13918
14454
  function findM2MBackPopulates(targetModelName, sourceModelName, sourceFieldName, relationName, allModels) {
13919
- 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));
13920
- return pythonAttrName(makeSnakeCase(backField ? backField.name : sourceModelName));
14455
+ const targetModel = allModels.find((m) => m.name === targetModelName);
14456
+ const backField = targetModel?.fields.find((f) => f.kind === "object" && f.type === sourceModelName && f.relationName === relationName && !(targetModelName === sourceModelName && f.name === sourceFieldName));
14457
+ return backField ? attributeName(targetModel, backField.name) : pythonAttrName(makeSnakeCase(sourceModelName));
13921
14458
  }
13922
- function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, tableName) {
14459
+ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, model, isMapperKey) {
14460
+ const tableName = model.dbName ?? model.name;
13923
14461
  const columnName = field.dbName ?? field.name;
13924
- const attrName = pythonAttrName(makeSnakeCase(field.name));
14462
+ const attrName = attributeName(model, field.name);
13925
14463
  const elemPythonType = field.kind === "enum" ? "str" : pythonTypeForNative(field);
13926
14464
  const pythonType = field.isList ? `list[${elemPythonType}]` : elemPythonType;
13927
14465
  const typeHint = field.isList || field.isRequired ? pythonType : `Optional[${pythonType}]`;
@@ -13976,12 +14514,12 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, pro
13976
14514
  if (!hasNowDefault) colArgs.push(`default=${utcNow}`);
13977
14515
  colArgs.push(`onupdate=${utcNow}`);
13978
14516
  }
13979
- if (colArgs.length === 0) return ` ${attrName}: Mapped[${typeHint}]`;
14517
+ if (colArgs.length === 0 && !isMapperKey) return ` ${attrName}: Mapped[${typeHint}]`;
13980
14518
  return ` ${attrName}: Mapped[${typeHint}] = mapped_column(${colArgs.join(", ")})`;
13981
14519
  }
13982
14520
  function generateTableArgs(model, allModels, indexes, provider) {
13983
14521
  const tableName = model.dbName ?? model.name;
13984
- const indexConstraints = indexes.filter((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
14522
+ const indexConstraints = modelIndexes(model, indexes).map((idx) => {
13985
14523
  const columns = idx.fields.map((f) => fieldColumn(model, f.name));
13986
14524
  const unique = idx.type === "unique";
13987
14525
  const name = idx.dbName ?? constraintName(tableName, columns, unique ? "key" : "idx", provider);
@@ -14022,63 +14560,69 @@ function deleteClause(onDelete) {
14022
14560
  }
14023
14561
  function generateBelongsToRelationships(associations, model, allModels) {
14024
14562
  return associations.belongsTo.map((assoc) => {
14025
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14026
- const snakeFk = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14563
+ const snakeName = attributeName(model, assoc.name);
14027
14564
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14028
- const fkClause = needsForeignKeysParam(assoc.targetModel, associations.belongsTo) ? `foreign_keys=[${snakeFk}], ` : "";
14029
- const pkField = model.fields.find((f) => f.isId);
14030
- const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${pythonAttrName(makeSnakeCase(pkField.name))}], ` : "";
14031
- return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
14565
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=[${assoc.foreignKeys.map((fk) => attributeName(model, fk)).join(", ")}], ` : "";
14566
+ const identity = primaryKeyFields$1(model);
14567
+ const remoteClause = assoc.targetModel === model.name && identity.length > 0 ? `remote_side=[${identity.map((name) => attributeName(model, name)).join(", ")}], ` : "";
14568
+ const target = className(assoc.targetModel);
14569
+ return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${target}"]` : `"${target}"`}] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
14032
14570
  });
14033
14571
  }
14572
+ function inverseForeignKeys(targetModelName, foreignKeys, allModels) {
14573
+ const targetModel = allModels.find((m) => m.name === targetModelName);
14574
+ const columns = foreignKeys.map((fk) => `${className(targetModelName)}.${attributeName(targetModel, fk)}`);
14575
+ return columns.length === 1 ? `"${columns.join("")}"` : `"[${columns.join(", ")}]"`;
14576
+ }
14034
14577
  function generateHasManyRelationships(associations, model, allModels) {
14035
14578
  return associations.hasMany.map((assoc) => {
14036
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14579
+ const snakeName = attributeName(model, assoc.name);
14037
14580
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14038
- const targetModel = allModels.find((m) => m.name === assoc.targetModel);
14039
- const needsFkParam = targetModel ? needsForeignKeysParam(model.name, foreignKeyEnds(targetModel)) : false;
14040
- const targetFkSnake = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14041
- const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
14042
- return ` ${snakeName}: Mapped[list["${makePascalCase(assoc.targetModel)}"]] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14581
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=${inverseForeignKeys(assoc.targetModel, assoc.foreignKeys, allModels)}, ` : "";
14582
+ return ` ${snakeName}: Mapped[list["${className(assoc.targetModel)}"]] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14043
14583
  });
14044
14584
  }
14045
14585
  function generateHasOneRelationships(associations, model, allModels) {
14046
14586
  return associations.hasOne.map((assoc) => {
14047
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14587
+ const snakeName = attributeName(model, assoc.name);
14048
14588
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
14049
- const targetModel = allModels.find((m) => m.name === assoc.targetModel);
14050
- const needsFkParam = targetModel ? needsForeignKeysParam(model.name, foreignKeyEnds(targetModel)) : false;
14051
- const targetFkSnake = pythonAttrName(makeSnakeCase(assoc.foreignKey));
14052
- const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
14053
- return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14589
+ const fkClause = needsForeignKeysParam(model.name, assoc.targetModel, allModels) ? `foreign_keys=${inverseForeignKeys(assoc.targetModel, assoc.foreignKeys, allModels)}, ` : "";
14590
+ const target = className(assoc.targetModel);
14591
+ return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${target}"]` : `"${target}"`}] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
14054
14592
  });
14055
14593
  }
14056
14594
  function generateManyToManyRelationships(associations, model, allModels, m2mTables) {
14057
14595
  return associations.manyToMany.map((assoc) => {
14058
- const snakeName = pythonAttrName(makeSnakeCase(assoc.name));
14596
+ const snakeName = attributeName(model, assoc.name);
14059
14597
  const backPop = findM2MBackPopulates(assoc.targetModel, model.name, assoc.name, assoc.relationName, allModels);
14060
14598
  const secondaryVar = m2mTables.find((t) => t.relationName === assoc.relationName)?.varName ?? makeSnakeCase(assoc.relationName);
14061
14599
  const pkField = model.fields.find((f) => f.isId);
14062
14600
  const other = model.fields.find((f) => f.kind === "object" && f.relationName === assoc.relationName && f.name !== assoc.name);
14063
14601
  const [own, far] = other && other.name < assoc.name ? ["B", "A"] : ["A", "B"];
14064
- const pk = `${makePascalCase(model.name)}.${pythonAttrName(makeSnakeCase(pkField?.name ?? "id"))}`;
14602
+ const pk = `${className(model.name)}.${attributeName(model, pkField?.name ?? "id")}`;
14065
14603
  const joinClause = assoc.targetModel === model.name && other ? `primaryjoin=lambda: ${pk} == ${secondaryVar}.c.${own}, secondaryjoin=lambda: ${pk} == ${secondaryVar}.c.${far}, ` : "";
14066
- return ` ${snakeName}: Mapped[list["${makePascalCase(assoc.targetModel)}"]] = relationship(secondary=${secondaryVar}, ${joinClause}back_populates="${backPop}")`;
14604
+ return ` ${snakeName}: Mapped[list["${className(assoc.targetModel)}"]] = relationship(secondary=${secondaryVar}, ${joinClause}back_populates="${backPop}")`;
14067
14605
  });
14068
14606
  }
14069
14607
  function generateModelBody(model, allModels, enums, indexes, m2mTables, provider) {
14070
14608
  const idField = model.fields.find((f) => f.isId);
14071
14609
  const compositePkFieldNames = new Set(model.primaryKey?.fields);
14072
- const isCompositePk = !idField && compositePkFieldNames.size > 0;
14073
- if (!(idField || isCompositePk)) return null;
14610
+ const identity = primaryKeyFields$1(model);
14611
+ if (identity.length === 0) return null;
14074
14612
  const associations = getAssociations(model, allModels);
14075
14613
  const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
14076
14614
  const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
14077
14615
  const tableName = model.dbName ?? model.name;
14078
- const columnLines = model.fields.filter((f) => f.kind !== "object").map((field) => {
14079
- return generateColumn(field, field.isId || compositePkFieldNames.has(field.name), belongsToFkFields.has(field.name), associations, allModels, enumMap, provider, tableName);
14616
+ const scalarFields = model.fields.filter((f) => f.kind !== "object");
14617
+ const isKeyless = !idField && !model.primaryKey;
14618
+ const columnLines = scalarFields.map((field) => {
14619
+ const isPk = field.isId || compositePkFieldNames.has(field.name);
14620
+ const isFk = belongsToFkFields.has(field.name);
14621
+ const isMapperKey = isKeyless && identity.includes(field.name);
14622
+ return generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, model, isMapperKey);
14080
14623
  });
14081
14624
  const tableArgsLines = generateTableArgs(model, allModels, indexes, provider);
14625
+ const mapperArgsLines = isKeyless ? ["", ` __mapper_args__ = {"primary_key": [${identity.map((name) => attributeName(model, name)).join(", ")}]}`] : [];
14082
14626
  const relationLines = [
14083
14627
  ...generateBelongsToRelationships(associations, model, allModels),
14084
14628
  ...generateHasManyRelationships(associations, model, allModels),
@@ -14087,11 +14631,12 @@ function generateModelBody(model, allModels, enums, indexes, m2mTables, provider
14087
14631
  ];
14088
14632
  const hasRelations = relationLines.length > 0;
14089
14633
  return [
14090
- `class ${makePascalCase(model.name)}(Base):`,
14634
+ `class ${className(model.name)}(Base):`,
14091
14635
  ` __tablename__ = "${tableName}"`,
14092
14636
  "",
14093
14637
  ...columnLines,
14094
14638
  ...tableArgsLines,
14639
+ ...mapperArgsLines,
14095
14640
  ...hasRelations ? [""] : [],
14096
14641
  ...relationLines
14097
14642
  ].join("\n");
@@ -14138,7 +14683,7 @@ function collectGlobalImports(models, _enums, indexes, m2mTables, provider) {
14138
14683
  }
14139
14684
  if (getAssociations(model, models).belongsTo.length > 0) saImports.add("ForeignKey");
14140
14685
  if (model.fields.some((f) => f.kind === "object" && (f.relationFromFields?.length ?? 0) > 1)) saImports.add("ForeignKeyConstraint");
14141
- if (indexes.some((idx) => idx.model === model.name && (idx.type === "unique" || idx.type === "normal" || idx.type === "fulltext"))) saImports.add("Index");
14686
+ if (modelIndexes(model, indexes).length > 0) saImports.add("Index");
14142
14687
  }
14143
14688
  if (m2mTables.length > 0) {
14144
14689
  saImports.add("Column");