hekireki 0.9.3 → 0.10.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 +185 -58
- package/dist/bin/activerecord.d.ts +1 -0
- package/dist/bin/activerecord.js +6 -0
- package/dist/bin/ajv.js +1 -1
- package/dist/bin/arktype.js +1 -1
- package/dist/bin/dbml.js +1 -1
- package/dist/bin/docs.js +1 -1
- package/dist/bin/drizzle.js +1 -1
- package/dist/bin/ecto.js +1 -1
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.d.ts +1 -0
- package/dist/bin/eloquent.js +6 -0
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/mermaid-er.js +1 -1
- package/dist/bin/sea-orm.js +1 -1
- package/dist/bin/sqlalchemy.js +1 -1
- package/dist/bin/typebox.js +1 -1
- package/dist/bin/valibot.js +1 -1
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-BQVq3vuc.js → bin-jiigoOO9.js} +610 -95
- package/package.json +11 -1
|
@@ -7,6 +7,7 @@ import { Resvg } from "@resvg/resvg-js";
|
|
|
7
7
|
import { run } from "@softwaretechnik/dbml-renderer";
|
|
8
8
|
import { Style, css } from "hono/css";
|
|
9
9
|
import { raw } from "hono/html";
|
|
10
|
+
import { HtmlEscapedCallbackPhase, resolveCallback } from "hono/utils/html";
|
|
10
11
|
import { Fragment, jsx, jsxs } from "hono/jsx/jsx-runtime";
|
|
11
12
|
//#region src/format/index.ts
|
|
12
13
|
async function fmt(input) {
|
|
@@ -210,17 +211,6 @@ function makeCommentBlock(lines, indent) {
|
|
|
210
211
|
const prefix = " ".repeat(indent);
|
|
211
212
|
return `${prefix}/**\n${lines.map((c) => `${prefix} * ${c}`).join("\n")}\n${prefix} */\n`;
|
|
212
213
|
}
|
|
213
|
-
function makePropertiesGenerator(libraryPrefix, wrapCardinality) {
|
|
214
|
-
return function makeProperties(modelFields, includeComments) {
|
|
215
|
-
return modelFields.filter((field) => field.validation).map((field) => {
|
|
216
|
-
const cleanLines = field.comment.filter((line) => !(line.includes("@relation") || line.includes("@z") || line.includes("@v") || line.includes("@a") || line.includes("@e") || line.includes("@t") || line.includes("@j")));
|
|
217
|
-
const docComment = includeComments ? makeCommentBlock(cleanLines, 2) : "";
|
|
218
|
-
const base = `${libraryPrefix}.${field.validation}`;
|
|
219
|
-
const wrapped = wrapCardinality ? wrapCardinality(base, field.isRequired) : base;
|
|
220
|
-
return `${docComment} ${field.fieldName}: ${wrapped}`;
|
|
221
|
-
}).join(",\n");
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
214
|
function groupByModel(validFields) {
|
|
225
215
|
const raw = Object.groupBy(validFields, (f) => f.modelName);
|
|
226
216
|
return Object.fromEntries(Object.entries(raw).filter((entry) => entry[1] != null));
|
|
@@ -233,7 +223,146 @@ function schemaFromFields(modelFields, comment, schemaBuilder, propertiesGenerat
|
|
|
233
223
|
return schemaBuilder(modelName, propertiesGenerator(modelFields, comment), objectType);
|
|
234
224
|
}
|
|
235
225
|
//#endregion
|
|
226
|
+
//#region src/helper/activerecord.ts
|
|
227
|
+
function fieldColumn$1(model, fieldName) {
|
|
228
|
+
return model.fields.find((f) => f.name === fieldName)?.dbName ?? fieldName;
|
|
229
|
+
}
|
|
230
|
+
function getAssociations$5(model, allModels) {
|
|
231
|
+
const belongsTo = [];
|
|
232
|
+
const hasMany = [];
|
|
233
|
+
const hasOne = [];
|
|
234
|
+
const habtm = [];
|
|
235
|
+
for (const field of model.fields) {
|
|
236
|
+
if (field.kind !== "object") continue;
|
|
237
|
+
if (field.relationFromFields && field.relationFromFields.length > 0) {
|
|
238
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
239
|
+
const referencedField = field.relationToFields?.[0] ?? "id";
|
|
240
|
+
belongsTo.push({
|
|
241
|
+
name: field.name,
|
|
242
|
+
targetModel: field.type,
|
|
243
|
+
foreignKeyColumn: fieldColumn$1(model, field.relationFromFields[0]),
|
|
244
|
+
primaryKeyColumn: targetModel ? fieldColumn$1(targetModel, referencedField) : referencedField,
|
|
245
|
+
optional: !field.isRequired
|
|
246
|
+
});
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
250
|
+
if (!targetModel) continue;
|
|
251
|
+
if (field.isList) {
|
|
252
|
+
if (targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object")?.isList) {
|
|
253
|
+
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
254
|
+
habtm.push({
|
|
255
|
+
name: field.name,
|
|
256
|
+
targetModel: field.type,
|
|
257
|
+
joinTable: `_${field.relationName ?? `${left}To${right}`}`,
|
|
258
|
+
foreignKey: model.name === left ? "A" : "B",
|
|
259
|
+
associationForeignKey: model.name === left ? "B" : "A"
|
|
260
|
+
});
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const foreignKey = targetModel.fields.find((f) => f.relationName === field.relationName && f.relationFromFields && f.relationFromFields.length > 0)?.relationFromFields?.[0];
|
|
265
|
+
if (!foreignKey) continue;
|
|
266
|
+
const foreignKeyColumn = fieldColumn$1(targetModel, foreignKey);
|
|
267
|
+
if (field.isList) hasMany.push({
|
|
268
|
+
name: field.name,
|
|
269
|
+
targetModel: field.type,
|
|
270
|
+
foreignKeyColumn
|
|
271
|
+
});
|
|
272
|
+
else hasOne.push({
|
|
273
|
+
name: field.name,
|
|
274
|
+
targetModel: field.type,
|
|
275
|
+
foreignKeyColumn
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
belongsTo,
|
|
280
|
+
hasMany,
|
|
281
|
+
hasOne,
|
|
282
|
+
habtm
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function activeRecordModels(models, allModels, enums) {
|
|
286
|
+
const contextModels = allModels ?? models;
|
|
287
|
+
const enumMap = new Map((enums ?? []).map((e) => [e.name, e.values]));
|
|
288
|
+
return models.map((model) => {
|
|
289
|
+
const associations = getAssociations$5(model, contextModels);
|
|
290
|
+
const tableName = model.dbName ?? makeSnakeCase(model.name);
|
|
291
|
+
const idField = model.fields.find((f) => f.isId);
|
|
292
|
+
const compositePkColumns = (model.primaryKey?.fields ?? []).map((name) => fieldColumn$1(model, name));
|
|
293
|
+
const primaryKeyLines = idField ? (idField.dbName ?? idField.name) !== "id" ? [` self.primary_key = "${idField.dbName ?? idField.name}"`] : [] : compositePkColumns.length > 0 ? [` self.primary_key = [${compositePkColumns.map((c) => `"${c}"`).join(", ")}]`] : [];
|
|
294
|
+
const inheritanceColumnLines = model.fields.some((f) => (f.kind === "scalar" || f.kind === "enum") && (f.dbName ?? f.name) === "type") ? [" self.inheritance_column = nil"] : [];
|
|
295
|
+
const attributeLines = model.fields.filter((f) => f.kind === "scalar" && f.type === "String").flatMap((f) => {
|
|
296
|
+
const def = f.default;
|
|
297
|
+
if (!(def && typeof def === "object" && "name" in def)) return [];
|
|
298
|
+
const generator = def.name === "uuid" ? "args" in def && def.args[0] === 7 ? "SecureRandom.uuid_v7" : "SecureRandom.uuid" : def.name === "ulid" ? "ULID.generate" : null;
|
|
299
|
+
if (generator === null) return [];
|
|
300
|
+
return [` attribute :${f.dbName ?? f.name}, default: -> { ${generator} }`];
|
|
301
|
+
});
|
|
302
|
+
const enumLines = model.fields.filter((f) => f.kind === "enum").map((f) => {
|
|
303
|
+
const pairs = (enumMap.get(f.type) ?? []).map((v) => `${v.name}: "${v.dbName ?? v.name}"`).join(", ");
|
|
304
|
+
return ` enum :${f.dbName ?? f.name}, { ${pairs} }`;
|
|
305
|
+
});
|
|
306
|
+
const belongsToLines = associations.belongsTo.map((a) => {
|
|
307
|
+
const primaryKeyOpt = a.primaryKeyColumn === "id" ? "" : `, primary_key: "${a.primaryKeyColumn}"`;
|
|
308
|
+
const optionalOpt = a.optional ? ", optional: true" : "";
|
|
309
|
+
return ` belongs_to :${makeSnakeCase(a.name)}, class_name: "${a.targetModel}", foreign_key: "${a.foreignKeyColumn}"${primaryKeyOpt}${optionalOpt}`;
|
|
310
|
+
});
|
|
311
|
+
const hasOneLines = associations.hasOne.map((a) => ` has_one :${makeSnakeCase(a.name)}, class_name: "${a.targetModel}", foreign_key: "${a.foreignKeyColumn}"`);
|
|
312
|
+
const hasManyLines = associations.hasMany.map((a) => ` has_many :${makeSnakeCase(a.name)}, class_name: "${a.targetModel}", foreign_key: "${a.foreignKeyColumn}"`);
|
|
313
|
+
const habtmLines = associations.habtm.map((a) => ` has_and_belongs_to_many :${makeSnakeCase(a.name)}, class_name: "${a.targetModel}", join_table: "${a.joinTable}", foreign_key: "${a.foreignKey}", association_foreign_key: "${a.associationForeignKey}"`);
|
|
314
|
+
const associationLines = [
|
|
315
|
+
...belongsToLines,
|
|
316
|
+
...hasOneLines,
|
|
317
|
+
...hasManyLines,
|
|
318
|
+
...habtmLines
|
|
319
|
+
];
|
|
320
|
+
const doc = stripAnnotations(model.documentation);
|
|
321
|
+
return [
|
|
322
|
+
...doc ? doc.split("\n").map((line) => `# ${line}`) : [],
|
|
323
|
+
`class ${model.name} < ApplicationRecord`,
|
|
324
|
+
` self.table_name = "${tableName}"`,
|
|
325
|
+
...primaryKeyLines,
|
|
326
|
+
...inheritanceColumnLines,
|
|
327
|
+
...attributeLines.length > 0 ? ["", ...attributeLines] : [],
|
|
328
|
+
...enumLines.length > 0 ? ["", ...enumLines] : [],
|
|
329
|
+
...associationLines.length > 0 ? ["", ...associationLines] : [],
|
|
330
|
+
"end"
|
|
331
|
+
].join("\n");
|
|
332
|
+
}).filter(Boolean).join("\n\n");
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
335
|
+
//#region src/generator/activerecord.ts
|
|
336
|
+
function activeRecordModelFiles(models, enums) {
|
|
337
|
+
return models.map((model) => ({
|
|
338
|
+
fileName: `${makeSnakeCase(model.name)}.rb`,
|
|
339
|
+
code: activeRecordModels([model], models, enums)
|
|
340
|
+
})).filter((entry) => entry.code.trim().length > 0);
|
|
341
|
+
}
|
|
342
|
+
//#endregion
|
|
343
|
+
//#region src/core/activerecord.ts
|
|
344
|
+
async function activerecord(options) {
|
|
345
|
+
if (!(options.generator.isCustomOutput && options.generator.output?.value)) return {
|
|
346
|
+
ok: false,
|
|
347
|
+
error: "output is required for Hekireki-ActiveRecord. Please specify output in your generator config."
|
|
348
|
+
};
|
|
349
|
+
const outDir = options.generator.output.value;
|
|
350
|
+
const enums = options.dmmf.datamodel.enums;
|
|
351
|
+
return emitMany(activeRecordModelFiles(options.dmmf.datamodel.models, enums), outDir);
|
|
352
|
+
}
|
|
353
|
+
//#endregion
|
|
236
354
|
//#region src/helper/validation-schema.ts
|
|
355
|
+
function makePropertiesGenerator(libraryPrefix, wrapCardinality) {
|
|
356
|
+
return function makeProperties(modelFields, includeComments) {
|
|
357
|
+
return modelFields.filter((field) => field.validation).map((field) => {
|
|
358
|
+
const cleanLines = field.comment.filter((line) => !(line.includes("@relation") || line.includes("@z") || line.includes("@v") || line.includes("@a") || line.includes("@e") || line.includes("@t") || line.includes("@j")));
|
|
359
|
+
const docComment = includeComments ? makeCommentBlock(cleanLines, 2) : "";
|
|
360
|
+
const base = `${libraryPrefix}.${field.validation}`;
|
|
361
|
+
const wrapped = wrapCardinality ? wrapCardinality(base, field.isRequired) : base;
|
|
362
|
+
return `${docComment} ${field.fieldName}: ${wrapped}`;
|
|
363
|
+
}).join(",\n");
|
|
364
|
+
};
|
|
365
|
+
}
|
|
237
366
|
function validationSchemas(models, type, comment, config) {
|
|
238
367
|
const modelInfos = models.map((model) => ({
|
|
239
368
|
documentation: model.documentation ?? "",
|
|
@@ -1556,7 +1685,6 @@ const HekirekiLogo = () => /* @__PURE__ */ jsxs("svg", {
|
|
|
1556
1685
|
height: "40",
|
|
1557
1686
|
viewBox: "0 0 40 40",
|
|
1558
1687
|
fill: "currentColor",
|
|
1559
|
-
xmlns: "http://www.w3.org/2000/svg",
|
|
1560
1688
|
class: iconClass,
|
|
1561
1689
|
children: [/* @__PURE__ */ jsx("circle", {
|
|
1562
1690
|
cx: "20",
|
|
@@ -1640,7 +1768,7 @@ const generateHTML = async (data) => {
|
|
|
1640
1768
|
types: createTypes(data)
|
|
1641
1769
|
})]
|
|
1642
1770
|
}) });
|
|
1643
|
-
return `<!DOCTYPE html>${await Promise.resolve(element).then((node) => node.toString())}`;
|
|
1771
|
+
return `<!DOCTYPE html>${await resolveCallback(await Promise.resolve(element).then((node) => node.toString()), HtmlEscapedCallbackPhase.Stringify, false, {})}`;
|
|
1644
1772
|
};
|
|
1645
1773
|
//#endregion
|
|
1646
1774
|
//#region src/generator/docs.ts
|
|
@@ -1882,7 +2010,14 @@ function resolveDefaultValue(dflt, fieldType, provider) {
|
|
|
1882
2010
|
chain: ".defaultNow()",
|
|
1883
2011
|
imports: []
|
|
1884
2012
|
};
|
|
1885
|
-
case "uuid": return {
|
|
2013
|
+
case "uuid": return dflt.args[0] === 7 ? {
|
|
2014
|
+
chain: ".$defaultFn(() => uuidv7())",
|
|
2015
|
+
imports: [{
|
|
2016
|
+
pkg: "uuid",
|
|
2017
|
+
kind: "named",
|
|
2018
|
+
name: "v7 as uuidv7"
|
|
2019
|
+
}]
|
|
2020
|
+
} : {
|
|
1886
2021
|
chain: ".$defaultFn(() => crypto.randomUUID())",
|
|
1887
2022
|
imports: []
|
|
1888
2023
|
};
|
|
@@ -2072,12 +2207,13 @@ function drizzleSchema(datamodel, provider, indexes) {
|
|
|
2072
2207
|
const enumLines = makeEnumDeclarations(datamodel.models, datamodel.enums, db, imports);
|
|
2073
2208
|
const tableLines = datamodel.models.map((model) => makeTable(model, datamodel.models, db, imports, datamodel.enums, indexes));
|
|
2074
2209
|
const relationsLines = makeRelations(datamodel.models, imports);
|
|
2210
|
+
const enumLinesWithGap = enumLines.flatMap((line, i) => i < enumLines.length - 1 ? [line, ""] : [line]);
|
|
2075
2211
|
const tableLinesWithGap = tableLines.flatMap((line, i) => i < tableLines.length - 1 ? [line, ""] : [line]);
|
|
2076
2212
|
const relationsLinesWithGap = relationsLines.flatMap((line, i) => i < relationsLines.length - 1 ? [line, ""] : [line]);
|
|
2077
2213
|
return [
|
|
2078
2214
|
generateImports(imports, db),
|
|
2079
2215
|
"",
|
|
2080
|
-
...
|
|
2216
|
+
...enumLinesWithGap.length > 0 ? [...enumLinesWithGap, ""] : [],
|
|
2081
2217
|
...tableLinesWithGap,
|
|
2082
2218
|
...relationsLinesWithGap.length > 0 ? ["", ...relationsLinesWithGap] : []
|
|
2083
2219
|
].join("\n");
|
|
@@ -2132,6 +2268,7 @@ function ectoTypeToTypespec(type) {
|
|
|
2132
2268
|
case "float": return "float()";
|
|
2133
2269
|
case "boolean": return "boolean()";
|
|
2134
2270
|
case "binary_id": return "Ecto.UUID.t()";
|
|
2271
|
+
case "Ecto.ULID": return "Ecto.ULID.t()";
|
|
2135
2272
|
case "naive_datetime": return "NaiveDateTime.t()";
|
|
2136
2273
|
case "utc_datetime": return "DateTime.t()";
|
|
2137
2274
|
case "decimal": return "Decimal.t()";
|
|
@@ -2140,26 +2277,37 @@ function ectoTypeToTypespec(type) {
|
|
|
2140
2277
|
default: return "term()";
|
|
2141
2278
|
}
|
|
2142
2279
|
}
|
|
2280
|
+
function formatEctoType(type) {
|
|
2281
|
+
return /^[A-Z]/.test(type) ? type : `:${type}`;
|
|
2282
|
+
}
|
|
2143
2283
|
function getPrimaryKeyConfig(field) {
|
|
2144
2284
|
const def = field.default;
|
|
2145
2285
|
const isFunctionDefault = def && typeof def === "object" && "name" in def;
|
|
2286
|
+
const pkColumn = field.dbName ?? field.name;
|
|
2287
|
+
const sourceOpt = pkColumn === "id" ? "" : `, source: :${pkColumn}`;
|
|
2146
2288
|
if (field.type === "String" && isFunctionDefault && def.name === "uuid") return {
|
|
2147
|
-
line: "
|
|
2289
|
+
line: "args" in def && def.args[0] === 7 ? `@primary_key {:id, Ecto.UUID, autogenerate: [version: 7]${sourceOpt}}` : `@primary_key {:id, :binary_id, autogenerate: true${sourceOpt}}`,
|
|
2148
2290
|
typeSpec: "Ecto.UUID.t()",
|
|
2149
2291
|
omitIdFieldInSchema: true,
|
|
2150
|
-
|
|
2292
|
+
foreignKeyType: "binary_id"
|
|
2293
|
+
};
|
|
2294
|
+
if (field.type === "String" && isFunctionDefault && def.name === "ulid") return {
|
|
2295
|
+
line: `@primary_key {:id, Ecto.ULID, autogenerate: true${sourceOpt}}`,
|
|
2296
|
+
typeSpec: "Ecto.ULID.t()",
|
|
2297
|
+
omitIdFieldInSchema: true,
|
|
2298
|
+
foreignKeyType: "Ecto.ULID"
|
|
2151
2299
|
};
|
|
2152
2300
|
if (field.type === "Int" && isFunctionDefault && def.name === "autoincrement") return {
|
|
2153
|
-
line:
|
|
2301
|
+
line: `@primary_key {:id, :id, autogenerate: true${sourceOpt}}`,
|
|
2154
2302
|
typeSpec: "integer()",
|
|
2155
2303
|
omitIdFieldInSchema: true,
|
|
2156
|
-
|
|
2304
|
+
foreignKeyType: null
|
|
2157
2305
|
};
|
|
2158
2306
|
return {
|
|
2159
2307
|
line: "@primary_key false",
|
|
2160
2308
|
typeSpec: "String.t()",
|
|
2161
2309
|
omitIdFieldInSchema: false,
|
|
2162
|
-
|
|
2310
|
+
foreignKeyType: null
|
|
2163
2311
|
};
|
|
2164
2312
|
}
|
|
2165
2313
|
function makeTimestampsLine(fields) {
|
|
@@ -2187,11 +2335,11 @@ function makeTimestampsLine(fields) {
|
|
|
2187
2335
|
if (inserted) {
|
|
2188
2336
|
const source = inserted.dbName ?? inserted.name;
|
|
2189
2337
|
if (source !== "inserted_at") opts.push(`inserted_at_source: :${source}`);
|
|
2190
|
-
}
|
|
2338
|
+
} else opts.push("inserted_at: false");
|
|
2191
2339
|
if (updated) {
|
|
2192
2340
|
const source = updated.dbName ?? updated.name;
|
|
2193
2341
|
if (source !== "updated_at") opts.push(`updated_at_source: :${source}`);
|
|
2194
|
-
}
|
|
2342
|
+
} else opts.push("updated_at: false");
|
|
2195
2343
|
return {
|
|
2196
2344
|
line: ` timestamps(${opts.join(", ")})`,
|
|
2197
2345
|
exclude
|
|
@@ -2203,14 +2351,14 @@ function getBelongsToFkType(allModels, targetModelName) {
|
|
|
2203
2351
|
const targetPk = targetModel.fields.find((f) => f.isId);
|
|
2204
2352
|
if (!targetPk) return null;
|
|
2205
2353
|
const pkConfig = getPrimaryKeyConfig(targetPk);
|
|
2206
|
-
if (pkConfig.
|
|
2354
|
+
if (pkConfig.foreignKeyType) return pkConfig.foreignKeyType;
|
|
2207
2355
|
if (pkConfig.line.includes(":id, autogenerate")) return null;
|
|
2208
2356
|
if (targetPk.type === "String") return "string";
|
|
2209
2357
|
const ectoType = prismaTypeToEctoType(targetPk.type);
|
|
2210
2358
|
if (ectoType === "integer") return null;
|
|
2211
2359
|
return ectoType;
|
|
2212
2360
|
}
|
|
2213
|
-
function getAssociations$
|
|
2361
|
+
function getAssociations$4(model, allModels) {
|
|
2214
2362
|
const belongsTo = [];
|
|
2215
2363
|
const hasMany = [];
|
|
2216
2364
|
const hasOne = [];
|
|
@@ -2232,10 +2380,16 @@ function getAssociations$3(model, allModels) {
|
|
|
2232
2380
|
if (field.isList) {
|
|
2233
2381
|
if (targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object")?.isList) {
|
|
2234
2382
|
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2383
|
+
const ownIdField = model.fields.find((f) => f.isId);
|
|
2384
|
+
const relatedIdField = targetModel.fields.find((f) => f.isId);
|
|
2235
2385
|
manyToMany.push({
|
|
2236
2386
|
name: field.name,
|
|
2237
2387
|
targetModel: field.type,
|
|
2238
|
-
joinThrough: `_${left}To${right}`
|
|
2388
|
+
joinThrough: `_${field.relationName ?? `${left}To${right}`}`,
|
|
2389
|
+
ownJoinColumn: model.name === left ? "A" : "B",
|
|
2390
|
+
ownKey: makeSnakeCase(ownIdField?.name ?? "id"),
|
|
2391
|
+
relatedJoinColumn: model.name === left ? "B" : "A",
|
|
2392
|
+
relatedKey: makeSnakeCase(relatedIdField?.name ?? "id")
|
|
2239
2393
|
});
|
|
2240
2394
|
continue;
|
|
2241
2395
|
}
|
|
@@ -2272,12 +2426,11 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2272
2426
|
line: "@primary_key false",
|
|
2273
2427
|
typeSpec: "",
|
|
2274
2428
|
omitIdFieldInSchema: false,
|
|
2275
|
-
|
|
2429
|
+
foreignKeyType: null
|
|
2276
2430
|
};
|
|
2277
|
-
const useBinaryId = pk.useBinaryForeignKey;
|
|
2278
2431
|
const fields = model.fields.map((f) => ({ ...f }));
|
|
2279
2432
|
const { line: timestampsLine, exclude: timestampsExclude } = makeTimestampsLine(fields);
|
|
2280
|
-
const associations = getAssociations$
|
|
2433
|
+
const associations = getAssociations$4(model, contextModels);
|
|
2281
2434
|
const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
|
|
2282
2435
|
const enumMap = /* @__PURE__ */ new Map();
|
|
2283
2436
|
if (enums) for (const e of enums) enumMap.set(e.name, e.values.map((v) => v.name));
|
|
@@ -2314,7 +2467,7 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2314
2467
|
const sourceOpt = snakeName !== dbColumnName ? `, source: :${dbColumnName}` : "";
|
|
2315
2468
|
if (f.kind === "enum") {
|
|
2316
2469
|
const values = enumMap.get(f.type);
|
|
2317
|
-
return ` field(:${snakeName}, Ecto.Enum, values: [${values ? values.map((v) => `:${v}`).join(", ") : ""}]${sourceOpt})`;
|
|
2470
|
+
return ` field(:${snakeName}, Ecto.Enum, values: [${values ? values.map((v) => `:${v}`).join(", ") : ""}]${typeof f.default === "string" ? `, default: :${f.default}` : ""}${sourceOpt})`;
|
|
2318
2471
|
}
|
|
2319
2472
|
const type = prismaTypeToEctoType(f.type);
|
|
2320
2473
|
const ectoType = f.isList ? `{:array, :${type}}` : `:${type}`;
|
|
@@ -2337,7 +2490,7 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2337
2490
|
const fkType = a.fkType ?? "id";
|
|
2338
2491
|
const pkOpt = isPkField ? ", primary_key: true" : "";
|
|
2339
2492
|
const sourceOpt = needsSource ? `, source: :${fkDbName}` : "";
|
|
2340
|
-
fkFieldLines.push(` field(:${snakeFk},
|
|
2493
|
+
fkFieldLines.push(` field(:${snakeFk}, ${formatEctoType(fkType)}${pkOpt}${sourceOpt})`);
|
|
2341
2494
|
}
|
|
2342
2495
|
}
|
|
2343
2496
|
const belongsToLines = associations.belongsTo.map((a) => {
|
|
@@ -2347,7 +2500,7 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2347
2500
|
const isPkField = compositePkFieldNames.has(a.foreignKey);
|
|
2348
2501
|
const opts = [`foreign_key: :${snakeFk}`];
|
|
2349
2502
|
if (needsSource || isPkField) opts.push("define_field: false");
|
|
2350
|
-
if (a.fkType &&
|
|
2503
|
+
if (a.fkType && a.fkType !== pk.foreignKeyType) opts.push(`type: ${formatEctoType(a.fkType)}`);
|
|
2351
2504
|
if (a.references !== "id") opts.push(`references: :${a.references}`);
|
|
2352
2505
|
return ` belongs_to(:${snakeAssocName}, ${appName}.${a.targetModel}, ${opts.join(", ")})`;
|
|
2353
2506
|
});
|
|
@@ -2360,7 +2513,9 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2360
2513
|
return ` has_many(:${makeSnakeCase(a.name)}, ${appName}.${a.targetModel}, foreign_key: :${snakeFk})`;
|
|
2361
2514
|
});
|
|
2362
2515
|
const manyToManyLines = associations.manyToMany.map((a) => {
|
|
2363
|
-
|
|
2516
|
+
const snakeAssocName = makeSnakeCase(a.name);
|
|
2517
|
+
const joinKeys = `join_keys: [${a.ownJoinColumn}: :${a.ownKey}, ${a.relatedJoinColumn}: :${a.relatedKey}]`;
|
|
2518
|
+
return ` many_to_many(:${snakeAssocName}, ${appName}.${a.targetModel}, join_through: "${a.joinThrough}", ${joinKeys})`;
|
|
2364
2519
|
});
|
|
2365
2520
|
return [
|
|
2366
2521
|
`defmodule ${appName}.${model.name} do`,
|
|
@@ -2372,7 +2527,7 @@ function ectoSchemas(models, app, allModels, enums) {
|
|
|
2372
2527
|
] : [" @moduledoc false"],
|
|
2373
2528
|
"",
|
|
2374
2529
|
` ${pk.line}`,
|
|
2375
|
-
...
|
|
2530
|
+
...pk.foreignKeyType ? [` @foreign_key_type ${formatEctoType(pk.foreignKeyType)}`] : [],
|
|
2376
2531
|
"",
|
|
2377
2532
|
...typeSpecLines,
|
|
2378
2533
|
"",
|
|
@@ -2482,6 +2637,253 @@ async function effect(options) {
|
|
|
2482
2637
|
return emit(effectCode(options.dmmf, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), getBool(options.generator.config?.relation)), resolved.dir, resolved.file);
|
|
2483
2638
|
}
|
|
2484
2639
|
//#endregion
|
|
2640
|
+
//#region src/helper/eloquent.ts
|
|
2641
|
+
function prismaTypeToEloquentCast(type) {
|
|
2642
|
+
if (type === "Int") return "integer";
|
|
2643
|
+
if (type === "BigInt") return "integer";
|
|
2644
|
+
if (type === "Float") return "float";
|
|
2645
|
+
if (type === "Boolean") return "boolean";
|
|
2646
|
+
if (type === "DateTime") return "datetime";
|
|
2647
|
+
if (type === "Json") return "array";
|
|
2648
|
+
return null;
|
|
2649
|
+
}
|
|
2650
|
+
function fieldColumn(model, fieldName) {
|
|
2651
|
+
return model.fields.find((f) => f.name === fieldName)?.dbName ?? fieldName;
|
|
2652
|
+
}
|
|
2653
|
+
function getAssociations$3(model, allModels) {
|
|
2654
|
+
const belongsTo = [];
|
|
2655
|
+
const hasMany = [];
|
|
2656
|
+
const hasOne = [];
|
|
2657
|
+
const belongsToMany = [];
|
|
2658
|
+
for (const field of model.fields) {
|
|
2659
|
+
if (field.kind !== "object") continue;
|
|
2660
|
+
if (field.relationFromFields && field.relationFromFields.length > 0) {
|
|
2661
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
2662
|
+
const referencedField = field.relationToFields?.[0] ?? "id";
|
|
2663
|
+
belongsTo.push({
|
|
2664
|
+
name: field.name,
|
|
2665
|
+
targetModel: field.type,
|
|
2666
|
+
foreignKeyColumn: fieldColumn(model, field.relationFromFields[0]),
|
|
2667
|
+
ownerKeyColumn: targetModel ? fieldColumn(targetModel, referencedField) : referencedField
|
|
2668
|
+
});
|
|
2669
|
+
continue;
|
|
2670
|
+
}
|
|
2671
|
+
const targetModel = allModels.find((m) => m.name === field.type);
|
|
2672
|
+
if (!targetModel) continue;
|
|
2673
|
+
if (field.isList) {
|
|
2674
|
+
if (targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object")?.isList) {
|
|
2675
|
+
const [left, right] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
2676
|
+
belongsToMany.push({
|
|
2677
|
+
name: field.name,
|
|
2678
|
+
targetModel: field.type,
|
|
2679
|
+
joinTable: `_${field.relationName ?? `${left}To${right}`}`,
|
|
2680
|
+
foreignPivotKey: model.name === left ? "A" : "B",
|
|
2681
|
+
relatedPivotKey: model.name === left ? "B" : "A"
|
|
2682
|
+
});
|
|
2683
|
+
continue;
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
const fkField = targetModel.fields.find((f) => f.relationName === field.relationName && f.relationFromFields && f.relationFromFields.length > 0);
|
|
2687
|
+
const foreignKey = fkField?.relationFromFields?.[0];
|
|
2688
|
+
if (!foreignKey) continue;
|
|
2689
|
+
const foreignKeyColumn = fieldColumn(targetModel, foreignKey);
|
|
2690
|
+
const localKeyColumn = fieldColumn(model, fkField?.relationToFields?.[0] ?? "id");
|
|
2691
|
+
if (field.isList) hasMany.push({
|
|
2692
|
+
name: field.name,
|
|
2693
|
+
targetModel: field.type,
|
|
2694
|
+
foreignKeyColumn,
|
|
2695
|
+
localKeyColumn
|
|
2696
|
+
});
|
|
2697
|
+
else hasOne.push({
|
|
2698
|
+
name: field.name,
|
|
2699
|
+
targetModel: field.type,
|
|
2700
|
+
foreignKeyColumn,
|
|
2701
|
+
localKeyColumn
|
|
2702
|
+
});
|
|
2703
|
+
}
|
|
2704
|
+
return {
|
|
2705
|
+
belongsTo,
|
|
2706
|
+
hasMany,
|
|
2707
|
+
hasOne,
|
|
2708
|
+
belongsToMany
|
|
2709
|
+
};
|
|
2710
|
+
}
|
|
2711
|
+
function findTimestamps(fields) {
|
|
2712
|
+
const createdAliases = ["created_at", "createdAt"];
|
|
2713
|
+
const updatedAliases = [
|
|
2714
|
+
"updated_at",
|
|
2715
|
+
"updatedAt",
|
|
2716
|
+
"modified_at",
|
|
2717
|
+
"modifiedAt"
|
|
2718
|
+
];
|
|
2719
|
+
const created = fields.find((f) => f.type === "DateTime" && createdAliases.includes(f.name));
|
|
2720
|
+
const updated = fields.find((f) => f.isUpdatedAt) ?? fields.find((f) => f.type === "DateTime" && updatedAliases.includes(f.name));
|
|
2721
|
+
const exclude = new Set([created?.name, updated?.name].filter((name) => name !== void 0));
|
|
2722
|
+
return {
|
|
2723
|
+
createdColumn: created ? created.dbName ?? created.name : null,
|
|
2724
|
+
updatedColumn: updated ? updated.dbName ?? updated.name : null,
|
|
2725
|
+
exclude
|
|
2726
|
+
};
|
|
2727
|
+
}
|
|
2728
|
+
function eloquentEnum(enumDef, namespace) {
|
|
2729
|
+
return [
|
|
2730
|
+
"<?php",
|
|
2731
|
+
"",
|
|
2732
|
+
`namespace ${namespace};`,
|
|
2733
|
+
"",
|
|
2734
|
+
`enum ${enumDef.name}: string`,
|
|
2735
|
+
"{",
|
|
2736
|
+
...enumDef.values.map((v) => ` case ${v.name} = '${v.dbName ?? v.name}';`),
|
|
2737
|
+
"}"
|
|
2738
|
+
].join("\n");
|
|
2739
|
+
}
|
|
2740
|
+
function eloquentModels(models, namespace, allModels, enums) {
|
|
2741
|
+
const contextModels = allModels ?? models;
|
|
2742
|
+
const enumNames = new Set((enums ?? []).map((e) => e.name));
|
|
2743
|
+
return models.map((model) => {
|
|
2744
|
+
const associations = getAssociations$3(model, contextModels);
|
|
2745
|
+
const tableName = model.dbName ?? makeSnakeCase(model.name);
|
|
2746
|
+
const idField = model.fields.find((f) => f.isId);
|
|
2747
|
+
const compositePkFields = model.primaryKey?.fields ?? [];
|
|
2748
|
+
const timestamps = findTimestamps(model.fields);
|
|
2749
|
+
const pkColumn = idField ? idField.dbName ?? idField.name : null;
|
|
2750
|
+
const pkUuidTrait = (() => {
|
|
2751
|
+
const def = idField?.default;
|
|
2752
|
+
if (!(def && typeof def === "object" && "name" in def)) return null;
|
|
2753
|
+
if (def.name === "ulid") return "HasUlids";
|
|
2754
|
+
if (def.name !== "uuid") return null;
|
|
2755
|
+
return "args" in def && def.args[0] === 7 ? "HasUuids" : "HasVersion4Uuids";
|
|
2756
|
+
})();
|
|
2757
|
+
const pkDefault = idField?.default;
|
|
2758
|
+
const isAutoincrement = idField !== void 0 && (idField.type === "Int" || idField.type === "BigInt") && pkDefault !== void 0 && pkDefault !== null && typeof pkDefault === "object" && "name" in pkDefault && pkDefault.name === "autoincrement";
|
|
2759
|
+
const timestampConstLines = [...timestamps.createdColumn === null && timestamps.updatedColumn !== null ? [" const CREATED_AT = null;"] : timestamps.createdColumn !== null && timestamps.createdColumn !== "created_at" ? [` const CREATED_AT = '${timestamps.createdColumn}';`] : [], ...timestamps.updatedColumn === null && timestamps.createdColumn !== null ? [" const UPDATED_AT = null;"] : timestamps.updatedColumn !== null && timestamps.updatedColumn !== "updated_at" ? [` const UPDATED_AT = '${timestamps.updatedColumn}';`] : []];
|
|
2760
|
+
const timestampsDisabled = timestamps.createdColumn === null && timestamps.updatedColumn === null;
|
|
2761
|
+
const attributeFields = model.fields.filter((f) => (f.kind === "scalar" || f.kind === "enum") && !f.isId && !timestamps.exclude.has(f.name));
|
|
2762
|
+
const fillableLines = attributeFields.length > 0 ? [
|
|
2763
|
+
" protected $fillable = [",
|
|
2764
|
+
...attributeFields.map((f) => ` '${f.dbName ?? f.name}',`),
|
|
2765
|
+
" ];"
|
|
2766
|
+
] : [];
|
|
2767
|
+
const castEntries = attributeFields.flatMap((f) => {
|
|
2768
|
+
const column = f.dbName ?? f.name;
|
|
2769
|
+
if (f.isList) return [];
|
|
2770
|
+
if (f.kind === "enum" && enumNames.has(f.type)) return [` '${column}' => ${f.type}::class,`];
|
|
2771
|
+
const cast = prismaTypeToEloquentCast(f.type);
|
|
2772
|
+
return cast ? [` '${column}' => '${cast}',`] : [];
|
|
2773
|
+
});
|
|
2774
|
+
const castLines = castEntries.length > 0 ? [
|
|
2775
|
+
" protected $casts = [",
|
|
2776
|
+
...castEntries,
|
|
2777
|
+
" ];"
|
|
2778
|
+
] : [];
|
|
2779
|
+
const propertyBlocks = [
|
|
2780
|
+
...pkUuidTrait !== null ? [[` use ${pkUuidTrait};`]] : [],
|
|
2781
|
+
...timestampConstLines.length > 0 ? [timestampConstLines] : [],
|
|
2782
|
+
[` protected $table = '${tableName}';`],
|
|
2783
|
+
...pkColumn !== null && pkColumn !== "id" ? [[` protected $primaryKey = '${pkColumn}';`]] : [],
|
|
2784
|
+
...idField === void 0 && compositePkFields.length > 0 ? [[" protected $primaryKey = null;"]] : [],
|
|
2785
|
+
...idField?.type === "String" ? [[" protected $keyType = 'string';"]] : [],
|
|
2786
|
+
...idField !== void 0 && !isAutoincrement || idField === void 0 && compositePkFields.length > 0 ? [[" public $incrementing = false;"]] : [],
|
|
2787
|
+
...timestampsDisabled ? [[" public $timestamps = false;"]] : [],
|
|
2788
|
+
...fillableLines.length > 0 ? [fillableLines] : [],
|
|
2789
|
+
...castLines.length > 0 ? [castLines] : []
|
|
2790
|
+
];
|
|
2791
|
+
const belongsToMethods = associations.belongsTo.map((a) => {
|
|
2792
|
+
const ownerKeyArg = a.ownerKeyColumn === "id" ? "" : `, '${a.ownerKeyColumn}'`;
|
|
2793
|
+
return [
|
|
2794
|
+
` public function ${a.name}(): BelongsTo`,
|
|
2795
|
+
" {",
|
|
2796
|
+
` return $this->belongsTo(${a.targetModel}::class, '${a.foreignKeyColumn}'${ownerKeyArg});`,
|
|
2797
|
+
" }"
|
|
2798
|
+
];
|
|
2799
|
+
});
|
|
2800
|
+
const hasOneMethods = associations.hasOne.map((a) => {
|
|
2801
|
+
const localKeyArg = a.localKeyColumn === "id" ? "" : `, '${a.localKeyColumn}'`;
|
|
2802
|
+
return [
|
|
2803
|
+
` public function ${a.name}(): HasOne`,
|
|
2804
|
+
" {",
|
|
2805
|
+
` return $this->hasOne(${a.targetModel}::class, '${a.foreignKeyColumn}'${localKeyArg});`,
|
|
2806
|
+
" }"
|
|
2807
|
+
];
|
|
2808
|
+
});
|
|
2809
|
+
const hasManyMethods = associations.hasMany.map((a) => {
|
|
2810
|
+
const localKeyArg = a.localKeyColumn === "id" ? "" : `, '${a.localKeyColumn}'`;
|
|
2811
|
+
return [
|
|
2812
|
+
` public function ${a.name}(): HasMany`,
|
|
2813
|
+
" {",
|
|
2814
|
+
` return $this->hasMany(${a.targetModel}::class, '${a.foreignKeyColumn}'${localKeyArg});`,
|
|
2815
|
+
" }"
|
|
2816
|
+
];
|
|
2817
|
+
});
|
|
2818
|
+
const belongsToManyMethods = associations.belongsToMany.map((a) => [
|
|
2819
|
+
` public function ${a.name}(): BelongsToMany`,
|
|
2820
|
+
" {",
|
|
2821
|
+
` return $this->belongsToMany(${a.targetModel}::class, '${a.joinTable}', '${a.foreignPivotKey}', '${a.relatedPivotKey}');`,
|
|
2822
|
+
" }"
|
|
2823
|
+
]);
|
|
2824
|
+
const methodBlocks = [
|
|
2825
|
+
...belongsToMethods,
|
|
2826
|
+
...hasOneMethods,
|
|
2827
|
+
...hasManyMethods,
|
|
2828
|
+
...belongsToManyMethods
|
|
2829
|
+
];
|
|
2830
|
+
const relationImports = [
|
|
2831
|
+
...associations.belongsTo.length > 0 ? ["BelongsTo"] : [],
|
|
2832
|
+
...associations.belongsToMany.length > 0 ? ["BelongsToMany"] : [],
|
|
2833
|
+
...associations.hasMany.length > 0 ? ["HasMany"] : [],
|
|
2834
|
+
...associations.hasOne.length > 0 ? ["HasOne"] : []
|
|
2835
|
+
];
|
|
2836
|
+
const doc = stripAnnotations(model.documentation);
|
|
2837
|
+
const docLines = doc ? [
|
|
2838
|
+
"/**",
|
|
2839
|
+
...doc.split("\n").map((line) => ` * ${line}`),
|
|
2840
|
+
" */"
|
|
2841
|
+
] : [];
|
|
2842
|
+
const bodyBlocks = [...propertyBlocks, ...methodBlocks];
|
|
2843
|
+
return [
|
|
2844
|
+
"<?php",
|
|
2845
|
+
"",
|
|
2846
|
+
`namespace ${namespace};`,
|
|
2847
|
+
"",
|
|
2848
|
+
...pkUuidTrait !== null ? [`use Illuminate\\Database\\Eloquent\\Concerns\\${pkUuidTrait};`] : [],
|
|
2849
|
+
"use Illuminate\\Database\\Eloquent\\Model;",
|
|
2850
|
+
...relationImports.map((r) => `use Illuminate\\Database\\Eloquent\\Relations\\${r};`),
|
|
2851
|
+
"",
|
|
2852
|
+
...docLines,
|
|
2853
|
+
`class ${model.name} extends Model`,
|
|
2854
|
+
"{",
|
|
2855
|
+
...bodyBlocks.flatMap((block, i) => i === 0 ? block : ["", ...block]),
|
|
2856
|
+
"}"
|
|
2857
|
+
].join("\n");
|
|
2858
|
+
}).filter(Boolean).join("\n\n");
|
|
2859
|
+
}
|
|
2860
|
+
//#endregion
|
|
2861
|
+
//#region src/generator/eloquent.ts
|
|
2862
|
+
function eloquentModelFiles(models, namespace, enums) {
|
|
2863
|
+
const resolvedNamespace = (Array.isArray(namespace) ? namespace.join("\\") : namespace).replace(/\./g, "\\");
|
|
2864
|
+
const modelFiles = models.map((model) => ({
|
|
2865
|
+
fileName: `${model.name}.php`,
|
|
2866
|
+
code: eloquentModels([model], resolvedNamespace, models, enums)
|
|
2867
|
+
}));
|
|
2868
|
+
const enumFiles = (enums ?? []).map((enumDef) => ({
|
|
2869
|
+
fileName: `${enumDef.name}.php`,
|
|
2870
|
+
code: eloquentEnum(enumDef, resolvedNamespace)
|
|
2871
|
+
}));
|
|
2872
|
+
return [...modelFiles, ...enumFiles].filter((entry) => entry.code.trim().length > 0);
|
|
2873
|
+
}
|
|
2874
|
+
//#endregion
|
|
2875
|
+
//#region src/core/eloquent.ts
|
|
2876
|
+
async function eloquent(options) {
|
|
2877
|
+
if (!(options.generator.isCustomOutput && options.generator.output?.value)) return {
|
|
2878
|
+
ok: false,
|
|
2879
|
+
error: "output is required for Hekireki-Eloquent. Please specify output in your generator config."
|
|
2880
|
+
};
|
|
2881
|
+
const outDir = options.generator.output.value;
|
|
2882
|
+
const namespace = options.generator.config?.namespace ?? "App\\Models";
|
|
2883
|
+
const enums = options.dmmf.datamodel.enums;
|
|
2884
|
+
return emitMany(eloquentModelFiles(options.dmmf.datamodel.models, namespace, enums), outDir);
|
|
2885
|
+
}
|
|
2886
|
+
//#endregion
|
|
2485
2887
|
//#region src/helper/gorm.ts
|
|
2486
2888
|
const PRISMA_TO_GO = {
|
|
2487
2889
|
String: "string",
|
|
@@ -2599,6 +3001,7 @@ function formatGoDefault(def) {
|
|
|
2599
3001
|
function buildGormTags(field, isPk, isCompositePk, compositeIndexTags) {
|
|
2600
3002
|
const columnName = field.dbName ?? makeSnakeCase(field.name);
|
|
2601
3003
|
const isUuidDefault = isFunctionDefault$2(field.default) && field.default.name === "uuid";
|
|
3004
|
+
const isUlidDefault = isFunctionDefault$2(field.default) && field.default.name === "ulid";
|
|
2602
3005
|
const isNowDefault = field.type === "DateTime" && isFunctionDefault$2(field.default) && field.default.name === "now";
|
|
2603
3006
|
const nativeType = resolveNativeType$1(field);
|
|
2604
3007
|
const includeNativeType = nativeType && (!isPk || !isFunctionDefault$2(field.default) || field.default.name !== "uuid");
|
|
@@ -2609,6 +3012,7 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags) {
|
|
|
2609
3012
|
isPk ? "primaryKey" : null,
|
|
2610
3013
|
isPk && isAutoincrement$2(field) ? "autoIncrement" : null,
|
|
2611
3014
|
isPk && isUuidDefault ? "type:char(36)" : null,
|
|
3015
|
+
isPk && isUlidDefault ? "type:char(26)" : null,
|
|
2612
3016
|
field.isUnique ? "uniqueIndex" : null,
|
|
2613
3017
|
...compositeIndexTags,
|
|
2614
3018
|
includeNativeType ? `type:${nativeType}` : null,
|
|
@@ -2678,11 +3082,6 @@ const GO_INITIALISMS = /* @__PURE__ */ new Set([
|
|
|
2678
3082
|
"xsrf",
|
|
2679
3083
|
"xss"
|
|
2680
3084
|
]);
|
|
2681
|
-
/**
|
|
2682
|
-
* Split a camelCase/PascalCase name into words, applying Go initialism rules.
|
|
2683
|
-
* e.g. "userId" -> ["User", "ID"], "avatarUrl" -> ["Avatar", "URL"],
|
|
2684
|
-
* "ipAddress" -> ["IP", "Address"], "createdAt" -> ["Created", "At"]
|
|
2685
|
-
*/
|
|
2686
3085
|
function splitGoWords(name) {
|
|
2687
3086
|
return name.replace(/([a-z0-9])([A-Z])/g, "$1\0$2").split("\0").map((part) => {
|
|
2688
3087
|
const lower = part.toLowerCase();
|
|
@@ -2692,6 +3091,40 @@ function splitGoWords(name) {
|
|
|
2692
3091
|
function goFieldName(name) {
|
|
2693
3092
|
return splitGoWords(name).join("");
|
|
2694
3093
|
}
|
|
3094
|
+
function generatedIdExpr$1(field) {
|
|
3095
|
+
if (!isFunctionDefault$2(field.default)) return null;
|
|
3096
|
+
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid.Must(uuid.NewV7()).String()" : "uuid.NewString()";
|
|
3097
|
+
if (field.default.name === "ulid") return "ulid.MustNew(ulid.Now(), rand.Reader).String()";
|
|
3098
|
+
return null;
|
|
3099
|
+
}
|
|
3100
|
+
function generatedIdFields(model) {
|
|
3101
|
+
return model.fields.filter((f) => f.kind === "scalar" && f.type === "String" && !f.isList && generatedIdExpr$1(f) !== null);
|
|
3102
|
+
}
|
|
3103
|
+
function generateBeforeCreateHook(model) {
|
|
3104
|
+
const idFields = generatedIdFields(model);
|
|
3105
|
+
if (idFields.length === 0) return [];
|
|
3106
|
+
const assignments = idFields.flatMap((field) => {
|
|
3107
|
+
const fieldName = goFieldName(field.name);
|
|
3108
|
+
const expr = generatedIdExpr$1(field);
|
|
3109
|
+
return field.isRequired ? [
|
|
3110
|
+
`\tif m.${fieldName} == "" {`,
|
|
3111
|
+
`\t\tm.${fieldName} = ${expr}`,
|
|
3112
|
+
" }"
|
|
3113
|
+
] : [
|
|
3114
|
+
`\tif m.${fieldName} == nil {`,
|
|
3115
|
+
`\t\tgenerated := ${expr}`,
|
|
3116
|
+
`\t\tm.${fieldName} = &generated`,
|
|
3117
|
+
" }"
|
|
3118
|
+
];
|
|
3119
|
+
});
|
|
3120
|
+
return [
|
|
3121
|
+
"",
|
|
3122
|
+
`func (m *${model.name}) BeforeCreate(_ *gorm.DB) error {`,
|
|
3123
|
+
...assignments,
|
|
3124
|
+
" return nil",
|
|
3125
|
+
"}"
|
|
3126
|
+
];
|
|
3127
|
+
}
|
|
2695
3128
|
function generateStructField(field, isPk, isCompositePk, compositeIndexTags, _enumNames) {
|
|
2696
3129
|
const fieldName = goFieldName(field.name);
|
|
2697
3130
|
const scalarType = field.kind === "enum" ? field.isRequired ? "string" : "*string" : prismaTypeToGoType(field.type, field.isRequired);
|
|
@@ -2760,13 +3193,23 @@ function generateModelStruct(model, allModels, enums, indexes) {
|
|
|
2760
3193
|
...fieldLines,
|
|
2761
3194
|
...relationLines,
|
|
2762
3195
|
"}",
|
|
2763
|
-
...tableNameMethod
|
|
3196
|
+
...tableNameMethod,
|
|
3197
|
+
...generateBeforeCreateHook(model)
|
|
2764
3198
|
].join("\n");
|
|
2765
3199
|
}
|
|
2766
3200
|
function collectImports(models) {
|
|
2767
3201
|
const needsTime = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "DateTime"));
|
|
2768
3202
|
const needsDatatypes = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "Json"));
|
|
2769
|
-
|
|
3203
|
+
const needsUuid = models.some((m) => generatedIdFields(m).some((f) => isFunctionDefault$2(f.default) && f.default.name === "uuid"));
|
|
3204
|
+
const needsUlid = models.some((m) => generatedIdFields(m).some((f) => isFunctionDefault$2(f.default) && f.default.name === "ulid"));
|
|
3205
|
+
return [
|
|
3206
|
+
needsUlid ? "\"crypto/rand\"" : null,
|
|
3207
|
+
needsTime ? "\"time\"" : null,
|
|
3208
|
+
needsUuid ? "\"github.com/google/uuid\"" : null,
|
|
3209
|
+
needsUlid ? "\"github.com/oklog/ulid/v2\"" : null,
|
|
3210
|
+
needsDatatypes ? "\"gorm.io/datatypes\"" : null,
|
|
3211
|
+
needsUuid || needsUlid ? "\"gorm.io/gorm\"" : null
|
|
3212
|
+
].filter((i) => i !== null);
|
|
2770
3213
|
}
|
|
2771
3214
|
function formatImports(imports) {
|
|
2772
3215
|
if (imports.length === 0) return [];
|
|
@@ -2878,10 +3321,17 @@ const PRISMA_TO_RUST = {
|
|
|
2878
3321
|
Float: "f64",
|
|
2879
3322
|
Decimal: "Decimal",
|
|
2880
3323
|
Boolean: "bool",
|
|
2881
|
-
DateTime: "
|
|
3324
|
+
DateTime: "DateTime",
|
|
2882
3325
|
Json: "Json",
|
|
2883
3326
|
Bytes: "Vec<u8>"
|
|
2884
3327
|
};
|
|
3328
|
+
function rustTypeForNative(field) {
|
|
3329
|
+
const nativeName = field.nativeType?.[0];
|
|
3330
|
+
if (nativeName === "Timestamptz") return "DateTimeWithTimeZone";
|
|
3331
|
+
if (nativeName === "Date") return "Date";
|
|
3332
|
+
if (nativeName === "Time" || nativeName === "Timetz") return "Time";
|
|
3333
|
+
return null;
|
|
3334
|
+
}
|
|
2885
3335
|
function prismaTypeToRustType(type, isRequired) {
|
|
2886
3336
|
const base = PRISMA_TO_RUST[type] ?? "String";
|
|
2887
3337
|
if (!isRequired) return `Option<${base}>`;
|
|
@@ -2981,7 +3431,7 @@ function resolveSeaOrmColumnType(field) {
|
|
|
2981
3431
|
case "Decimal":
|
|
2982
3432
|
case "Money": return args.length >= 2 ? `Decimal(Some((${args[0]}, ${args[1]})))` : "Decimal(None)";
|
|
2983
3433
|
case "Uuid": return "Uuid";
|
|
2984
|
-
case "Timestamp":
|
|
3434
|
+
case "Timestamp": return null;
|
|
2985
3435
|
case "Timestamptz": return "TimestampWithTimeZone";
|
|
2986
3436
|
case "Date": return "Date";
|
|
2987
3437
|
case "Time":
|
|
@@ -2996,6 +3446,12 @@ function isFunctionDefault$1(def) {
|
|
|
2996
3446
|
function isAutoincrement$1(field) {
|
|
2997
3447
|
return isFunctionDefault$1(field.default) && field.default.name === "autoincrement";
|
|
2998
3448
|
}
|
|
3449
|
+
function generatedIdExpr(field) {
|
|
3450
|
+
if (!isFunctionDefault$1(field.default)) return null;
|
|
3451
|
+
if (field.default.name === "uuid") return field.default.args[0] === 7 ? "uuid::Uuid::now_v7().to_string()" : "uuid::Uuid::new_v4().to_string()";
|
|
3452
|
+
if (field.default.name === "ulid") return "ulid::Ulid::generate().to_string()";
|
|
3453
|
+
return null;
|
|
3454
|
+
}
|
|
2999
3455
|
function formatRustDefault(def) {
|
|
3000
3456
|
if (def === void 0 || def === null) return null;
|
|
3001
3457
|
if (typeof def === "boolean") return def ? "true" : "false";
|
|
@@ -3079,14 +3535,8 @@ function getAssociations$1(model, allModels) {
|
|
|
3079
3535
|
manyToMany
|
|
3080
3536
|
};
|
|
3081
3537
|
}
|
|
3082
|
-
function toSnakeCase(name) {
|
|
3083
|
-
return makeSnakeCase(name);
|
|
3084
|
-
}
|
|
3085
3538
|
function toPascalCase(name) {
|
|
3086
|
-
return name.charAt(0).toUpperCase() +
|
|
3087
|
-
}
|
|
3088
|
-
function toModuleName(modelName) {
|
|
3089
|
-
return toSnakeCase(modelName);
|
|
3539
|
+
return name.split("_").filter((part) => part !== "").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
3090
3540
|
}
|
|
3091
3541
|
const NON_EQ_PRISMA_TYPES = /* @__PURE__ */ new Set(["Float"]);
|
|
3092
3542
|
function canDeriveEq(fields) {
|
|
@@ -3106,7 +3556,7 @@ function generateEnum(e, serde = {}) {
|
|
|
3106
3556
|
return [
|
|
3107
3557
|
"#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]",
|
|
3108
3558
|
...buildSerdeAttributes(serde),
|
|
3109
|
-
|
|
3559
|
+
`#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "${e.dbName ?? e.name}")]`,
|
|
3110
3560
|
`pub enum ${e.name} {`,
|
|
3111
3561
|
...variants,
|
|
3112
3562
|
"}"
|
|
@@ -3115,22 +3565,29 @@ function generateEnum(e, serde = {}) {
|
|
|
3115
3565
|
function generateRelationEnum(_model, associations) {
|
|
3116
3566
|
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");
|
|
3117
3567
|
const variants = [];
|
|
3568
|
+
const targetCount = /* @__PURE__ */ new Map();
|
|
3569
|
+
for (const assoc of [
|
|
3570
|
+
...associations.belongsTo,
|
|
3571
|
+
...associations.hasMany,
|
|
3572
|
+
...associations.hasOne
|
|
3573
|
+
]) targetCount.set(assoc.targetModel, (targetCount.get(assoc.targetModel) ?? 0) + 1);
|
|
3574
|
+
const isAmbiguous = (targetModel) => (targetCount.get(targetModel) ?? 0) > 1;
|
|
3118
3575
|
for (const assoc of associations.belongsTo) {
|
|
3119
3576
|
const variantName = toPascalCase(assoc.name);
|
|
3120
|
-
const targetModule =
|
|
3577
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3121
3578
|
const fromCol = toPascalCase(assoc.foreignKey);
|
|
3122
3579
|
const toCol = toPascalCase(assoc.references);
|
|
3123
3580
|
variants.push(` #[sea_orm(\n belongs_to = "super::${targetModule}::Entity",\n from = "Column::${fromCol}",\n to = "super::${targetModule}::Column::${toCol}"\n )]\n ${variantName},`);
|
|
3124
3581
|
}
|
|
3125
3582
|
for (const assoc of associations.hasMany) {
|
|
3126
3583
|
const variantName = toPascalCase(assoc.name);
|
|
3127
|
-
const targetModule =
|
|
3128
|
-
variants.push(` #[sea_orm(has_many = "super::${targetModule}::Entity")]\n ${variantName},`);
|
|
3584
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3585
|
+
variants.push(isAmbiguous(assoc.targetModel) ? ` #[sea_orm(\n has_many = "super::${targetModule}::Entity",\n from = "Column::${toPascalCase(assoc.references)}",\n to = "super::${targetModule}::Column::${toPascalCase(assoc.foreignKey)}"\n )]\n ${variantName},` : ` #[sea_orm(has_many = "super::${targetModule}::Entity")]\n ${variantName},`);
|
|
3129
3586
|
}
|
|
3130
3587
|
for (const assoc of associations.hasOne) {
|
|
3131
3588
|
const variantName = toPascalCase(assoc.name);
|
|
3132
|
-
const targetModule =
|
|
3133
|
-
variants.push(` #[sea_orm(has_one = "super::${targetModule}::Entity")]\n ${variantName},`);
|
|
3589
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3590
|
+
variants.push(isAmbiguous(assoc.targetModel) ? ` #[sea_orm(\n has_one = "super::${targetModule}::Entity",\n from = "Column::${toPascalCase(assoc.references)}",\n to = "super::${targetModule}::Column::${toPascalCase(assoc.foreignKey)}"\n )]\n ${variantName},` : ` #[sea_orm(has_one = "super::${targetModule}::Entity")]\n ${variantName},`);
|
|
3134
3591
|
}
|
|
3135
3592
|
return [
|
|
3136
3593
|
"#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]",
|
|
@@ -3145,7 +3602,7 @@ function generateRelatedImpls(model, associations) {
|
|
|
3145
3602
|
for (const assoc of associations.belongsTo) {
|
|
3146
3603
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
3147
3604
|
emittedTargets.add(assoc.targetModel);
|
|
3148
|
-
const targetModule =
|
|
3605
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3149
3606
|
impls.push([
|
|
3150
3607
|
`impl Related<super::${targetModule}::Entity> for Entity {`,
|
|
3151
3608
|
" fn to() -> RelationDef {",
|
|
@@ -3157,7 +3614,7 @@ function generateRelatedImpls(model, associations) {
|
|
|
3157
3614
|
for (const assoc of associations.hasMany) {
|
|
3158
3615
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
3159
3616
|
emittedTargets.add(assoc.targetModel);
|
|
3160
|
-
const targetModule =
|
|
3617
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3161
3618
|
impls.push([
|
|
3162
3619
|
`impl Related<super::${targetModule}::Entity> for Entity {`,
|
|
3163
3620
|
" fn to() -> RelationDef {",
|
|
@@ -3169,7 +3626,7 @@ function generateRelatedImpls(model, associations) {
|
|
|
3169
3626
|
for (const assoc of associations.hasOne) {
|
|
3170
3627
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
3171
3628
|
emittedTargets.add(assoc.targetModel);
|
|
3172
|
-
const targetModule =
|
|
3629
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3173
3630
|
impls.push([
|
|
3174
3631
|
`impl Related<super::${targetModule}::Entity> for Entity {`,
|
|
3175
3632
|
" fn to() -> RelationDef {",
|
|
@@ -3181,9 +3638,9 @@ function generateRelatedImpls(model, associations) {
|
|
|
3181
3638
|
for (const assoc of associations.manyToMany) {
|
|
3182
3639
|
if (emittedTargets.has(assoc.targetModel)) continue;
|
|
3183
3640
|
emittedTargets.add(assoc.targetModel);
|
|
3184
|
-
const targetModule =
|
|
3641
|
+
const targetModule = makeSnakeCase(assoc.targetModel);
|
|
3185
3642
|
const [leftName, rightName] = model.name < assoc.targetModel ? [model.name, assoc.targetModel] : [assoc.targetModel, model.name];
|
|
3186
|
-
const junctionModule =
|
|
3643
|
+
const junctionModule = makeSnakeCase(`${leftName}To${rightName}`);
|
|
3187
3644
|
const junctionRelToTarget = toPascalCase(assoc.targetModel);
|
|
3188
3645
|
const junctionRelToSelf = toPascalCase(model.name);
|
|
3189
3646
|
impls.push([
|
|
@@ -3204,27 +3661,45 @@ function generateEntityFile(model, allModels, enums, serde = {}) {
|
|
|
3204
3661
|
const compositePkFieldNames = new Set(model.primaryKey?.fields ?? []);
|
|
3205
3662
|
const isCompositePk = !idField && compositePkFieldNames.size > 0;
|
|
3206
3663
|
if (!(idField || isCompositePk)) return "";
|
|
3207
|
-
const tableName = model.dbName ??
|
|
3664
|
+
const tableName = model.dbName ?? makeSnakeCase(model.name);
|
|
3208
3665
|
const associations = getAssociations$1(model, allModels);
|
|
3209
3666
|
const enumNames = new Set(enums.map((e) => e.name));
|
|
3210
3667
|
const scalarFields = model.fields.filter((f) => f.kind !== "object");
|
|
3211
3668
|
const fieldLines = [];
|
|
3212
3669
|
for (const field of scalarFields) {
|
|
3213
3670
|
const isPk = field.isId || compositePkFieldNames.has(field.name);
|
|
3214
|
-
const { ident: fieldName, derivedColumn } = rustFieldIdent(
|
|
3671
|
+
const { ident: fieldName, derivedColumn } = rustFieldIdent(makeSnakeCase(field.name));
|
|
3215
3672
|
const attrs = buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn);
|
|
3216
|
-
const
|
|
3217
|
-
const
|
|
3673
|
+
const nativeOverride = rustTypeForNative(field);
|
|
3674
|
+
const elemType = enumNames.has(field.type) ? field.type : nativeOverride ?? prismaTypeToRustType(field.type, true);
|
|
3675
|
+
const rustType = field.isList ? `Vec<${elemType}>` : enumNames.has(field.type) || nativeOverride !== null ? field.isRequired ? elemType : `Option<${elemType}>` : prismaTypeToRustType(field.type, field.isRequired);
|
|
3218
3676
|
for (const attr of attrs) fieldLines.push(` ${attr}`);
|
|
3219
3677
|
fieldLines.push(` pub ${fieldName}: ${rustType},`);
|
|
3220
3678
|
}
|
|
3221
3679
|
const relationEnum = generateRelationEnum(model, associations);
|
|
3222
3680
|
const relatedImpls = generateRelatedImpls(model, associations);
|
|
3681
|
+
const enumImports = [...new Set(scalarFields.filter((f) => enumNames.has(f.type)).map((f) => f.type))].sort().map((name) => `use super::${makeSnakeCase(name)}::${name};`);
|
|
3682
|
+
const generatedIdFields = scalarFields.filter((f) => f.type === "String" && !f.isList && generatedIdExpr(f) !== null);
|
|
3223
3683
|
const useLines = [
|
|
3224
3684
|
"use sea_orm::entity::prelude::*;",
|
|
3685
|
+
...generatedIdFields.length > 0 ? ["use sea_orm::Set;"] : [],
|
|
3225
3686
|
"use serde::{Deserialize, Serialize};",
|
|
3226
|
-
...
|
|
3687
|
+
...enumImports
|
|
3227
3688
|
];
|
|
3689
|
+
const behaviorImpl = generatedIdFields.length === 0 ? "impl ActiveModelBehavior for ActiveModel {}" : [
|
|
3690
|
+
"impl ActiveModelBehavior for ActiveModel {",
|
|
3691
|
+
" fn new() -> Self {",
|
|
3692
|
+
" Self {",
|
|
3693
|
+
...generatedIdFields.map((field) => {
|
|
3694
|
+
const { ident } = rustFieldIdent(makeSnakeCase(field.name));
|
|
3695
|
+
const generate = generatedIdExpr(field);
|
|
3696
|
+
return ` ${ident}: Set(${field.isRequired ? generate : `Some(${generate})`}),`;
|
|
3697
|
+
}),
|
|
3698
|
+
" ..ActiveModelTrait::default()",
|
|
3699
|
+
" }",
|
|
3700
|
+
" }",
|
|
3701
|
+
"}"
|
|
3702
|
+
].join("\n");
|
|
3228
3703
|
const deriveModel = canDeriveEq(scalarFields) ? "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]" : "#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]";
|
|
3229
3704
|
const serdeAttrs = buildSerdeAttributes(serde);
|
|
3230
3705
|
return [
|
|
@@ -3240,18 +3715,18 @@ function generateEntityFile(model, allModels, enums, serde = {}) {
|
|
|
3240
3715
|
relationEnum,
|
|
3241
3716
|
"",
|
|
3242
3717
|
...relatedImpls.map((impl) => `${impl}\n`),
|
|
3243
|
-
|
|
3718
|
+
behaviorImpl
|
|
3244
3719
|
].join("\n");
|
|
3245
3720
|
}
|
|
3246
3721
|
function generateM2MEntity(leftModel, rightModel, _allModels, serde = {}) {
|
|
3247
3722
|
const [sortedLeft, sortedRight] = leftModel < rightModel ? [leftModel, rightModel] : [rightModel, leftModel];
|
|
3248
3723
|
const tableName = `_${sortedLeft}To${sortedRight}`;
|
|
3249
|
-
const leftModule =
|
|
3250
|
-
const rightModule =
|
|
3251
|
-
const leftFk = `${
|
|
3252
|
-
const rightFk = `${
|
|
3253
|
-
const leftCol = toPascalCase(`${
|
|
3254
|
-
const rightCol = toPascalCase(`${
|
|
3724
|
+
const leftModule = makeSnakeCase(sortedLeft);
|
|
3725
|
+
const rightModule = makeSnakeCase(sortedRight);
|
|
3726
|
+
const leftFk = `${makeSnakeCase(sortedLeft)}_id`;
|
|
3727
|
+
const rightFk = `${makeSnakeCase(sortedRight)}_id`;
|
|
3728
|
+
const leftCol = toPascalCase(`${makeSnakeCase(sortedLeft)}Id`);
|
|
3729
|
+
const rightCol = toPascalCase(`${makeSnakeCase(sortedRight)}Id`);
|
|
3255
3730
|
const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
|
|
3256
3731
|
const deriveModel = "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]";
|
|
3257
3732
|
const serdeAttrs = buildSerdeAttributes(serde);
|
|
@@ -3262,9 +3737,9 @@ function generateM2MEntity(leftModel, rightModel, _allModels, serde = {}) {
|
|
|
3262
3737
|
...serdeAttrs,
|
|
3263
3738
|
`#[sea_orm(table_name = "${tableName}")]`,
|
|
3264
3739
|
"pub struct Model {",
|
|
3265
|
-
" #[sea_orm(primary_key, auto_increment = false)]",
|
|
3740
|
+
" #[sea_orm(primary_key, auto_increment = false, column_name = \"A\")]",
|
|
3266
3741
|
` pub ${leftFk}: String,`,
|
|
3267
|
-
" #[sea_orm(primary_key, auto_increment = false)]",
|
|
3742
|
+
" #[sea_orm(primary_key, auto_increment = false, column_name = \"B\")]",
|
|
3268
3743
|
` pub ${rightFk}: String,`,
|
|
3269
3744
|
"}",
|
|
3270
3745
|
"",
|
|
@@ -3292,7 +3767,7 @@ function generateModRs(moduleNames) {
|
|
|
3292
3767
|
}
|
|
3293
3768
|
function generatePreludeRs(models) {
|
|
3294
3769
|
return `${models.map((m) => {
|
|
3295
|
-
return `pub use super::${
|
|
3770
|
+
return `pub use super::${makeSnakeCase(m.name)}::Entity as ${m.name};`;
|
|
3296
3771
|
}).join("\n")}\n`;
|
|
3297
3772
|
}
|
|
3298
3773
|
function collectM2MPairs(models) {
|
|
@@ -3316,8 +3791,8 @@ function collectM2MPairs(models) {
|
|
|
3316
3791
|
function seaOrmFiles(models, enums, serde = {}) {
|
|
3317
3792
|
const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
|
|
3318
3793
|
const enumFiles = enums.map((e) => ({
|
|
3319
|
-
fileName: `${
|
|
3320
|
-
moduleName:
|
|
3794
|
+
fileName: `${makeSnakeCase(e.name)}.rs`,
|
|
3795
|
+
moduleName: makeSnakeCase(e.name),
|
|
3321
3796
|
code: [
|
|
3322
3797
|
...useLines,
|
|
3323
3798
|
"",
|
|
@@ -3326,12 +3801,12 @@ function seaOrmFiles(models, enums, serde = {}) {
|
|
|
3326
3801
|
].join("\n")
|
|
3327
3802
|
}));
|
|
3328
3803
|
const entityFiles = models.map((model) => ({
|
|
3329
|
-
fileName: `${
|
|
3330
|
-
moduleName:
|
|
3804
|
+
fileName: `${makeSnakeCase(model.name)}.rs`,
|
|
3805
|
+
moduleName: makeSnakeCase(model.name),
|
|
3331
3806
|
code: generateEntityFile(model, models, enums, serde)
|
|
3332
3807
|
})).filter((entry) => entry.code.trim().length > 0);
|
|
3333
3808
|
const m2mFiles = collectM2MPairs(models).map((pair) => {
|
|
3334
|
-
const moduleName =
|
|
3809
|
+
const moduleName = makeSnakeCase(`${pair.left}To${pair.right}`);
|
|
3335
3810
|
return {
|
|
3336
3811
|
fileName: `${moduleName}.rs`,
|
|
3337
3812
|
moduleName,
|
|
@@ -3437,8 +3912,14 @@ const PYTHON_KEYWORDS = /* @__PURE__ */ new Set([
|
|
|
3437
3912
|
"with",
|
|
3438
3913
|
"yield"
|
|
3439
3914
|
]);
|
|
3915
|
+
const DECLARATIVE_RESERVED = /* @__PURE__ */ new Set([
|
|
3916
|
+
"self",
|
|
3917
|
+
"cls",
|
|
3918
|
+
"metadata",
|
|
3919
|
+
"registry"
|
|
3920
|
+
]);
|
|
3440
3921
|
function pythonAttrName(columnName) {
|
|
3441
|
-
return PYTHON_KEYWORDS.has(columnName) ? `${columnName}_` : columnName;
|
|
3922
|
+
return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) ? `${columnName}_` : columnName;
|
|
3442
3923
|
}
|
|
3443
3924
|
function resolveNativeType(field) {
|
|
3444
3925
|
const baseType = prismaTypeToSQLAlchemyType(field.type);
|
|
@@ -3456,14 +3937,16 @@ function resolveNativeType(field) {
|
|
|
3456
3937
|
case "TinyInt": return "SmallInteger";
|
|
3457
3938
|
case "MediumInt": return "Integer";
|
|
3458
3939
|
case "DoublePrecision":
|
|
3459
|
-
case "Double":
|
|
3460
|
-
case "Real": return "
|
|
3940
|
+
case "Double": return "Double";
|
|
3941
|
+
case "Real": return "REAL";
|
|
3461
3942
|
case "Decimal":
|
|
3462
3943
|
case "Money": return args.length >= 2 ? `Numeric(precision=${args[0]}, scale=${args[1]})` : "Numeric";
|
|
3463
3944
|
case "Uuid": return "Uuid";
|
|
3464
3945
|
case "Timestamp": return "DateTime";
|
|
3946
|
+
case "Timestamptz": return "DateTime(timezone=True)";
|
|
3465
3947
|
case "Date": return "Date";
|
|
3466
3948
|
case "Time": return "Time";
|
|
3949
|
+
case "Timetz": return "Time(timezone=True)";
|
|
3467
3950
|
case "JsonB": return "JSON";
|
|
3468
3951
|
case "Xml": return "String";
|
|
3469
3952
|
default: return baseType;
|
|
@@ -3471,6 +3954,7 @@ function resolveNativeType(field) {
|
|
|
3471
3954
|
}
|
|
3472
3955
|
function needsExplicitSaType(field) {
|
|
3473
3956
|
if (field.kind === "enum") return true;
|
|
3957
|
+
if (field.type === "Json") return true;
|
|
3474
3958
|
if (field.nativeType) {
|
|
3475
3959
|
if (resolveNativeType(field) !== prismaTypeToSQLAlchemyType(field.type)) return true;
|
|
3476
3960
|
}
|
|
@@ -3484,7 +3968,7 @@ function pythonTypeForNative(field) {
|
|
|
3484
3968
|
const [nativeName] = field.nativeType;
|
|
3485
3969
|
if (nativeName === "Uuid") return "uuid_mod.UUID";
|
|
3486
3970
|
if (nativeName === "Date") return "date";
|
|
3487
|
-
if (nativeName === "Time") return "time_type";
|
|
3971
|
+
if (nativeName === "Time" || nativeName === "Timetz") return "time_type";
|
|
3488
3972
|
const raw = prismaTypeToPythonType(field.type);
|
|
3489
3973
|
return raw === "Decimal" ? "DecimalType" : raw;
|
|
3490
3974
|
}
|
|
@@ -3500,7 +3984,8 @@ function getAssociations(model, allModels) {
|
|
|
3500
3984
|
name: field.name,
|
|
3501
3985
|
targetModel: field.type,
|
|
3502
3986
|
foreignKey: field.relationFromFields[0],
|
|
3503
|
-
references: field.relationToFields?.[0] ?? "id"
|
|
3987
|
+
references: field.relationToFields?.[0] ?? "id",
|
|
3988
|
+
optional: !field.isRequired
|
|
3504
3989
|
});
|
|
3505
3990
|
continue;
|
|
3506
3991
|
}
|
|
@@ -3528,7 +4013,8 @@ function getAssociations(model, allModels) {
|
|
|
3528
4013
|
name: field.name,
|
|
3529
4014
|
targetModel: field.type,
|
|
3530
4015
|
foreignKey,
|
|
3531
|
-
isList: false
|
|
4016
|
+
isList: false,
|
|
4017
|
+
optional: !field.isRequired
|
|
3532
4018
|
});
|
|
3533
4019
|
}
|
|
3534
4020
|
return {
|
|
@@ -3547,11 +4033,13 @@ function collectManyToManyTables(allModels) {
|
|
|
3547
4033
|
const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
|
|
3548
4034
|
const leftModelObj = allModels.find((m) => m.name === leftName);
|
|
3549
4035
|
const rightModelObj = allModels.find((m) => m.name === rightName);
|
|
4036
|
+
const relationName = field.relationName ?? `${leftName}To${rightName}`;
|
|
3550
4037
|
return [{
|
|
3551
|
-
relationName
|
|
4038
|
+
relationName,
|
|
3552
4039
|
info: {
|
|
3553
|
-
|
|
3554
|
-
|
|
4040
|
+
relationName,
|
|
4041
|
+
tableName: `_${relationName}`,
|
|
4042
|
+
varName: makeSnakeCase(relationName),
|
|
3555
4043
|
leftModel: leftName,
|
|
3556
4044
|
leftTable: leftModelObj?.dbName ?? makeSnakeCase(leftName),
|
|
3557
4045
|
leftPkField: leftModelObj?.fields.find((f) => f.isId),
|
|
@@ -3595,6 +4083,13 @@ function isFunctionDefault(def) {
|
|
|
3595
4083
|
function isAutoincrement(field) {
|
|
3596
4084
|
return isFunctionDefault(field.default) && field.default.name === "autoincrement";
|
|
3597
4085
|
}
|
|
4086
|
+
function uuidDefaultVersion(field) {
|
|
4087
|
+
if (!(isFunctionDefault(field.default) && field.default.name === "uuid")) return null;
|
|
4088
|
+
return field.default.args[0] === 7 ? 7 : 4;
|
|
4089
|
+
}
|
|
4090
|
+
function isUlidDefault(field) {
|
|
4091
|
+
return isFunctionDefault(field.default) && field.default.name === "ulid";
|
|
4092
|
+
}
|
|
3598
4093
|
function needsForeignKeysParam(targetModel, assocs) {
|
|
3599
4094
|
return assocs.filter((a) => a.targetModel === targetModel).length > 1;
|
|
3600
4095
|
}
|
|
@@ -3644,12 +4139,20 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap) {
|
|
|
3644
4139
|
if (isPk) colArgs.push("primary_key=True");
|
|
3645
4140
|
if (isPk && isAutoincrement(field)) colArgs.push("autoincrement=True");
|
|
3646
4141
|
if (field.isUnique) colArgs.push("unique=True");
|
|
4142
|
+
const uuidVersion = uuidDefaultVersion(field);
|
|
3647
4143
|
if (field.type === "DateTime" && isFunctionDefault(field.default) && field.default.name === "now") colArgs.push("server_default=func.now()");
|
|
4144
|
+
else if (uuidVersion !== null) {
|
|
4145
|
+
const isNativeUuid = field.nativeType?.[0] === "Uuid";
|
|
4146
|
+
colArgs.push(isNativeUuid ? uuidVersion === 7 ? "default=uuid6.uuid7" : "default=uuid_mod.uuid4" : uuidVersion === 7 ? "default=lambda: str(uuid6.uuid7())" : "default=lambda: str(uuid_mod.uuid4())");
|
|
4147
|
+
} else if (isUlidDefault(field)) colArgs.push("default=lambda: str(ULID())");
|
|
3648
4148
|
else if (!isPk || isAutoincrement(field)) {
|
|
3649
4149
|
const defaultVal = formatDefault(field.default);
|
|
3650
4150
|
if (defaultVal !== null && !isPk) colArgs.push(`default=${defaultVal}`);
|
|
3651
4151
|
}
|
|
3652
|
-
if (field.isUpdatedAt)
|
|
4152
|
+
if (field.isUpdatedAt) {
|
|
4153
|
+
if (!(field.type === "DateTime" && isFunctionDefault(field.default) && field.default.name === "now")) colArgs.push("default=func.now()");
|
|
4154
|
+
colArgs.push("onupdate=func.now()");
|
|
4155
|
+
}
|
|
3653
4156
|
if (colArgs.length === 0) return ` ${attrName}: Mapped[${typeHint}]`;
|
|
3654
4157
|
return ` ${attrName}: Mapped[${typeHint}] = mapped_column(${colArgs.join(", ")})`;
|
|
3655
4158
|
}
|
|
@@ -3660,7 +4163,7 @@ function generateTableArgs(model, indexes) {
|
|
|
3660
4163
|
}).join(", ")})`;
|
|
3661
4164
|
});
|
|
3662
4165
|
const indexConstraints = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
|
|
3663
|
-
return `Index("${idx.dbName ?? idx.name ?? `idx_${idx.fields.map((f) => makeSnakeCase(f.name)).join("_")}`}", ${idx.fields.map((f) => {
|
|
4166
|
+
return `Index("${idx.dbName ?? idx.name ?? `idx_${model.dbName ?? makeSnakeCase(model.name)}_${idx.fields.map((f) => makeSnakeCase(f.name)).join("_")}`}", ${idx.fields.map((f) => {
|
|
3664
4167
|
return `"${model.fields.find((mf) => mf.name === f.name)?.dbName ?? makeSnakeCase(f.name)}"`;
|
|
3665
4168
|
}).join(", ")})`;
|
|
3666
4169
|
});
|
|
@@ -3681,7 +4184,7 @@ function generateBelongsToRelationships(associations, model, allModels) {
|
|
|
3681
4184
|
const fkClause = needsForeignKeysParam(assoc.targetModel, associations.belongsTo) ? `foreign_keys=[${snakeFk}], ` : "";
|
|
3682
4185
|
const pkField = model.fields.find((f) => f.isId);
|
|
3683
4186
|
const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${pkField.dbName ?? makeSnakeCase(pkField.name)}], ` : "";
|
|
3684
|
-
return ` ${snakeName}: Mapped["${assoc.targetModel}"] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
|
|
4187
|
+
return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${assoc.targetModel}"]` : `"${assoc.targetModel}"`}] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
|
|
3685
4188
|
});
|
|
3686
4189
|
}
|
|
3687
4190
|
function generateHasManyRelationships(associations, model, allModels) {
|
|
@@ -3703,15 +4206,14 @@ function generateHasOneRelationships(associations, model, allModels) {
|
|
|
3703
4206
|
const needsFkParam = targetModel ? needsForeignKeysParam(model.name, getAssociations(targetModel, allModels).belongsTo) : false;
|
|
3704
4207
|
const targetFkSnake = makeSnakeCase(assoc.foreignKey);
|
|
3705
4208
|
const fkClause = needsFkParam ? `foreign_keys="${assoc.targetModel}.${targetFkSnake}", ` : "";
|
|
3706
|
-
return ` ${snakeName}: Mapped["${assoc.targetModel}"] = relationship(${fkClause}back_populates="${backPop}"
|
|
4209
|
+
return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${assoc.targetModel}"]` : `"${assoc.targetModel}"`}] = relationship(${fkClause}back_populates="${backPop}")`;
|
|
3707
4210
|
});
|
|
3708
4211
|
}
|
|
3709
4212
|
function generateManyToManyRelationships(associations, model, allModels, m2mTables) {
|
|
3710
4213
|
return associations.manyToMany.map((assoc) => {
|
|
3711
4214
|
const snakeName = makeSnakeCase(assoc.name);
|
|
3712
4215
|
const backPop = findM2MBackPopulates(assoc.targetModel, model.name, assoc.relationName, allModels);
|
|
3713
|
-
const
|
|
3714
|
-
const secondaryVar = m2mTables.find((t) => t.leftModel === leftName && t.rightModel === rightName)?.varName ?? `${makeSnakeCase(leftName)}_to_${makeSnakeCase(rightName)}`;
|
|
4216
|
+
const secondaryVar = m2mTables.find((t) => t.relationName === assoc.relationName)?.varName ?? makeSnakeCase(assoc.relationName);
|
|
3715
4217
|
return ` ${snakeName}: Mapped[list["${assoc.targetModel}"]] = relationship(secondary=${secondaryVar}, back_populates="${backPop}")`;
|
|
3716
4218
|
});
|
|
3717
4219
|
}
|
|
@@ -3755,10 +4257,13 @@ function collectGlobalImports(models, _enums, indexes, m2mTables) {
|
|
|
3755
4257
|
const needsDecimal = models.some((m) => m.fields.some((f) => f.type === "Decimal"));
|
|
3756
4258
|
const needsDatetime = models.some((m) => m.fields.some((f) => f.type === "DateTime"));
|
|
3757
4259
|
const needsUuid = models.some((m) => m.fields.some((f) => {
|
|
4260
|
+
if (uuidDefaultVersion(f) === 4) return true;
|
|
3758
4261
|
if (!f.nativeType) return false;
|
|
3759
4262
|
const [n] = f.nativeType;
|
|
3760
4263
|
return n === "Uuid";
|
|
3761
4264
|
}));
|
|
4265
|
+
const needsUuid7 = models.some((m) => m.fields.some((f) => uuidDefaultVersion(f) === 7));
|
|
4266
|
+
const needsUlid = models.some((m) => m.fields.some((f) => isUlidDefault(f)));
|
|
3762
4267
|
const needsDate = models.some((m) => m.fields.some((f) => {
|
|
3763
4268
|
if (!f.nativeType) return false;
|
|
3764
4269
|
const [n] = f.nativeType;
|
|
@@ -3822,6 +4327,8 @@ function collectGlobalImports(models, _enums, indexes, m2mTables) {
|
|
|
3822
4327
|
if (needsTime) dtParts.push("time as time_type");
|
|
3823
4328
|
if (dtParts.length > 0) lines.push(`from datetime import ${dtParts.join(", ")}`);
|
|
3824
4329
|
if (needsUuid) lines.push("import uuid as uuid_mod");
|
|
4330
|
+
if (needsUuid7) lines.push("import uuid6");
|
|
4331
|
+
if (needsUlid) lines.push("from ulid import ULID");
|
|
3825
4332
|
return lines;
|
|
3826
4333
|
}
|
|
3827
4334
|
//#endregion
|
|
@@ -4071,6 +4578,10 @@ async function zod(options) {
|
|
|
4071
4578
|
//#endregion
|
|
4072
4579
|
//#region src/bin/index.ts
|
|
4073
4580
|
const GENERATORS = {
|
|
4581
|
+
activerecord: {
|
|
4582
|
+
prettyName: "Hekireki-ActiveRecord",
|
|
4583
|
+
handler: activerecord
|
|
4584
|
+
},
|
|
4074
4585
|
ajv: {
|
|
4075
4586
|
prettyName: "Hekireki-AJV",
|
|
4076
4587
|
handler: ajv
|
|
@@ -4099,6 +4610,10 @@ const GENERATORS = {
|
|
|
4099
4610
|
prettyName: "Hekireki-Effect",
|
|
4100
4611
|
handler: effect
|
|
4101
4612
|
},
|
|
4613
|
+
eloquent: {
|
|
4614
|
+
prettyName: "Hekireki-Eloquent",
|
|
4615
|
+
handler: eloquent
|
|
4616
|
+
},
|
|
4102
4617
|
gorm: {
|
|
4103
4618
|
prettyName: "Hekireki-GORM",
|
|
4104
4619
|
handler: gorm
|