hekireki 0.41.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.
- package/README.md +8 -0
- package/dist/bin/activerecord.js +1 -1
- package/dist/bin/ajv.js +1 -1
- package/dist/bin/arktype.js +1 -1
- package/dist/bin/atlas.js +1 -1
- package/dist/bin/django.js +1 -1
- package/dist/bin/drizzle.js +1 -1
- package/dist/bin/ecto.js +1 -1
- package/dist/bin/efcore.js +1 -1
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.js +1 -1
- package/dist/bin/er.js +1 -1
- package/dist/bin/exposed.js +1 -1
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/hekireki.js +5 -5
- package/dist/bin/kysely.js +1 -1
- package/dist/bin/openapi.js +1 -1
- package/dist/bin/pydantic.js +1 -1
- package/dist/bin/sea-orm.js +1 -1
- package/dist/bin/seed.js +1 -1
- package/dist/bin/sqlalchemy.js +1 -1
- package/dist/bin/typebox.js +1 -1
- package/dist/bin/valibot.js +1 -1
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-T1le3lMh.js → bin-CW-vHdsl.js} +834 -320
- package/dist/{discover-BaDQsKnF.js → discover-Dyzb_7x-.js} +1 -1
- package/dist/{emit-C4CeSye3.js → emit-CbBm_I0C.js} +1 -1
- package/dist/{migrate-2xlj7ayX.js → migrate-B-EMC7CC.js} +3 -3
- package/dist/{plan-B8PRmVdV.js → plan-DVBOCKsd.js} +3 -3
- package/dist/{prisma-model-DFq7AQgV.js → prisma-model-D98BBcmY.js} +12 -1
- package/dist/{run-BQlJs4wi.js → run-BKHmqvBJ.js} +4 -4
- package/dist/{schema-CfxnFLAw.js → schema-BRtObhQG.js} +1 -1
- package/dist/{sql-izRRI1Bi.js → sql-BYvD2bjK.js} +1 -1
- package/dist/{start-C7m4KyUz.js → start-KD0RjI3H.js} +128 -128
- package/dist/studio/assets/{chip-D4JuozFz.js → chip-Yqg0IG0j.js} +1 -1
- package/dist/studio/assets/{client-DTRYUhbF.js → client-C-v3Paav.js} +1 -1
- package/dist/studio/assets/{code-block-B7oBDy4S.js → code-block-CPMTXPBi.js} +1 -1
- package/dist/studio/assets/{confirm-dialog-DgDjONHy.js → confirm-dialog-CKCkchiq.js} +1 -1
- package/dist/studio/assets/{copy-CO4Wewxa.js → copy-BwEVZZV_.js} +1 -1
- package/dist/studio/assets/{copy-button-DDzfUcsZ.js → copy-button-jDpd_nhT.js} +1 -1
- package/dist/studio/assets/{docs-DyJ-qhu9.js → docs-CXORFY0Y.js} +1 -1
- package/dist/studio/assets/{enums._name-CcIWxnq0.js → enums._name-BUBU_WMt.js} +1 -1
- package/dist/studio/assets/{field-icon-DwOxCe9v.js → field-icon-C1wSRFKO.js} +1 -1
- package/dist/studio/assets/hooks-DXskM7gG.js +2 -0
- package/dist/studio/assets/{index-D2cpa83b.js → index-DzCcMC-d.js} +4 -4
- package/dist/studio/assets/{labels-BrdjOFB0.js → labels-B5gZ2suK.js} +1 -1
- package/dist/studio/assets/{lazyRouteComponent-CzElNsBd.js → lazyRouteComponent-8L8QSEt_.js} +1 -1
- package/dist/studio/assets/{lu-BwZ0uwaH.js → lu-CuC8O-Qz.js} +1 -1
- package/dist/studio/assets/{marked-text-CRUtsVYt.js → marked-text-B27DfhKS.js} +1 -1
- package/dist/studio/assets/{models._name-Drem1hqS.js → models._name-CQFgPD0T.js} +1 -1
- package/dist/studio/assets/{monaco-Doo5FK2W.js → monaco-CMwienx7.js} +1 -1
- package/dist/studio/assets/{monaco-CKCcdl6_.js → monaco-DRYJTcJl.js} +1 -1
- package/dist/studio/assets/{not-found-KT_nPOAU.js → not-found-69Bz9b3p.js} +1 -1
- package/dist/studio/assets/{prisma-4lQKwVn6.js → prisma-1nDx08Wb.js} +1 -1
- package/dist/studio/assets/{result-table-DY7sKJQq.js → result-table-0P18Nywh.js} +1 -1
- package/dist/studio/assets/routes-Bl7HRpBJ.js +1 -0
- package/dist/studio/assets/{schema-gate-Dq2l2Sh6.js → schema-gate-BmKFmHnL.js} +1 -1
- package/dist/studio/assets/schema-view-BEdx0cC2.js +9 -0
- package/dist/studio/assets/{sql-CjIkv--0.js → sql-GBZZtEKI.js} +1 -1
- package/dist/studio/assets/{table-BxRDQMeA.js → table-UZ-Yt-OH.js} +1 -1
- package/dist/studio/assets/{tabs-BwlFa2ot.js → tabs-BpZ0hh1V.js} +1 -1
- package/dist/studio/assets/{useFormValidation-DifOycKN.js → useFormValidation-CC75L7h9.js} +1 -1
- package/dist/studio/assets/{useMatch-D2UWqcDy.js → useMatch-BF6XlF2m.js} +1 -1
- package/dist/studio/assets/{useMultipleSelectionState-2b0OEWtf.js → useMultipleSelectionState-zIKA_ZNd.js} +1 -1
- package/dist/studio/index.html +9 -9
- package/package.json +10 -10
- package/dist/studio/assets/hooks-6J-1786l.js +0 -2
- package/dist/studio/assets/routes-D6hrrw5V.js +0 -1
- package/dist/studio/assets/schema-view-CnitOLrD.js +0 -9
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as emitMany, r as emitRaw, t as emit } from "./emit-
|
|
3
|
-
import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-
|
|
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/
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
|
54
|
-
["(
|
|
55
|
-
["(
|
|
56
|
-
["(
|
|
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
|
|
63
|
-
["(
|
|
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
|
-
["(
|
|
67
|
-
|
|
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
|
-
["([
|
|
79
|
-
["(
|
|
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]
|
|
84
|
-
["(
|
|
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
|
-
["(
|
|
89
|
-
["(
|
|
62
|
+
["^(m|l)ice$", "$1ouse"],
|
|
63
|
+
["(bus)(es)?$", "$1"],
|
|
64
|
+
["(o)es$", "$1"],
|
|
90
65
|
["(shoe)s$", "$1"],
|
|
91
|
-
["(cris|
|
|
92
|
-
["(
|
|
93
|
-
["(
|
|
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
|
-
["(
|
|
99
|
-
["(
|
|
100
|
-
|
|
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
|
|
108
|
-
|
|
109
|
-
"
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
155
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
-
*
|
|
167
|
-
* 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
|
|
170
|
-
* @returns The
|
|
113
|
+
* @param term - An underscored name.
|
|
114
|
+
* @returns The class name Rails gives.
|
|
171
115
|
*/
|
|
172
|
-
function
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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}`;
|
|
177
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* The first of `candidate`, `candidate1`, `candidate2`, ... that is free — the numbering
|
|
149
|
+
* `dotnet ef dbcontext scaffold` gives names that collide, which the other generators follow too.
|
|
150
|
+
*
|
|
151
|
+
* @param candidate - The preferred name.
|
|
152
|
+
* @param isTaken - Whether a name is already in use.
|
|
153
|
+
* @returns A free name.
|
|
154
|
+
*/
|
|
155
|
+
function uniqueName(candidate, isTaken) {
|
|
156
|
+
if (!isTaken(candidate)) return candidate;
|
|
157
|
+
for (let index = 1; index <= 1e4; index += 1) if (!isTaken(`${candidate}${index}`)) return `${candidate}${index}`;
|
|
158
|
+
return candidate;
|
|
159
|
+
}
|
|
160
|
+
function allocate(candidates, reserved, fold) {
|
|
161
|
+
const names = /* @__PURE__ */ new Map();
|
|
162
|
+
const taken = new Set(reserved.map(fold));
|
|
163
|
+
for (const { key, candidate } of candidates) {
|
|
164
|
+
const name = uniqueName(candidate, (one) => taken.has(fold(one)));
|
|
165
|
+
names.set(key, name);
|
|
166
|
+
taken.add(fold(name));
|
|
167
|
+
}
|
|
168
|
+
return names;
|
|
169
|
+
}
|
|
170
|
+
// src/helper/activerecord-names.ts
|
|
171
|
+
const ACTIVE_RECORD_INSTANCE_METHODS = new Set(`
|
|
172
|
+
__callbacks __id__ _assign_attribute _assign_attributes _before_commit_callbacks
|
|
173
|
+
_clear_locking_column _commit_callbacks _committed_already_called _create_callbacks _create_record
|
|
174
|
+
_delete_row _destroy _destroy_callbacks _ensure_no_duplicate_errors _find_callbacks _find_record
|
|
175
|
+
_in_memory_query_constraints_hash _initialize_callbacks _last_transaction_return_status
|
|
176
|
+
_lock_value_for_database _marshal_dump_7_1 _merge_attributes _new_record_before_last_commit
|
|
177
|
+
_query_attribute _query_constraints_hash _raise_readonly_record_error _raise_record_not_destroyed
|
|
178
|
+
_raise_record_not_touched_error _read_attribute _reflections _rollback_callbacks
|
|
179
|
+
_run_before_commit_callbacks _run_commit_callbacks _run_create_callbacks _run_destroy_callbacks
|
|
180
|
+
_run_find_callbacks _run_initialize_callbacks _run_rollback_callbacks _run_save_callbacks
|
|
181
|
+
_run_touch_callbacks _run_update_callbacks _run_validate_callbacks _run_validation_callbacks
|
|
182
|
+
_save_callbacks _touch_callbacks _touch_row _trigger_destroy_callback _trigger_update_callback
|
|
183
|
+
_update_callbacks _update_record _update_row _validate_callbacks _validation_callbacks _validators
|
|
184
|
+
_write_attribute accessed_fields add_to_transaction aggregate_reflections
|
|
185
|
+
all_attributes_for_inspect all_timestamp_attributes_in_model around_save_collection_association
|
|
186
|
+
assign_attributes assign_multiparameter_attributes
|
|
187
|
+
assign_nested_attributes_for_collection_association
|
|
188
|
+
assign_nested_attributes_for_one_to_one_association assign_nested_parameter_attributes
|
|
189
|
+
assign_to_or_mark_for_destruction associated_records_to_validate_or_save association
|
|
190
|
+
association_instance_get association_instance_set attachment_changes attachment_reflections
|
|
191
|
+
attribute attribute_aliases attribute_before_last_save attribute_before_type_cast attribute_change
|
|
192
|
+
attribute_change_to_be_saved attribute_for_database attribute_for_inspect attribute_in_database
|
|
193
|
+
attribute_method_patterns attribute_missing attribute_names attribute_names_for_partial_inserts
|
|
194
|
+
attribute_names_for_partial_updates attribute_names_for_serialization attribute_previous_change
|
|
195
|
+
attribute_previously_was attribute_was attribute_writer_missing attributes
|
|
196
|
+
attributes_before_type_cast attributes_for_create attributes_for_database attributes_for_inspect
|
|
197
|
+
attributes_for_update attributes_in_database attributes_with_values automatic_scope_inversing
|
|
198
|
+
automatically_invert_plural_associations becomes build_decrypt_attribute_assignments
|
|
199
|
+
build_encrypt_attribute_assignments cache_key cache_key_with_version cache_timestamp_format
|
|
200
|
+
cache_version cache_versioning call_reject_if cant_modify_encrypted_attributes_when_frozen changed
|
|
201
|
+
changed_attribute_names_to_save changed_attributes changes changes_applied changes_to_save
|
|
202
|
+
ciphertext_for class clear_attribute_change clear_attribute_changes clear_changes_information
|
|
203
|
+
clear_timestamp_attributes clear_transaction_record_state clone collection_cache_versioning
|
|
204
|
+
column_for_attribute compute_primary_key connection_handler context_for_validation
|
|
205
|
+
counter_cached_association_names create_or_update current_time_from_proper_timezone decrement
|
|
206
|
+
decrypt decrypt_attributes decrypt_rich_texts default_connection_handler default_role
|
|
207
|
+
default_scope_override default_scopes default_shard default_validation_context defined_enums
|
|
208
|
+
delete deprecated_associations_api_guard destroy destroy_association_async_batch_size
|
|
209
|
+
destroy_association_async_job destroy_associations destroy_row destroyed_by_association dup
|
|
210
|
+
encode_with encrypt encrypt_attributes encrypt_rich_texts encryptable_rich_texts
|
|
211
|
+
encrypted_attributes ensure_proper_type errors execute_callstack_for_multiparameter_attributes
|
|
212
|
+
extract_callstack_for_multiparameter_attributes find_parameter_position find_record_by_id
|
|
213
|
+
forget_attribute_assignments format_for_inspect freeze from_json full_inspect generate_token_for
|
|
214
|
+
halted_callback_hook hash id id_before_type_cast id_for_database id_in_database id_was
|
|
215
|
+
include_root_in_json increment init_attributes init_internals init_with init_with_attributes
|
|
216
|
+
initialize_internals_callback inspect_with_attributes inspection_filter lock_optimistically logger
|
|
217
|
+
mark_for_destruction marshal_dump marshal_load matched_attribute_method
|
|
218
|
+
max_updated_column_timestamp missing_attribute model_name mutations_before_last_save
|
|
219
|
+
mutations_from_database nested_attributes_options normalize_attribute
|
|
220
|
+
normalize_changed_in_place_attributes normalized_attributes partial_inserts partial_updates
|
|
221
|
+
perform_validations pluralize_table_names populate_with_current_scope_attributes pretty_print
|
|
222
|
+
previous_changes primary_key_prefix_type query_attribute query_cast_attribute
|
|
223
|
+
raise_validation_error raw_timestamp_to_cache_version read_attribute
|
|
224
|
+
read_attribute_before_type_cast read_attribute_for_database read_attribute_for_serialization
|
|
225
|
+
read_attribute_for_validation read_store_attribute record_timestamps record_update_timestamps
|
|
226
|
+
reload remember_transaction_record_state report_deprecated_association restore_attributes
|
|
227
|
+
restore_transaction_record_state run_callbacks sanitize_for_mass_assignment
|
|
228
|
+
sanitize_forbidden_attributes save save_belongs_to_association save_collection_association
|
|
229
|
+
save_has_one_association saved_change_to_attribute saved_changes serializable_add_includes
|
|
230
|
+
serializable_attributes serializable_hash signed_id signed_id_verifier_secret
|
|
231
|
+
skip_time_zone_conversion_for_attributes slice store_accessor_for store_full_class_name
|
|
232
|
+
store_full_sti_class strict_loaded_associations strict_loading_mode surreptitiously_touch
|
|
233
|
+
table_name_prefix table_name_suffix time_zone_aware_attributes time_zone_aware_types
|
|
234
|
+
timestamp_attributes_for_create_in_model timestamp_attributes_for_update_in_model to_ary to_gid
|
|
235
|
+
to_gid_param to_global_id to_key to_model to_partial_path to_sgid to_sgid_param
|
|
236
|
+
to_signed_global_id toggle touch touch_deferred_attributes touch_later transaction
|
|
237
|
+
type_cast_attribute_value type_for_attribute update update_attribute update_column update_columns
|
|
238
|
+
validate validate_belongs_to_association validate_collection_association
|
|
239
|
+
validate_encryption_allowed validate_has_one_association validates_absence_of
|
|
240
|
+
validates_acceptance_of validates_comparison_of validates_confirmation_of validates_exclusion_of
|
|
241
|
+
validates_format_of validates_inclusion_of validates_length_of validates_numericality_of
|
|
242
|
+
validates_presence_of validates_size_of validates_with validation_context values_at
|
|
243
|
+
verify_readonly_attribute with_lock with_transaction_returning_status write_attribute
|
|
244
|
+
write_store_attribute
|
|
245
|
+
`.split(/\s+/u).filter((name) => name !== ""));
|
|
246
|
+
const RUBY_TOP_LEVEL_CONSTANTS = new Set(`
|
|
247
|
+
ARGF ARGV AbstractController ActionCable ActionController ActionDispatch ActionMailbox
|
|
248
|
+
ActionMailer ActionPack ActionText ActionView ActiveJob ActiveModel ActiveRecord ActiveStorage
|
|
249
|
+
ActiveSupport Addrinfo ApplicationRecord Arel ArgumentError Array Base64 BasicObject BasicSocket
|
|
250
|
+
BigDecimal BigMath Binding CGI Class ClosedQueueError Comparable Complex Concurrent
|
|
251
|
+
ConditionVariable Crass Cuid Cuid2 Data Date DateAndTime DateTime Delegator DidYouMean Digest Dir
|
|
252
|
+
ENV EOFError ERB Encoding EncodingError Enumerable Enumerator Errno ErrorHighlight Erubi Etc
|
|
253
|
+
Exception FalseClass Fiber FiberError File FileTest FileUtils Float FloatDomainError Forwardable
|
|
254
|
+
FrozenError GC Gem GlobalID Hash HashWithIndifferentAccess I18n IO IOError IPAddr IPSocket
|
|
255
|
+
IndexError Integer Interrupt JSON Kernel KeyError LoadError LocalJumpError Logger Loofah Mail
|
|
256
|
+
Marcel Marshal MatchData Math Method Mime MiniMime Module Monitor MonitorMixin Mutex NameError
|
|
257
|
+
Nanoid Net NilClass NoMatchingPatternError NoMatchingPatternKeyError NoMemoryError NoMethodError
|
|
258
|
+
Nokogiri NotImplementedError Numeric Object ObjectSpace OpenSSL ParseError Pathname Prism
|
|
259
|
+
PrismaDateTime Proc Process Psych Queue Racc Rack Ractor RactorLocalSingleton Rails Rake Random
|
|
260
|
+
Range RangeError Rational RbConfig Refinement Regexp RegexpError Ruby RubyVM RuntimeError SQLite3
|
|
261
|
+
STDERR STDIN STDOUT ScanError ScriptError SecureRandom SecurityError Set Shellwords Signal
|
|
262
|
+
SignalException SignedGlobalID SimpleDelegator SingleForwardable Singleton SizedQueue Socket
|
|
263
|
+
SocketError StandardError StopIteration String StringIO StringScanner Struct Symbol SyntaxError
|
|
264
|
+
SyntaxSuggest SystemCallError SystemExit SystemStackError TCPServer TCPSocket TSort TZInfo
|
|
265
|
+
Tempfile Thread ThreadError ThreadGroup Time Timeout TracePoint Trix TrueClass TypeError UDPSocket
|
|
266
|
+
ULID UNIXServer UNIXSocket URI UnboundMethod UncaughtThrowError UnicodeNormalize Warning WeakRef
|
|
267
|
+
YAML Zeitwerk ZeroDivisionError Zlib
|
|
268
|
+
`.split(/\s+/u).filter((name) => name !== ""));
|
|
178
269
|
// src/helper/activerecord.ts
|
|
179
270
|
const RAILS_RESERVED_NAMES = new Set(`abort
|
|
180
271
|
abstract_class
|
|
@@ -912,6 +1003,54 @@ writer_method
|
|
|
912
1003
|
yaml_encoder
|
|
913
1004
|
yaml_tag
|
|
914
1005
|
yield_self`.split("\n"));
|
|
1006
|
+
/**
|
|
1007
|
+
* The class each model is written as: its name in PascalCase, or where Ruby or Rails already has
|
|
1008
|
+
* a constant of that name at the top level, that name with `Record` after it (`Monitor` is
|
|
1009
|
+
* `MonitorRecord`), numbered on where another model has that one too. Names are compared as the
|
|
1010
|
+
* files Zeitwerk loads them from, so two never share one.
|
|
1011
|
+
*
|
|
1012
|
+
* @param models - Every model of the schema.
|
|
1013
|
+
* @returns The class name of each model, by the model's name.
|
|
1014
|
+
*/
|
|
1015
|
+
function activeRecordClassNames(models) {
|
|
1016
|
+
const own = models.map((model) => ({
|
|
1017
|
+
key: model.name,
|
|
1018
|
+
candidate: makePascalCase(model.name)
|
|
1019
|
+
}));
|
|
1020
|
+
const renamed = allocate(own.filter(({ candidate }) => RUBY_TOP_LEVEL_CONSTANTS.has(candidate)).map(({ key, candidate }) => ({
|
|
1021
|
+
key,
|
|
1022
|
+
candidate: `${candidate}Record`
|
|
1023
|
+
})), [...RUBY_TOP_LEVEL_CONSTANTS, ...own.map(({ candidate }) => candidate)], makeSnakeCase);
|
|
1024
|
+
return new Map(own.map(({ key, candidate }) => [key, renamed.get(key) ?? candidate]));
|
|
1025
|
+
}
|
|
1026
|
+
function railsNames(models) {
|
|
1027
|
+
const classNames = activeRecordClassNames(models);
|
|
1028
|
+
const classOf = (modelName) => classNames.get(modelName) ?? makePascalCase(modelName);
|
|
1029
|
+
const associations = new Map(models.map((model) => {
|
|
1030
|
+
const named = relationEnds(model, models).map(({ field }) => ({
|
|
1031
|
+
field,
|
|
1032
|
+
name: makeSnakeCase(field.name)
|
|
1033
|
+
}));
|
|
1034
|
+
const taken = /* @__PURE__ */ new Set([
|
|
1035
|
+
...ACTIVE_RECORD_INSTANCE_METHODS,
|
|
1036
|
+
...named.map(({ name }) => name),
|
|
1037
|
+
...model.fields.filter((f) => f.kind !== "object").map((f) => f.dbName ?? f.name)
|
|
1038
|
+
]);
|
|
1039
|
+
const renamed = allocate(named.filter(({ name }) => ACTIVE_RECORD_INSTANCE_METHODS.has(name)).map(({ field, name }) => {
|
|
1040
|
+
const target = underscore(classOf(field.type));
|
|
1041
|
+
const conventional = field.isList ? pluralize$1(target) : target;
|
|
1042
|
+
return {
|
|
1043
|
+
key: field.name,
|
|
1044
|
+
candidate: taken.has(conventional) ? `${underscore(classOf(model.name))}_${name}` : conventional
|
|
1045
|
+
};
|
|
1046
|
+
}), [...taken], makeSnakeCase);
|
|
1047
|
+
return [model.name, new Map(named.map(({ field, name }) => [field.name, renamed.get(field.name) ?? name]))];
|
|
1048
|
+
}));
|
|
1049
|
+
return {
|
|
1050
|
+
classOf,
|
|
1051
|
+
associationOf: (modelName, fieldName) => associations.get(modelName)?.get(fieldName) ?? makeSnakeCase(fieldName)
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
915
1054
|
function primaryKeyFields(model) {
|
|
916
1055
|
const idField = model.fields.find((f) => f.isId);
|
|
917
1056
|
return idField ? [idField.name] : model.primaryKey?.fields ?? [];
|
|
@@ -1176,8 +1315,9 @@ function yamlLines(tree, depth) {
|
|
|
1176
1315
|
* (`activerecord.errors.models.todo.attributes.title.blank`).
|
|
1177
1316
|
*/
|
|
1178
1317
|
function activeRecordLocaleFiles(models) {
|
|
1318
|
+
const { classOf, associationOf } = railsNames(models);
|
|
1179
1319
|
return models.flatMap((model) => {
|
|
1180
|
-
const modelKey =
|
|
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" ?
|
|
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 =
|
|
1464
|
+
const className = classOf(model.name);
|
|
1465
|
+
const modelSnake = underscore(className);
|
|
1324
1466
|
const tableName = model.dbName ?? model.name;
|
|
1325
|
-
const tableNameLines = tableName === pluralize(
|
|
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 =
|
|
1450
|
-
const
|
|
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
|
-
...
|
|
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
|
-
...
|
|
1599
|
+
...inverse === null || conventional ? [] : [`inverse_of: :${inverse}`]
|
|
1457
1600
|
]);
|
|
1458
1601
|
});
|
|
1459
1602
|
const hasLines = (macro, list) => list.map((a) => {
|
|
1460
|
-
const name =
|
|
1461
|
-
const inverse =
|
|
1462
|
-
const
|
|
1463
|
-
const derivedClass = macro === "has_many" ? name
|
|
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: "${
|
|
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 =
|
|
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
|
-
...
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
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
|
|
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,
|
|
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
|
|
3102
|
-
if (pkFields.length
|
|
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
|
|
3118
|
-
return model.fields.some((f) => f.
|
|
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
|
-
|
|
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
|
|
3152
|
-
const indexClasses = indexes.filter((idx) =>
|
|
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) =>
|
|
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
|
-
|
|
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}'`;
|
|
@@ -3692,7 +3883,7 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
|
|
|
3692
3883
|
const columns = model.primaryKey.fields.map((f) => `table.${f}`).join(", ");
|
|
3693
3884
|
return provider === "mysql" ? `primaryKey({ columns: [${columns}] })` : `primaryKey({ name: '${tableName}_pkey', columns: [${columns}] })`;
|
|
3694
3885
|
})() : null;
|
|
3695
|
-
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) => {
|
|
3696
3887
|
const name = idx.dbName ?? constraintName(tableName, idx.fields.map((f) => fieldColumn(model, f.name)), idx.type === "unique" ? "key" : "idx", provider);
|
|
3697
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(",")));
|
|
3698
3889
|
const make = idx.type !== "unique" ? "index" : referenced ? "unique" : "uniqueIndex";
|
|
@@ -3704,7 +3895,7 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
|
|
|
3704
3895
|
return `sql\`\${table.${f.name}}(${prefix})\``;
|
|
3705
3896
|
}).join(", ")})`;
|
|
3706
3897
|
});
|
|
3707
|
-
const fkLines = model.fields.filter(
|
|
3898
|
+
const fkLines = model.fields.filter(isForeignKey).map((f) => {
|
|
3708
3899
|
imports.core.add("foreignKey");
|
|
3709
3900
|
const target = f.type === model.name ? "table" : resolveVarNameByType(f.type, models);
|
|
3710
3901
|
const from = f.relationFromFields ?? [];
|
|
@@ -3719,6 +3910,19 @@ function makeTableConstraints(model, models, provider, imports, indexes, tableNa
|
|
|
3719
3910
|
].filter((l) => l !== null);
|
|
3720
3911
|
return all.length > 0 ? all.join(", ") : null;
|
|
3721
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
|
+
}
|
|
3722
3926
|
function makeTable(model, models, provider, imports, enums, indexes) {
|
|
3723
3927
|
const tableFunc = provider === "postgresql" ? "pgTable" : provider === "mysql" ? "mysqlTable" : "sqliteTable";
|
|
3724
3928
|
imports.core.add(tableFunc);
|
|
@@ -3726,7 +3930,10 @@ function makeTable(model, models, provider, imports, enums, indexes) {
|
|
|
3726
3930
|
const tableName = resolveTableName(model);
|
|
3727
3931
|
const columns = model.fields.map((field) => makeColumn(field, model, models, provider, imports, enums)).filter((c) => c !== null).join(", ");
|
|
3728
3932
|
const constraints = makeTableConstraints(model, models, provider, imports, indexes, tableName);
|
|
3729
|
-
|
|
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}])`;
|
|
3730
3937
|
}
|
|
3731
3938
|
function joinVarName(relationName) {
|
|
3732
3939
|
return snakeToCamel(makeSnakeCase(relationName));
|
|
@@ -4415,9 +4622,8 @@ function ectoSchemas(models, app, allModels, enums, options = {}) {
|
|
|
4415
4622
|
const contextModels = allModels ?? models;
|
|
4416
4623
|
return models.map((model) => {
|
|
4417
4624
|
const idField = model.fields.find((f) => f.isId);
|
|
4418
|
-
const compositePkFieldNames = new Set(model
|
|
4625
|
+
const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
|
|
4419
4626
|
const isCompositePk = !idField && compositePkFieldNames.size > 0;
|
|
4420
|
-
if (!(idField || isCompositePk)) return "";
|
|
4421
4627
|
const pk = idField ? getPrimaryKeyConfig(idField) : {
|
|
4422
4628
|
line: "@primary_key false",
|
|
4423
4629
|
typeSpec: "",
|
|
@@ -4811,45 +5017,172 @@ function ecto(options) {
|
|
|
4811
5017
|
return yield* emitMany(files, output);
|
|
4812
5018
|
});
|
|
4813
5019
|
}
|
|
4814
|
-
// src/utils/
|
|
4815
|
-
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
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();
|
|
5165
|
+
}
|
|
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;
|
|
4830
5173
|
}
|
|
4831
5174
|
/**
|
|
4832
|
-
*
|
|
4833
|
-
*
|
|
5175
|
+
* Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
|
|
5176
|
+
* is returned as it is.
|
|
4834
5177
|
*
|
|
4835
|
-
* @param
|
|
4836
|
-
* @
|
|
4837
|
-
* @returns A free name.
|
|
5178
|
+
* @param word - The word to pluralize.
|
|
5179
|
+
* @returns The plural form Humanizer 2.14.1 gives.
|
|
4838
5180
|
*/
|
|
4839
|
-
function
|
|
4840
|
-
|
|
4841
|
-
|
|
4842
|
-
|
|
4843
|
-
}
|
|
4844
|
-
function allocate(candidates, reserved, fold) {
|
|
4845
|
-
const names = /* @__PURE__ */ new Map();
|
|
4846
|
-
const taken = new Set(reserved.map(fold));
|
|
4847
|
-
for (const { key, candidate } of candidates) {
|
|
4848
|
-
const name = uniqueName(candidate, (one) => taken.has(fold(one)));
|
|
4849
|
-
names.set(key, name);
|
|
4850
|
-
taken.add(fold(name));
|
|
4851
|
-
}
|
|
4852
|
-
return names;
|
|
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;
|
|
4853
5186
|
}
|
|
4854
5187
|
function typeRef(fullName) {
|
|
4855
5188
|
return `T|${fullName}`;
|
|
@@ -5131,7 +5464,7 @@ function planNames$1(models, enums, fileClasses, options) {
|
|
|
5131
5464
|
], (name) => name)
|
|
5132
5465
|
};
|
|
5133
5466
|
}
|
|
5134
|
-
function className(names, model) {
|
|
5467
|
+
function className$1(names, model) {
|
|
5135
5468
|
return names.classes.get(model.name) ?? model.name;
|
|
5136
5469
|
}
|
|
5137
5470
|
function enumName$1(names, name) {
|
|
@@ -5144,7 +5477,7 @@ function generatedRef(names, name) {
|
|
|
5144
5477
|
return `${names.namespace}.${name}`;
|
|
5145
5478
|
}
|
|
5146
5479
|
function modelType(names, model) {
|
|
5147
|
-
return typeRef(generatedRef(names, className(names, model)));
|
|
5480
|
+
return typeRef(generatedRef(names, className$1(names, model)));
|
|
5148
5481
|
}
|
|
5149
5482
|
function mapping$1(clr, isValueType, facets = [], elementStoreType = null, temporal = null) {
|
|
5150
5483
|
return {
|
|
@@ -5523,7 +5856,7 @@ function enumConverters(plan) {
|
|
|
5523
5856
|
* @returns The plan the file writers take.
|
|
5524
5857
|
*/
|
|
5525
5858
|
function planEfCore(datamodel, options) {
|
|
5526
|
-
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)));
|
|
5527
5860
|
const schema = {
|
|
5528
5861
|
provider: options.provider,
|
|
5529
5862
|
models: datamodel.models,
|
|
@@ -5566,7 +5899,7 @@ function memberType(plan, field) {
|
|
|
5566
5899
|
if (field.isList || !field.isRequired) return null;
|
|
5567
5900
|
if (field.kind === "object") {
|
|
5568
5901
|
const target = plan.models.find((m) => m.name === field.type);
|
|
5569
|
-
return target ? generatedRef(plan.names, className(plan.names, target)) : null;
|
|
5902
|
+
return target ? generatedRef(plan.names, className$1(plan.names, target)) : null;
|
|
5570
5903
|
}
|
|
5571
5904
|
return /^\0T\|([^\0]+)\0$/u.exec(fieldPlan(plan, field).clr.clr)?.[1] ?? null;
|
|
5572
5905
|
}
|
|
@@ -5590,7 +5923,7 @@ function entityProperty$1(plan, model, field) {
|
|
|
5590
5923
|
* @returns The file, as `{ fileName, code }`.
|
|
5591
5924
|
*/
|
|
5592
5925
|
function entityFile$1(plan, model) {
|
|
5593
|
-
const name = className(plan.names, model);
|
|
5926
|
+
const name = className$1(plan.names, model);
|
|
5594
5927
|
const fields = model.fields.filter((f) => f.kind !== "unsupported");
|
|
5595
5928
|
const body = [
|
|
5596
5929
|
`public partial class ${name}`,
|
|
@@ -9555,7 +9888,7 @@ function planExposed(datamodel, options) {
|
|
|
9555
9888
|
const views = viewNames(blocks);
|
|
9556
9889
|
const models = datamodel.models.filter((m) => !views.has(m.name));
|
|
9557
9890
|
const conditions = indexConditions(blocks);
|
|
9558
|
-
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) => {
|
|
9559
9892
|
const condition = conditions.find((c) => c.model === m.name && c.unique === (index.type === "unique") && c.dbName === index.dbName && isSameList(c.fields, fieldNames(index)));
|
|
9560
9893
|
return condition ? {
|
|
9561
9894
|
type: index.type,
|
|
@@ -11515,7 +11848,7 @@ function constraintTag(onDelete, onUpdate) {
|
|
|
11515
11848
|
function buildRelationTag(parts) {
|
|
11516
11849
|
return `\`gorm:"${parts.join(";")}"\``;
|
|
11517
11850
|
}
|
|
11518
|
-
function generateRelationFields(
|
|
11851
|
+
function generateRelationFields(associations) {
|
|
11519
11852
|
const belongsToLines = associations.belongsTo.map((assoc) => {
|
|
11520
11853
|
const fieldName = goFieldName(assoc.name);
|
|
11521
11854
|
const fkFieldName = assoc.foreignKeys.map(goFieldName).join(",");
|
|
@@ -11524,7 +11857,7 @@ function generateRelationFields(model, associations) {
|
|
|
11524
11857
|
const isAmbiguous = fieldName !== goModelName(assoc.targetModel) || associations.belongsTo.filter((a) => a.targetModel === assoc.targetModel).length > 1;
|
|
11525
11858
|
const isGuessed = fkFieldName === `${fieldName}${refsFieldName}`;
|
|
11526
11859
|
const tagParts = [isAmbiguous || isComposite || !isGuessed ? `foreignKey:${fkFieldName}` : null, isComposite || needsReferencesTag(assoc.references) ? `references:${refsFieldName}` : null].filter((p) => p !== null);
|
|
11527
|
-
const targetType =
|
|
11860
|
+
const targetType = `*${goModelName(assoc.targetModel)}`;
|
|
11528
11861
|
return tagParts.length > 0 ? [
|
|
11529
11862
|
fieldName,
|
|
11530
11863
|
targetType,
|
|
@@ -11604,9 +11937,8 @@ function alignFields(rows) {
|
|
|
11604
11937
|
}
|
|
11605
11938
|
function generateModelStruct(model, allModels, enums, indexes, provider) {
|
|
11606
11939
|
const idField = model.fields.find((f) => f.isId);
|
|
11607
|
-
const compositePkFieldNames = new Set(model
|
|
11940
|
+
const compositePkFieldNames = new Set(idField ? [] : primaryKeyFields$1(model));
|
|
11608
11941
|
const isCompositePk = !idField && compositePkFieldNames.size > 0;
|
|
11609
|
-
if (!(idField || isCompositePk)) return null;
|
|
11610
11942
|
const associations = getAssociations$2(model, allModels);
|
|
11611
11943
|
const compositeTagMap = collectCompositeIndexTags(model, indexes);
|
|
11612
11944
|
const tableName = model.dbName ?? model.name;
|
|
@@ -11615,7 +11947,7 @@ function generateModelStruct(model, allModels, enums, indexes, provider) {
|
|
|
11615
11947
|
const fieldIndexTags = compositeTagMap.get(field.name) ?? [];
|
|
11616
11948
|
return generateStructField(field, isPk, isCompositePk, fieldIndexTags, enums, provider);
|
|
11617
11949
|
});
|
|
11618
|
-
const relationLines = generateRelationFields(
|
|
11950
|
+
const relationLines = generateRelationFields(associations);
|
|
11619
11951
|
const tableNameMethod = [
|
|
11620
11952
|
"",
|
|
11621
11953
|
`func (${goModelName(model.name)}) TableName() string {`,
|
|
@@ -11935,7 +12267,7 @@ function formatImports(groups) {
|
|
|
11935
12267
|
// src/generator/gorm.ts
|
|
11936
12268
|
function generateGormModels(models, enums, indexes, packageName = "model", provider) {
|
|
11937
12269
|
const idx = indexes ?? [];
|
|
11938
|
-
const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider))
|
|
12270
|
+
const modelBodies = models.map((model) => generateModelStruct(model, models, enums, idx, provider));
|
|
11939
12271
|
return [
|
|
11940
12272
|
`package ${packageName}`,
|
|
11941
12273
|
...formatImports(collectImports(models)),
|
|
@@ -12833,6 +13165,87 @@ function rustFieldIdent(snake) {
|
|
|
12833
13165
|
derivedColumn: snake
|
|
12834
13166
|
};
|
|
12835
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
|
+
}
|
|
12836
13249
|
function resolveSeaOrmColumnType(field) {
|
|
12837
13250
|
if (!field.nativeType) return null;
|
|
12838
13251
|
const [nativeName, nativeArgs] = field.nativeType;
|
|
@@ -13029,7 +13442,7 @@ function generateEnum(e, serde = {}) {
|
|
|
13029
13442
|
"}"
|
|
13030
13443
|
].join("\n");
|
|
13031
13444
|
}
|
|
13032
|
-
function generateRelationEnum(
|
|
13445
|
+
function generateRelationEnum(model, associations, allModels) {
|
|
13033
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");
|
|
13034
13447
|
const variants = [];
|
|
13035
13448
|
const targetCount = /* @__PURE__ */ new Map();
|
|
@@ -13041,9 +13454,11 @@ function generateRelationEnum(_model, associations) {
|
|
|
13041
13454
|
const isAmbiguous = (targetModel) => (targetCount.get(targetModel) ?? 0) > 1;
|
|
13042
13455
|
for (const assoc of associations.belongsTo) {
|
|
13043
13456
|
const variantName = makePascalCase(assoc.name);
|
|
13044
|
-
const targetModule =
|
|
13045
|
-
const
|
|
13046
|
-
const
|
|
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);
|
|
13047
13462
|
const actions = [assoc.onUpdate ? `on_update = "${assoc.onUpdate}"` : null, assoc.onDelete ? `on_delete = "${assoc.onDelete}"` : null].filter((l) => l !== null);
|
|
13048
13463
|
const attribute = seaOrmAttribute(" ", [
|
|
13049
13464
|
`belongs_to = "super::${targetModule}::Entity"`,
|
|
@@ -13055,14 +13470,14 @@ function generateRelationEnum(_model, associations) {
|
|
|
13055
13470
|
}
|
|
13056
13471
|
for (const assoc of associations.hasMany) {
|
|
13057
13472
|
const variantName = makePascalCase(assoc.name);
|
|
13058
|
-
const targetModule =
|
|
13059
|
-
const attribute = seaOrmAttribute(" ", [`has_many = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${
|
|
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)}"`] : []]);
|
|
13060
13475
|
variants.push(`${attribute}\n ${variantName},`);
|
|
13061
13476
|
}
|
|
13062
13477
|
for (const assoc of associations.hasOne) {
|
|
13063
13478
|
const variantName = makePascalCase(assoc.name);
|
|
13064
|
-
const targetModule =
|
|
13065
|
-
const attribute = seaOrmAttribute(" ", [`has_one = "super::${targetModule}::Entity"`, ...isAmbiguous(assoc.targetModel) ? [`from = "Column::${
|
|
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)}"`] : []]);
|
|
13066
13481
|
variants.push(`${attribute}\n ${variantName},`);
|
|
13067
13482
|
}
|
|
13068
13483
|
return [
|
|
@@ -13078,11 +13493,10 @@ function generateRelatedImpls(model, associations) {
|
|
|
13078
13493
|
for (const assoc of associations.belongsTo) {
|
|
13079
13494
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
13080
13495
|
emittedTargets.add(assoc.targetModel);
|
|
13081
|
-
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
13082
13496
|
impls.push([
|
|
13083
|
-
relatedImplHeader(
|
|
13497
|
+
relatedImplHeader(rustModule(assoc.targetModel).ident),
|
|
13084
13498
|
" fn to() -> RelationDef {",
|
|
13085
|
-
`
|
|
13499
|
+
relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
|
|
13086
13500
|
" }",
|
|
13087
13501
|
"}"
|
|
13088
13502
|
].join("\n"));
|
|
@@ -13090,11 +13504,10 @@ function generateRelatedImpls(model, associations) {
|
|
|
13090
13504
|
for (const assoc of associations.hasMany) {
|
|
13091
13505
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
13092
13506
|
emittedTargets.add(assoc.targetModel);
|
|
13093
|
-
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
13094
13507
|
impls.push([
|
|
13095
|
-
relatedImplHeader(
|
|
13508
|
+
relatedImplHeader(rustModule(assoc.targetModel).ident),
|
|
13096
13509
|
" fn to() -> RelationDef {",
|
|
13097
|
-
`
|
|
13510
|
+
relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
|
|
13098
13511
|
" }",
|
|
13099
13512
|
"}"
|
|
13100
13513
|
].join("\n"));
|
|
@@ -13102,18 +13515,17 @@ function generateRelatedImpls(model, associations) {
|
|
|
13102
13515
|
for (const assoc of associations.hasOne) {
|
|
13103
13516
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
13104
13517
|
emittedTargets.add(assoc.targetModel);
|
|
13105
|
-
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
13106
13518
|
impls.push([
|
|
13107
|
-
relatedImplHeader(
|
|
13519
|
+
relatedImplHeader(rustModule(assoc.targetModel).ident),
|
|
13108
13520
|
" fn to() -> RelationDef {",
|
|
13109
|
-
`
|
|
13521
|
+
relationChain(" ", `Relation::${makePascalCase(assoc.name)}`, [".def()"], ""),
|
|
13110
13522
|
" }",
|
|
13111
13523
|
"}"
|
|
13112
13524
|
].join("\n"));
|
|
13113
13525
|
}
|
|
13114
13526
|
for (const assoc of associations.manyToMany) {
|
|
13115
13527
|
if (assoc.targetModel === model.name) {
|
|
13116
|
-
const junctionModule =
|
|
13528
|
+
const junctionModule = rustModule(assoc.relationName).ident;
|
|
13117
13529
|
const [own, other] = assoc.isSideA ? ["A", "B"] : ["B", "A"];
|
|
13118
13530
|
impls.push([
|
|
13119
13531
|
`pub struct ${makePascalCase(assoc.name)}Link;`,
|
|
@@ -13124,8 +13536,8 @@ function generateRelatedImpls(model, associations) {
|
|
|
13124
13536
|
"",
|
|
13125
13537
|
" fn link(&self) -> Vec<RelationDef> {",
|
|
13126
13538
|
" vec![",
|
|
13127
|
-
`
|
|
13128
|
-
`
|
|
13539
|
+
relationChain(" ", `super::${junctionModule}::Relation::${own}`, [".def()", ".rev()"], ","),
|
|
13540
|
+
relationChain(" ", `super::${junctionModule}::Relation::${other}`, [".def()"], ","),
|
|
13129
13541
|
" ]",
|
|
13130
13542
|
" }",
|
|
13131
13543
|
"}"
|
|
@@ -13134,17 +13546,17 @@ function generateRelatedImpls(model, associations) {
|
|
|
13134
13546
|
}
|
|
13135
13547
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
13136
13548
|
emittedTargets.add(assoc.targetModel);
|
|
13137
|
-
const targetModule =
|
|
13138
|
-
const junctionModule =
|
|
13549
|
+
const targetModule = rustModule(assoc.targetModel).ident;
|
|
13550
|
+
const junctionModule = rustModule(assoc.relationName).ident;
|
|
13139
13551
|
const junctionRelToTarget = makePascalCase(assoc.targetModel);
|
|
13140
13552
|
const junctionRelToSelf = makePascalCase(model.name);
|
|
13141
13553
|
impls.push([
|
|
13142
13554
|
relatedImplHeader(targetModule),
|
|
13143
13555
|
" fn to() -> RelationDef {",
|
|
13144
|
-
`
|
|
13556
|
+
relationChain(" ", `super::${junctionModule}::Relation::${junctionRelToTarget}`, [".def()"], ""),
|
|
13145
13557
|
" }",
|
|
13146
13558
|
" fn via() -> Option<RelationDef> {",
|
|
13147
|
-
`
|
|
13559
|
+
viaBody(`super::${junctionModule}::Relation::${junctionRelToSelf}`),
|
|
13148
13560
|
" }",
|
|
13149
13561
|
"}"
|
|
13150
13562
|
].join("\n"));
|
|
@@ -13152,21 +13564,21 @@ function generateRelatedImpls(model, associations) {
|
|
|
13152
13564
|
return impls;
|
|
13153
13565
|
}
|
|
13154
13566
|
function generateEntityFile(model, allModels, enums, serde = {}, provider) {
|
|
13155
|
-
const
|
|
13156
|
-
const
|
|
13157
|
-
|
|
13158
|
-
if (!(idField || isCompositePk)) return "";
|
|
13567
|
+
const primaryKey = new Set(primaryKeyFields$1(model));
|
|
13568
|
+
const isCompositePk = primaryKey.size > 1;
|
|
13569
|
+
if (primaryKey.size === 0) return "";
|
|
13159
13570
|
const tableName = model.dbName ?? model.name;
|
|
13160
13571
|
const associations = getAssociations$1(model, allModels);
|
|
13161
13572
|
const enumNames = new Set(enums.map((e) => e.name));
|
|
13573
|
+
const fieldNames = seaOrmFieldNames(model);
|
|
13162
13574
|
const scalarFields = model.fields.filter((f) => f.kind !== "object");
|
|
13163
13575
|
const fieldLines = [];
|
|
13164
13576
|
const stampLines = [];
|
|
13165
13577
|
let stampsNow = false;
|
|
13166
13578
|
let stampsOnInsert = false;
|
|
13167
13579
|
for (const field of scalarFields) {
|
|
13168
|
-
const isPk =
|
|
13169
|
-
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));
|
|
13170
13582
|
const attrs = buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums);
|
|
13171
13583
|
const nativeOverride = rustTypeForNative(field, provider);
|
|
13172
13584
|
const elemType = enumNames.has(field.type) ? field.type : nativeOverride ?? prismaTypeToRustType(field.type, true);
|
|
@@ -13189,9 +13601,12 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
|
|
|
13189
13601
|
const assignment = ` self.${fieldName} = Set(${field.isRequired ? value : `Some(${value})`});`;
|
|
13190
13602
|
stampLines.push(...condition, assignment.length <= 100 || ` self.${fieldName} =`.length > 99 ? assignment : ` self.${fieldName} =\n ${assignment.trimStart().slice(`self.${fieldName} = `.length)}`, " }");
|
|
13191
13603
|
}
|
|
13192
|
-
const relationEnum = generateRelationEnum(model, associations);
|
|
13604
|
+
const relationEnum = generateRelationEnum(model, associations, allModels);
|
|
13193
13605
|
const relatedImpls = generateRelatedImpls(model, associations);
|
|
13194
|
-
const superImports = [...new Set(scalarFields.flatMap((f) => enumNames.has(f.type) ? [f.type] : f.type === "DateTime" && provider === "sqlite" ? ["PrismaDateTime"] : []))].map((name) =>
|
|
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};`);
|
|
13195
13610
|
const generatedIdFields = scalarFields.filter((f) => f.type === "String" && !f.isList && generatedIdExpr(f) !== null);
|
|
13196
13611
|
const useLines = [
|
|
13197
13612
|
...superImports,
|
|
@@ -13204,7 +13619,7 @@ function generateEntityFile(model, allModels, enums, serde = {}, provider) {
|
|
|
13204
13619
|
" fn new() -> Self {",
|
|
13205
13620
|
" Self {",
|
|
13206
13621
|
...generatedIdFields.map((field) => {
|
|
13207
|
-
const { ident } = rustFieldIdent(makeSnakeCase(field.name));
|
|
13622
|
+
const { ident } = fieldNames.get(field.name) ?? rustFieldIdent(makeSnakeCase(field.name));
|
|
13208
13623
|
const generate = generatedIdExpr(field) ?? "";
|
|
13209
13624
|
const value = field.isRequired ? generate : `Some(${generate})`;
|
|
13210
13625
|
const n = ident.length;
|
|
@@ -13265,8 +13680,8 @@ function pkRustType(modelName, models) {
|
|
|
13265
13680
|
function generateM2MEntity(leftModel, rightModel, relationName, allModels, serde = {}) {
|
|
13266
13681
|
const [sortedLeft, sortedRight] = leftModel < rightModel ? [leftModel, rightModel] : [rightModel, leftModel];
|
|
13267
13682
|
const tableName = `_${relationName}`;
|
|
13268
|
-
const leftModule =
|
|
13269
|
-
const rightModule =
|
|
13683
|
+
const leftModule = rustModule(sortedLeft).ident;
|
|
13684
|
+
const rightModule = rustModule(sortedRight).ident;
|
|
13270
13685
|
const isSelf = sortedLeft === sortedRight;
|
|
13271
13686
|
const leftFk = isSelf ? "a" : `${makeSnakeCase(sortedLeft)}_id`;
|
|
13272
13687
|
const rightFk = isSelf ? "b" : `${makeSnakeCase(sortedRight)}_id`;
|
|
@@ -13399,7 +13814,10 @@ function generateModRs(moduleNames) {
|
|
|
13399
13814
|
return `${moduleNames.map((m) => `pub mod ${m};`).join("\n")}\n`;
|
|
13400
13815
|
}
|
|
13401
13816
|
function generatePreludeRs(models) {
|
|
13402
|
-
return `${models.map((m) =>
|
|
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`;
|
|
13403
13821
|
}
|
|
13404
13822
|
function collectM2MPairs(models) {
|
|
13405
13823
|
const pairs = models.flatMap((model) => getAssociations$1(model, models).manyToMany.map((assoc) => {
|
|
@@ -13422,8 +13840,8 @@ function collectM2MPairs(models) {
|
|
|
13422
13840
|
function seaOrmFiles(models, enums, serde = {}, provider) {
|
|
13423
13841
|
const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
|
|
13424
13842
|
const enumFiles = enums.map((e) => ({
|
|
13425
|
-
fileName:
|
|
13426
|
-
moduleName:
|
|
13843
|
+
fileName: rustModule(e.name).file,
|
|
13844
|
+
moduleName: rustModule(e.name).ident,
|
|
13427
13845
|
code: [
|
|
13428
13846
|
...useLines,
|
|
13429
13847
|
"",
|
|
@@ -13431,23 +13849,26 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
|
|
|
13431
13849
|
""
|
|
13432
13850
|
].join("\n")
|
|
13433
13851
|
}));
|
|
13434
|
-
const
|
|
13435
|
-
|
|
13436
|
-
|
|
13852
|
+
const entities = models.map((model) => ({
|
|
13853
|
+
model,
|
|
13854
|
+
fileName: rustModule(model.name).file,
|
|
13855
|
+
moduleName: rustModule(model.name).ident,
|
|
13437
13856
|
code: generateEntityFile(model, models, enums, serde, provider)
|
|
13438
13857
|
})).filter((entry) => entry.code.trim().length > 0);
|
|
13439
|
-
const
|
|
13440
|
-
|
|
13441
|
-
|
|
13442
|
-
|
|
13443
|
-
|
|
13444
|
-
|
|
13445
|
-
|
|
13446
|
-
|
|
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
|
+
}));
|
|
13447
13868
|
const preludeEntry = {
|
|
13448
13869
|
fileName: "prelude.rs",
|
|
13449
13870
|
moduleName: "prelude",
|
|
13450
|
-
code: generatePreludeRs(
|
|
13871
|
+
code: generatePreludeRs(entities.map(({ model }) => model))
|
|
13451
13872
|
};
|
|
13452
13873
|
const prismaDateTimeFiles = provider === "sqlite" && models.some((m) => m.fields.some((f) => f.type === "DateTime")) ? [{
|
|
13453
13874
|
fileName: "prisma_date_time.rs",
|
|
@@ -13463,7 +13884,10 @@ function seaOrmFiles(models, enums, serde = {}, provider) {
|
|
|
13463
13884
|
];
|
|
13464
13885
|
const modEntry = {
|
|
13465
13886
|
fileName: "mod.rs",
|
|
13466
|
-
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
|
+
}))
|
|
13467
13891
|
};
|
|
13468
13892
|
return [...allEntries.map(({ fileName, code }) => ({
|
|
13469
13893
|
fileName,
|
|
@@ -13576,8 +14000,87 @@ const DECLARATIVE_RESERVED = /* @__PURE__ */ new Set([
|
|
|
13576
14000
|
"metadata",
|
|
13577
14001
|
"registry"
|
|
13578
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
|
+
]);
|
|
13579
14063
|
function pythonAttrName(columnName) {
|
|
13580
|
-
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)));
|
|
13581
14084
|
}
|
|
13582
14085
|
function plainType(type, provider) {
|
|
13583
14086
|
switch (type) {
|
|
@@ -13749,12 +14252,14 @@ function getAssociations(model, allModels) {
|
|
|
13749
14252
|
continue;
|
|
13750
14253
|
}
|
|
13751
14254
|
const fkField = end.inverse;
|
|
13752
|
-
const
|
|
14255
|
+
const foreignKeys = fkField.relationFromFields ?? [];
|
|
14256
|
+
const foreignKey = foreignKeys[0] ?? "";
|
|
13753
14257
|
const { onDelete } = referentialActions(fkField);
|
|
13754
14258
|
if (end.kind === "hasMany") hasMany.push({
|
|
13755
14259
|
name: field.name,
|
|
13756
14260
|
targetModel: field.type,
|
|
13757
14261
|
foreignKey,
|
|
14262
|
+
foreignKeys,
|
|
13758
14263
|
isList: true,
|
|
13759
14264
|
onDelete
|
|
13760
14265
|
});
|
|
@@ -13762,6 +14267,7 @@ function getAssociations(model, allModels) {
|
|
|
13762
14267
|
name: field.name,
|
|
13763
14268
|
targetModel: field.type,
|
|
13764
14269
|
foreignKey,
|
|
14270
|
+
foreignKeys,
|
|
13765
14271
|
isList: false,
|
|
13766
14272
|
optional: !field.isRequired,
|
|
13767
14273
|
onDelete
|
|
@@ -13925,11 +14431,10 @@ function usesUtcDateTime(models) {
|
|
|
13925
14431
|
"DateTime"
|
|
13926
14432
|
].includes(f.nativeType?.[0] ?? "")));
|
|
13927
14433
|
}
|
|
13928
|
-
function needsForeignKeysParam(
|
|
13929
|
-
|
|
13930
|
-
|
|
13931
|
-
|
|
13932
|
-
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;
|
|
13933
14438
|
}
|
|
13934
14439
|
function findBackPopulates(targetModelName, sourceModelName, foreignKey, allModels, sourceFieldName) {
|
|
13935
14440
|
const targetModel = allModels.find((m) => m.name === targetModelName);
|
|
@@ -13944,15 +14449,17 @@ function findBackPopulates(targetModelName, sourceModelName, foreignKey, allMode
|
|
|
13944
14449
|
if (f.relationFromFields?.includes(foreignKey)) return true;
|
|
13945
14450
|
return sourceModel ? sourceModel.fields.some((sf) => sf.relationName === f.relationName && sf.relationFromFields?.includes(foreignKey)) : false;
|
|
13946
14451
|
});
|
|
13947
|
-
return
|
|
14452
|
+
return backField ? attributeName(targetModel, backField.name) : pythonAttrName(makeSnakeCase(sourceModelName));
|
|
13948
14453
|
}
|
|
13949
14454
|
function findM2MBackPopulates(targetModelName, sourceModelName, sourceFieldName, relationName, allModels) {
|
|
13950
|
-
const
|
|
13951
|
-
|
|
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));
|
|
13952
14458
|
}
|
|
13953
|
-
function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider,
|
|
14459
|
+
function generateColumn(field, isPk, isFk, associations, allModels, enumMap, provider, model, isMapperKey) {
|
|
14460
|
+
const tableName = model.dbName ?? model.name;
|
|
13954
14461
|
const columnName = field.dbName ?? field.name;
|
|
13955
|
-
const attrName =
|
|
14462
|
+
const attrName = attributeName(model, field.name);
|
|
13956
14463
|
const elemPythonType = field.kind === "enum" ? "str" : pythonTypeForNative(field);
|
|
13957
14464
|
const pythonType = field.isList ? `list[${elemPythonType}]` : elemPythonType;
|
|
13958
14465
|
const typeHint = field.isList || field.isRequired ? pythonType : `Optional[${pythonType}]`;
|
|
@@ -14007,12 +14514,12 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap, pro
|
|
|
14007
14514
|
if (!hasNowDefault) colArgs.push(`default=${utcNow}`);
|
|
14008
14515
|
colArgs.push(`onupdate=${utcNow}`);
|
|
14009
14516
|
}
|
|
14010
|
-
if (colArgs.length === 0) return ` ${attrName}: Mapped[${typeHint}]`;
|
|
14517
|
+
if (colArgs.length === 0 && !isMapperKey) return ` ${attrName}: Mapped[${typeHint}]`;
|
|
14011
14518
|
return ` ${attrName}: Mapped[${typeHint}] = mapped_column(${colArgs.join(", ")})`;
|
|
14012
14519
|
}
|
|
14013
14520
|
function generateTableArgs(model, allModels, indexes, provider) {
|
|
14014
14521
|
const tableName = model.dbName ?? model.name;
|
|
14015
|
-
const indexConstraints =
|
|
14522
|
+
const indexConstraints = modelIndexes(model, indexes).map((idx) => {
|
|
14016
14523
|
const columns = idx.fields.map((f) => fieldColumn(model, f.name));
|
|
14017
14524
|
const unique = idx.type === "unique";
|
|
14018
14525
|
const name = idx.dbName ?? constraintName(tableName, columns, unique ? "key" : "idx", provider);
|
|
@@ -14053,63 +14560,69 @@ function deleteClause(onDelete) {
|
|
|
14053
14560
|
}
|
|
14054
14561
|
function generateBelongsToRelationships(associations, model, allModels) {
|
|
14055
14562
|
return associations.belongsTo.map((assoc) => {
|
|
14056
|
-
const snakeName =
|
|
14057
|
-
const snakeFk = pythonAttrName(makeSnakeCase(assoc.foreignKey));
|
|
14563
|
+
const snakeName = attributeName(model, assoc.name);
|
|
14058
14564
|
const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
|
|
14059
|
-
const fkClause = needsForeignKeysParam(assoc.targetModel,
|
|
14060
|
-
const
|
|
14061
|
-
const remoteClause = assoc.targetModel === model.name &&
|
|
14062
|
-
|
|
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}")`;
|
|
14063
14570
|
});
|
|
14064
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
|
+
}
|
|
14065
14577
|
function generateHasManyRelationships(associations, model, allModels) {
|
|
14066
14578
|
return associations.hasMany.map((assoc) => {
|
|
14067
|
-
const snakeName =
|
|
14579
|
+
const snakeName = attributeName(model, assoc.name);
|
|
14068
14580
|
const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
|
|
14069
|
-
const
|
|
14070
|
-
|
|
14071
|
-
const targetFkSnake = pythonAttrName(makeSnakeCase(assoc.foreignKey));
|
|
14072
|
-
const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
|
|
14073
|
-
return ` ${snakeName}: Mapped[list["${makePascalCase(assoc.targetModel)}"]] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
|
|
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}")`;
|
|
14074
14583
|
});
|
|
14075
14584
|
}
|
|
14076
14585
|
function generateHasOneRelationships(associations, model, allModels) {
|
|
14077
14586
|
return associations.hasOne.map((assoc) => {
|
|
14078
|
-
const snakeName =
|
|
14587
|
+
const snakeName = attributeName(model, assoc.name);
|
|
14079
14588
|
const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
|
|
14080
|
-
const
|
|
14081
|
-
const
|
|
14082
|
-
|
|
14083
|
-
const fkClause = needsFkParam ? `foreign_keys="${makePascalCase(assoc.targetModel)}.${targetFkSnake}", ` : "";
|
|
14084
|
-
return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${fkClause}${deleteClause(assoc.onDelete)}back_populates="${backPop}")`;
|
|
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}")`;
|
|
14085
14592
|
});
|
|
14086
14593
|
}
|
|
14087
14594
|
function generateManyToManyRelationships(associations, model, allModels, m2mTables) {
|
|
14088
14595
|
return associations.manyToMany.map((assoc) => {
|
|
14089
|
-
const snakeName =
|
|
14596
|
+
const snakeName = attributeName(model, assoc.name);
|
|
14090
14597
|
const backPop = findM2MBackPopulates(assoc.targetModel, model.name, assoc.name, assoc.relationName, allModels);
|
|
14091
14598
|
const secondaryVar = m2mTables.find((t) => t.relationName === assoc.relationName)?.varName ?? makeSnakeCase(assoc.relationName);
|
|
14092
14599
|
const pkField = model.fields.find((f) => f.isId);
|
|
14093
14600
|
const other = model.fields.find((f) => f.kind === "object" && f.relationName === assoc.relationName && f.name !== assoc.name);
|
|
14094
14601
|
const [own, far] = other && other.name < assoc.name ? ["B", "A"] : ["A", "B"];
|
|
14095
|
-
const pk = `${
|
|
14602
|
+
const pk = `${className(model.name)}.${attributeName(model, pkField?.name ?? "id")}`;
|
|
14096
14603
|
const joinClause = assoc.targetModel === model.name && other ? `primaryjoin=lambda: ${pk} == ${secondaryVar}.c.${own}, secondaryjoin=lambda: ${pk} == ${secondaryVar}.c.${far}, ` : "";
|
|
14097
|
-
return ` ${snakeName}: Mapped[list["${
|
|
14604
|
+
return ` ${snakeName}: Mapped[list["${className(assoc.targetModel)}"]] = relationship(secondary=${secondaryVar}, ${joinClause}back_populates="${backPop}")`;
|
|
14098
14605
|
});
|
|
14099
14606
|
}
|
|
14100
14607
|
function generateModelBody(model, allModels, enums, indexes, m2mTables, provider) {
|
|
14101
14608
|
const idField = model.fields.find((f) => f.isId);
|
|
14102
14609
|
const compositePkFieldNames = new Set(model.primaryKey?.fields);
|
|
14103
|
-
const
|
|
14104
|
-
if (
|
|
14610
|
+
const identity = primaryKeyFields$1(model);
|
|
14611
|
+
if (identity.length === 0) return null;
|
|
14105
14612
|
const associations = getAssociations(model, allModels);
|
|
14106
14613
|
const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
|
|
14107
14614
|
const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
|
|
14108
14615
|
const tableName = model.dbName ?? model.name;
|
|
14109
|
-
const
|
|
14110
|
-
|
|
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);
|
|
14111
14623
|
});
|
|
14112
14624
|
const tableArgsLines = generateTableArgs(model, allModels, indexes, provider);
|
|
14625
|
+
const mapperArgsLines = isKeyless ? ["", ` __mapper_args__ = {"primary_key": [${identity.map((name) => attributeName(model, name)).join(", ")}]}`] : [];
|
|
14113
14626
|
const relationLines = [
|
|
14114
14627
|
...generateBelongsToRelationships(associations, model, allModels),
|
|
14115
14628
|
...generateHasManyRelationships(associations, model, allModels),
|
|
@@ -14118,11 +14631,12 @@ function generateModelBody(model, allModels, enums, indexes, m2mTables, provider
|
|
|
14118
14631
|
];
|
|
14119
14632
|
const hasRelations = relationLines.length > 0;
|
|
14120
14633
|
return [
|
|
14121
|
-
`class ${
|
|
14634
|
+
`class ${className(model.name)}(Base):`,
|
|
14122
14635
|
` __tablename__ = "${tableName}"`,
|
|
14123
14636
|
"",
|
|
14124
14637
|
...columnLines,
|
|
14125
14638
|
...tableArgsLines,
|
|
14639
|
+
...mapperArgsLines,
|
|
14126
14640
|
...hasRelations ? [""] : [],
|
|
14127
14641
|
...relationLines
|
|
14128
14642
|
].join("\n");
|
|
@@ -14169,7 +14683,7 @@ function collectGlobalImports(models, _enums, indexes, m2mTables, provider) {
|
|
|
14169
14683
|
}
|
|
14170
14684
|
if (getAssociations(model, models).belongsTo.length > 0) saImports.add("ForeignKey");
|
|
14171
14685
|
if (model.fields.some((f) => f.kind === "object" && (f.relationFromFields?.length ?? 0) > 1)) saImports.add("ForeignKeyConstraint");
|
|
14172
|
-
if (
|
|
14686
|
+
if (modelIndexes(model, indexes).length > 0) saImports.add("Index");
|
|
14173
14687
|
}
|
|
14174
14688
|
if (m2mTables.length > 0) {
|
|
14175
14689
|
saImports.add("Column");
|