hekireki 0.9.2 → 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.
@@ -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",
@@ -1632,14 +1760,15 @@ const MainContent = ({ models, types }) => /* @__PURE__ */ jsxs("div", {
1632
1760
  class: mainContentClass,
1633
1761
  children: [models, types]
1634
1762
  });
1635
- const generateHTML = (data) => {
1636
- return `<!DOCTYPE html>${(/* @__PURE__ */ jsx(Layout, { children: /* @__PURE__ */ jsxs("div", {
1763
+ const generateHTML = async (data) => {
1764
+ const element = /* @__PURE__ */ jsx(Layout, { children: /* @__PURE__ */ jsxs("div", {
1637
1765
  class: containerClass,
1638
1766
  children: [/* @__PURE__ */ jsx(Sidebar, { toc: createTOC(data) }), /* @__PURE__ */ jsx(MainContent, {
1639
1767
  models: createModels(data),
1640
1768
  types: createTypes(data)
1641
1769
  })]
1642
- }) })).toString()}`;
1770
+ }) });
1771
+ return `<!DOCTYPE html>${await resolveCallback(await Promise.resolve(element).then((node) => node.toString()), HtmlEscapedCallbackPhase.Stringify, false, {})}`;
1643
1772
  };
1644
1773
  //#endregion
1645
1774
  //#region src/generator/docs.ts
@@ -1654,7 +1783,7 @@ async function docs(options) {
1654
1783
  error: "output is required for Hekireki-Docs. Please specify output in your generator config."
1655
1784
  };
1656
1785
  const output = options.generator.output.value;
1657
- return emitRaw(docsHTML(options.dmmf), output, path.join(output, "index.html"));
1786
+ return emitRaw(await docsHTML(options.dmmf), output, path.join(output, "index.html"));
1658
1787
  }
1659
1788
  //#endregion
1660
1789
  //#region src/helper/drizzle.ts
@@ -1881,7 +2010,14 @@ function resolveDefaultValue(dflt, fieldType, provider) {
1881
2010
  chain: ".defaultNow()",
1882
2011
  imports: []
1883
2012
  };
1884
- 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
+ } : {
1885
2021
  chain: ".$defaultFn(() => crypto.randomUUID())",
1886
2022
  imports: []
1887
2023
  };
@@ -2071,12 +2207,13 @@ function drizzleSchema(datamodel, provider, indexes) {
2071
2207
  const enumLines = makeEnumDeclarations(datamodel.models, datamodel.enums, db, imports);
2072
2208
  const tableLines = datamodel.models.map((model) => makeTable(model, datamodel.models, db, imports, datamodel.enums, indexes));
2073
2209
  const relationsLines = makeRelations(datamodel.models, imports);
2210
+ const enumLinesWithGap = enumLines.flatMap((line, i) => i < enumLines.length - 1 ? [line, ""] : [line]);
2074
2211
  const tableLinesWithGap = tableLines.flatMap((line, i) => i < tableLines.length - 1 ? [line, ""] : [line]);
2075
2212
  const relationsLinesWithGap = relationsLines.flatMap((line, i) => i < relationsLines.length - 1 ? [line, ""] : [line]);
2076
2213
  return [
2077
2214
  generateImports(imports, db),
2078
2215
  "",
2079
- ...enumLines.length > 0 ? [...enumLines, ""] : [],
2216
+ ...enumLinesWithGap.length > 0 ? [...enumLinesWithGap, ""] : [],
2080
2217
  ...tableLinesWithGap,
2081
2218
  ...relationsLinesWithGap.length > 0 ? ["", ...relationsLinesWithGap] : []
2082
2219
  ].join("\n");
@@ -2131,6 +2268,7 @@ function ectoTypeToTypespec(type) {
2131
2268
  case "float": return "float()";
2132
2269
  case "boolean": return "boolean()";
2133
2270
  case "binary_id": return "Ecto.UUID.t()";
2271
+ case "Ecto.ULID": return "Ecto.ULID.t()";
2134
2272
  case "naive_datetime": return "NaiveDateTime.t()";
2135
2273
  case "utc_datetime": return "DateTime.t()";
2136
2274
  case "decimal": return "Decimal.t()";
@@ -2139,26 +2277,37 @@ function ectoTypeToTypespec(type) {
2139
2277
  default: return "term()";
2140
2278
  }
2141
2279
  }
2280
+ function formatEctoType(type) {
2281
+ return /^[A-Z]/.test(type) ? type : `:${type}`;
2282
+ }
2142
2283
  function getPrimaryKeyConfig(field) {
2143
2284
  const def = field.default;
2144
2285
  const isFunctionDefault = def && typeof def === "object" && "name" in def;
2286
+ const pkColumn = field.dbName ?? field.name;
2287
+ const sourceOpt = pkColumn === "id" ? "" : `, source: :${pkColumn}`;
2145
2288
  if (field.type === "String" && isFunctionDefault && def.name === "uuid") return {
2146
- line: "@primary_key {:id, :binary_id, autogenerate: true}",
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}}`,
2147
2290
  typeSpec: "Ecto.UUID.t()",
2148
2291
  omitIdFieldInSchema: true,
2149
- useBinaryForeignKey: true
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"
2150
2299
  };
2151
2300
  if (field.type === "Int" && isFunctionDefault && def.name === "autoincrement") return {
2152
- line: "@primary_key {:id, :id, autogenerate: true}",
2301
+ line: `@primary_key {:id, :id, autogenerate: true${sourceOpt}}`,
2153
2302
  typeSpec: "integer()",
2154
2303
  omitIdFieldInSchema: true,
2155
- useBinaryForeignKey: false
2304
+ foreignKeyType: null
2156
2305
  };
2157
2306
  return {
2158
2307
  line: "@primary_key false",
2159
2308
  typeSpec: "String.t()",
2160
2309
  omitIdFieldInSchema: false,
2161
- useBinaryForeignKey: false
2310
+ foreignKeyType: null
2162
2311
  };
2163
2312
  }
2164
2313
  function makeTimestampsLine(fields) {
@@ -2186,11 +2335,11 @@ function makeTimestampsLine(fields) {
2186
2335
  if (inserted) {
2187
2336
  const source = inserted.dbName ?? inserted.name;
2188
2337
  if (source !== "inserted_at") opts.push(`inserted_at_source: :${source}`);
2189
- }
2338
+ } else opts.push("inserted_at: false");
2190
2339
  if (updated) {
2191
2340
  const source = updated.dbName ?? updated.name;
2192
2341
  if (source !== "updated_at") opts.push(`updated_at_source: :${source}`);
2193
- }
2342
+ } else opts.push("updated_at: false");
2194
2343
  return {
2195
2344
  line: ` timestamps(${opts.join(", ")})`,
2196
2345
  exclude
@@ -2202,14 +2351,14 @@ function getBelongsToFkType(allModels, targetModelName) {
2202
2351
  const targetPk = targetModel.fields.find((f) => f.isId);
2203
2352
  if (!targetPk) return null;
2204
2353
  const pkConfig = getPrimaryKeyConfig(targetPk);
2205
- if (pkConfig.useBinaryForeignKey) return "binary_id";
2354
+ if (pkConfig.foreignKeyType) return pkConfig.foreignKeyType;
2206
2355
  if (pkConfig.line.includes(":id, autogenerate")) return null;
2207
2356
  if (targetPk.type === "String") return "string";
2208
2357
  const ectoType = prismaTypeToEctoType(targetPk.type);
2209
2358
  if (ectoType === "integer") return null;
2210
2359
  return ectoType;
2211
2360
  }
2212
- function getAssociations$3(model, allModels) {
2361
+ function getAssociations$4(model, allModels) {
2213
2362
  const belongsTo = [];
2214
2363
  const hasMany = [];
2215
2364
  const hasOne = [];
@@ -2231,10 +2380,16 @@ function getAssociations$3(model, allModels) {
2231
2380
  if (field.isList) {
2232
2381
  if (targetModel.fields.find((f) => f.relationName === field.relationName && f.kind === "object")?.isList) {
2233
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);
2234
2385
  manyToMany.push({
2235
2386
  name: field.name,
2236
2387
  targetModel: field.type,
2237
- 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")
2238
2393
  });
2239
2394
  continue;
2240
2395
  }
@@ -2271,12 +2426,11 @@ function ectoSchemas(models, app, allModels, enums) {
2271
2426
  line: "@primary_key false",
2272
2427
  typeSpec: "",
2273
2428
  omitIdFieldInSchema: false,
2274
- useBinaryForeignKey: false
2429
+ foreignKeyType: null
2275
2430
  };
2276
- const useBinaryId = pk.useBinaryForeignKey;
2277
2431
  const fields = model.fields.map((f) => ({ ...f }));
2278
2432
  const { line: timestampsLine, exclude: timestampsExclude } = makeTimestampsLine(fields);
2279
- const associations = getAssociations$3(model, contextModels);
2433
+ const associations = getAssociations$4(model, contextModels);
2280
2434
  const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
2281
2435
  const enumMap = /* @__PURE__ */ new Map();
2282
2436
  if (enums) for (const e of enums) enumMap.set(e.name, e.values.map((v) => v.name));
@@ -2313,7 +2467,7 @@ function ectoSchemas(models, app, allModels, enums) {
2313
2467
  const sourceOpt = snakeName !== dbColumnName ? `, source: :${dbColumnName}` : "";
2314
2468
  if (f.kind === "enum") {
2315
2469
  const values = enumMap.get(f.type);
2316
- 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})`;
2317
2471
  }
2318
2472
  const type = prismaTypeToEctoType(f.type);
2319
2473
  const ectoType = f.isList ? `{:array, :${type}}` : `:${type}`;
@@ -2336,7 +2490,7 @@ function ectoSchemas(models, app, allModels, enums) {
2336
2490
  const fkType = a.fkType ?? "id";
2337
2491
  const pkOpt = isPkField ? ", primary_key: true" : "";
2338
2492
  const sourceOpt = needsSource ? `, source: :${fkDbName}` : "";
2339
- fkFieldLines.push(` field(:${snakeFk}, :${fkType}${pkOpt}${sourceOpt})`);
2493
+ fkFieldLines.push(` field(:${snakeFk}, ${formatEctoType(fkType)}${pkOpt}${sourceOpt})`);
2340
2494
  }
2341
2495
  }
2342
2496
  const belongsToLines = associations.belongsTo.map((a) => {
@@ -2346,7 +2500,7 @@ function ectoSchemas(models, app, allModels, enums) {
2346
2500
  const isPkField = compositePkFieldNames.has(a.foreignKey);
2347
2501
  const opts = [`foreign_key: :${snakeFk}`];
2348
2502
  if (needsSource || isPkField) opts.push("define_field: false");
2349
- if (a.fkType && (!useBinaryId || a.fkType !== "binary_id")) opts.push(`type: :${a.fkType}`);
2503
+ if (a.fkType && a.fkType !== pk.foreignKeyType) opts.push(`type: ${formatEctoType(a.fkType)}`);
2350
2504
  if (a.references !== "id") opts.push(`references: :${a.references}`);
2351
2505
  return ` belongs_to(:${snakeAssocName}, ${appName}.${a.targetModel}, ${opts.join(", ")})`;
2352
2506
  });
@@ -2359,7 +2513,9 @@ function ectoSchemas(models, app, allModels, enums) {
2359
2513
  return ` has_many(:${makeSnakeCase(a.name)}, ${appName}.${a.targetModel}, foreign_key: :${snakeFk})`;
2360
2514
  });
2361
2515
  const manyToManyLines = associations.manyToMany.map((a) => {
2362
- return ` many_to_many(:${makeSnakeCase(a.name)}, ${appName}.${a.targetModel}, join_through: "${a.joinThrough}")`;
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})`;
2363
2519
  });
2364
2520
  return [
2365
2521
  `defmodule ${appName}.${model.name} do`,
@@ -2371,7 +2527,7 @@ function ectoSchemas(models, app, allModels, enums) {
2371
2527
  ] : [" @moduledoc false"],
2372
2528
  "",
2373
2529
  ` ${pk.line}`,
2374
- ...useBinaryId ? [" @foreign_key_type :binary_id"] : [],
2530
+ ...pk.foreignKeyType ? [` @foreign_key_type ${formatEctoType(pk.foreignKeyType)}`] : [],
2375
2531
  "",
2376
2532
  ...typeSpecLines,
2377
2533
  "",
@@ -2481,6 +2637,253 @@ async function effect(options) {
2481
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);
2482
2638
  }
2483
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
2484
2887
  //#region src/helper/gorm.ts
2485
2888
  const PRISMA_TO_GO = {
2486
2889
  String: "string",
@@ -2598,6 +3001,7 @@ function formatGoDefault(def) {
2598
3001
  function buildGormTags(field, isPk, isCompositePk, compositeIndexTags) {
2599
3002
  const columnName = field.dbName ?? makeSnakeCase(field.name);
2600
3003
  const isUuidDefault = isFunctionDefault$2(field.default) && field.default.name === "uuid";
3004
+ const isUlidDefault = isFunctionDefault$2(field.default) && field.default.name === "ulid";
2601
3005
  const isNowDefault = field.type === "DateTime" && isFunctionDefault$2(field.default) && field.default.name === "now";
2602
3006
  const nativeType = resolveNativeType$1(field);
2603
3007
  const includeNativeType = nativeType && (!isPk || !isFunctionDefault$2(field.default) || field.default.name !== "uuid");
@@ -2608,6 +3012,7 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags) {
2608
3012
  isPk ? "primaryKey" : null,
2609
3013
  isPk && isAutoincrement$2(field) ? "autoIncrement" : null,
2610
3014
  isPk && isUuidDefault ? "type:char(36)" : null,
3015
+ isPk && isUlidDefault ? "type:char(26)" : null,
2611
3016
  field.isUnique ? "uniqueIndex" : null,
2612
3017
  ...compositeIndexTags,
2613
3018
  includeNativeType ? `type:${nativeType}` : null,
@@ -2677,11 +3082,6 @@ const GO_INITIALISMS = /* @__PURE__ */ new Set([
2677
3082
  "xsrf",
2678
3083
  "xss"
2679
3084
  ]);
2680
- /**
2681
- * Split a camelCase/PascalCase name into words, applying Go initialism rules.
2682
- * e.g. "userId" -> ["User", "ID"], "avatarUrl" -> ["Avatar", "URL"],
2683
- * "ipAddress" -> ["IP", "Address"], "createdAt" -> ["Created", "At"]
2684
- */
2685
3085
  function splitGoWords(name) {
2686
3086
  return name.replace(/([a-z0-9])([A-Z])/g, "$1\0$2").split("\0").map((part) => {
2687
3087
  const lower = part.toLowerCase();
@@ -2691,6 +3091,40 @@ function splitGoWords(name) {
2691
3091
  function goFieldName(name) {
2692
3092
  return splitGoWords(name).join("");
2693
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
+ }
2694
3128
  function generateStructField(field, isPk, isCompositePk, compositeIndexTags, _enumNames) {
2695
3129
  const fieldName = goFieldName(field.name);
2696
3130
  const scalarType = field.kind === "enum" ? field.isRequired ? "string" : "*string" : prismaTypeToGoType(field.type, field.isRequired);
@@ -2759,13 +3193,23 @@ function generateModelStruct(model, allModels, enums, indexes) {
2759
3193
  ...fieldLines,
2760
3194
  ...relationLines,
2761
3195
  "}",
2762
- ...tableNameMethod
3196
+ ...tableNameMethod,
3197
+ ...generateBeforeCreateHook(model)
2763
3198
  ].join("\n");
2764
3199
  }
2765
3200
  function collectImports(models) {
2766
3201
  const needsTime = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "DateTime"));
2767
3202
  const needsDatatypes = models.some((m) => m.fields.some((f) => f.kind !== "object" && f.type === "Json"));
2768
- return [needsTime ? "\"time\"" : null, needsDatatypes ? "\"gorm.io/datatypes\"" : null].filter((i) => i !== null);
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);
2769
3213
  }
2770
3214
  function formatImports(imports) {
2771
3215
  if (imports.length === 0) return [];
@@ -2877,10 +3321,17 @@ const PRISMA_TO_RUST = {
2877
3321
  Float: "f64",
2878
3322
  Decimal: "Decimal",
2879
3323
  Boolean: "bool",
2880
- DateTime: "DateTimeUtc",
3324
+ DateTime: "DateTime",
2881
3325
  Json: "Json",
2882
3326
  Bytes: "Vec<u8>"
2883
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
+ }
2884
3335
  function prismaTypeToRustType(type, isRequired) {
2885
3336
  const base = PRISMA_TO_RUST[type] ?? "String";
2886
3337
  if (!isRequired) return `Option<${base}>`;
@@ -2980,7 +3431,7 @@ function resolveSeaOrmColumnType(field) {
2980
3431
  case "Decimal":
2981
3432
  case "Money": return args.length >= 2 ? `Decimal(Some((${args[0]}, ${args[1]})))` : "Decimal(None)";
2982
3433
  case "Uuid": return "Uuid";
2983
- case "Timestamp":
3434
+ case "Timestamp": return null;
2984
3435
  case "Timestamptz": return "TimestampWithTimeZone";
2985
3436
  case "Date": return "Date";
2986
3437
  case "Time":
@@ -2995,6 +3446,12 @@ function isFunctionDefault$1(def) {
2995
3446
  function isAutoincrement$1(field) {
2996
3447
  return isFunctionDefault$1(field.default) && field.default.name === "autoincrement";
2997
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
+ }
2998
3455
  function formatRustDefault(def) {
2999
3456
  if (def === void 0 || def === null) return null;
3000
3457
  if (typeof def === "boolean") return def ? "true" : "false";
@@ -3078,14 +3535,8 @@ function getAssociations$1(model, allModels) {
3078
3535
  manyToMany
3079
3536
  };
3080
3537
  }
3081
- function toSnakeCase(name) {
3082
- return makeSnakeCase(name);
3083
- }
3084
3538
  function toPascalCase(name) {
3085
- return name.charAt(0).toUpperCase() + name.slice(1);
3086
- }
3087
- function toModuleName(modelName) {
3088
- return toSnakeCase(modelName);
3539
+ return name.split("_").filter((part) => part !== "").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
3089
3540
  }
3090
3541
  const NON_EQ_PRISMA_TYPES = /* @__PURE__ */ new Set(["Float"]);
3091
3542
  function canDeriveEq(fields) {
@@ -3105,7 +3556,7 @@ function generateEnum(e, serde = {}) {
3105
3556
  return [
3106
3557
  "#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]",
3107
3558
  ...buildSerdeAttributes(serde),
3108
- "#[sea_orm(rs_type = \"String\", db_type = \"String(StringLen::None)\")]",
3559
+ `#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "${e.dbName ?? e.name}")]`,
3109
3560
  `pub enum ${e.name} {`,
3110
3561
  ...variants,
3111
3562
  "}"
@@ -3114,22 +3565,29 @@ function generateEnum(e, serde = {}) {
3114
3565
  function generateRelationEnum(_model, associations) {
3115
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");
3116
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;
3117
3575
  for (const assoc of associations.belongsTo) {
3118
3576
  const variantName = toPascalCase(assoc.name);
3119
- const targetModule = toModuleName(assoc.targetModel);
3577
+ const targetModule = makeSnakeCase(assoc.targetModel);
3120
3578
  const fromCol = toPascalCase(assoc.foreignKey);
3121
3579
  const toCol = toPascalCase(assoc.references);
3122
3580
  variants.push(` #[sea_orm(\n belongs_to = "super::${targetModule}::Entity",\n from = "Column::${fromCol}",\n to = "super::${targetModule}::Column::${toCol}"\n )]\n ${variantName},`);
3123
3581
  }
3124
3582
  for (const assoc of associations.hasMany) {
3125
3583
  const variantName = toPascalCase(assoc.name);
3126
- const targetModule = toModuleName(assoc.targetModel);
3127
- 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},`);
3128
3586
  }
3129
3587
  for (const assoc of associations.hasOne) {
3130
3588
  const variantName = toPascalCase(assoc.name);
3131
- const targetModule = toModuleName(assoc.targetModel);
3132
- 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},`);
3133
3591
  }
3134
3592
  return [
3135
3593
  "#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]",
@@ -3144,7 +3602,7 @@ function generateRelatedImpls(model, associations) {
3144
3602
  for (const assoc of associations.belongsTo) {
3145
3603
  if (emittedTargets.has(assoc.targetModel)) continue;
3146
3604
  emittedTargets.add(assoc.targetModel);
3147
- const targetModule = toModuleName(assoc.targetModel);
3605
+ const targetModule = makeSnakeCase(assoc.targetModel);
3148
3606
  impls.push([
3149
3607
  `impl Related<super::${targetModule}::Entity> for Entity {`,
3150
3608
  " fn to() -> RelationDef {",
@@ -3156,7 +3614,7 @@ function generateRelatedImpls(model, associations) {
3156
3614
  for (const assoc of associations.hasMany) {
3157
3615
  if (emittedTargets.has(assoc.targetModel)) continue;
3158
3616
  emittedTargets.add(assoc.targetModel);
3159
- const targetModule = toModuleName(assoc.targetModel);
3617
+ const targetModule = makeSnakeCase(assoc.targetModel);
3160
3618
  impls.push([
3161
3619
  `impl Related<super::${targetModule}::Entity> for Entity {`,
3162
3620
  " fn to() -> RelationDef {",
@@ -3168,7 +3626,7 @@ function generateRelatedImpls(model, associations) {
3168
3626
  for (const assoc of associations.hasOne) {
3169
3627
  if (emittedTargets.has(assoc.targetModel)) continue;
3170
3628
  emittedTargets.add(assoc.targetModel);
3171
- const targetModule = toModuleName(assoc.targetModel);
3629
+ const targetModule = makeSnakeCase(assoc.targetModel);
3172
3630
  impls.push([
3173
3631
  `impl Related<super::${targetModule}::Entity> for Entity {`,
3174
3632
  " fn to() -> RelationDef {",
@@ -3180,9 +3638,9 @@ function generateRelatedImpls(model, associations) {
3180
3638
  for (const assoc of associations.manyToMany) {
3181
3639
  if (emittedTargets.has(assoc.targetModel)) continue;
3182
3640
  emittedTargets.add(assoc.targetModel);
3183
- const targetModule = toModuleName(assoc.targetModel);
3641
+ const targetModule = makeSnakeCase(assoc.targetModel);
3184
3642
  const [leftName, rightName] = model.name < assoc.targetModel ? [model.name, assoc.targetModel] : [assoc.targetModel, model.name];
3185
- const junctionModule = toSnakeCase(`${leftName}To${rightName}`);
3643
+ const junctionModule = makeSnakeCase(`${leftName}To${rightName}`);
3186
3644
  const junctionRelToTarget = toPascalCase(assoc.targetModel);
3187
3645
  const junctionRelToSelf = toPascalCase(model.name);
3188
3646
  impls.push([
@@ -3203,27 +3661,45 @@ function generateEntityFile(model, allModels, enums, serde = {}) {
3203
3661
  const compositePkFieldNames = new Set(model.primaryKey?.fields ?? []);
3204
3662
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
3205
3663
  if (!(idField || isCompositePk)) return "";
3206
- const tableName = model.dbName ?? toSnakeCase(model.name);
3664
+ const tableName = model.dbName ?? makeSnakeCase(model.name);
3207
3665
  const associations = getAssociations$1(model, allModels);
3208
3666
  const enumNames = new Set(enums.map((e) => e.name));
3209
3667
  const scalarFields = model.fields.filter((f) => f.kind !== "object");
3210
3668
  const fieldLines = [];
3211
3669
  for (const field of scalarFields) {
3212
3670
  const isPk = field.isId || compositePkFieldNames.has(field.name);
3213
- const { ident: fieldName, derivedColumn } = rustFieldIdent(toSnakeCase(field.name));
3671
+ const { ident: fieldName, derivedColumn } = rustFieldIdent(makeSnakeCase(field.name));
3214
3672
  const attrs = buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn);
3215
- const elemType = enumNames.has(field.type) ? field.type : prismaTypeToRustType(field.type, true);
3216
- const rustType = field.isList ? `Vec<${elemType}>` : enumNames.has(field.type) ? field.isRequired ? field.type : `Option<${field.type}>` : prismaTypeToRustType(field.type, field.isRequired);
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);
3217
3676
  for (const attr of attrs) fieldLines.push(` ${attr}`);
3218
3677
  fieldLines.push(` pub ${fieldName}: ${rustType},`);
3219
3678
  }
3220
3679
  const relationEnum = generateRelationEnum(model, associations);
3221
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);
3222
3683
  const useLines = [
3223
3684
  "use sea_orm::entity::prelude::*;",
3685
+ ...generatedIdFields.length > 0 ? ["use sea_orm::Set;"] : [],
3224
3686
  "use serde::{Deserialize, Serialize};",
3225
- ...[...new Set(scalarFields.filter((f) => enumNames.has(f.type)).map((f) => f.type))].sort().map((name) => `use super::${toSnakeCase(name)}::${name};`)
3687
+ ...enumImports
3226
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");
3227
3703
  const deriveModel = canDeriveEq(scalarFields) ? "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]" : "#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]";
3228
3704
  const serdeAttrs = buildSerdeAttributes(serde);
3229
3705
  return [
@@ -3239,18 +3715,18 @@ function generateEntityFile(model, allModels, enums, serde = {}) {
3239
3715
  relationEnum,
3240
3716
  "",
3241
3717
  ...relatedImpls.map((impl) => `${impl}\n`),
3242
- "impl ActiveModelBehavior for ActiveModel {}"
3718
+ behaviorImpl
3243
3719
  ].join("\n");
3244
3720
  }
3245
3721
  function generateM2MEntity(leftModel, rightModel, _allModels, serde = {}) {
3246
3722
  const [sortedLeft, sortedRight] = leftModel < rightModel ? [leftModel, rightModel] : [rightModel, leftModel];
3247
3723
  const tableName = `_${sortedLeft}To${sortedRight}`;
3248
- const leftModule = toModuleName(sortedLeft);
3249
- const rightModule = toModuleName(sortedRight);
3250
- const leftFk = `${toSnakeCase(sortedLeft)}_id`;
3251
- const rightFk = `${toSnakeCase(sortedRight)}_id`;
3252
- const leftCol = toPascalCase(`${toSnakeCase(sortedLeft)}Id`);
3253
- const rightCol = toPascalCase(`${toSnakeCase(sortedRight)}Id`);
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`);
3254
3730
  const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
3255
3731
  const deriveModel = "#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]";
3256
3732
  const serdeAttrs = buildSerdeAttributes(serde);
@@ -3261,9 +3737,9 @@ function generateM2MEntity(leftModel, rightModel, _allModels, serde = {}) {
3261
3737
  ...serdeAttrs,
3262
3738
  `#[sea_orm(table_name = "${tableName}")]`,
3263
3739
  "pub struct Model {",
3264
- " #[sea_orm(primary_key, auto_increment = false)]",
3740
+ " #[sea_orm(primary_key, auto_increment = false, column_name = \"A\")]",
3265
3741
  ` pub ${leftFk}: String,`,
3266
- " #[sea_orm(primary_key, auto_increment = false)]",
3742
+ " #[sea_orm(primary_key, auto_increment = false, column_name = \"B\")]",
3267
3743
  ` pub ${rightFk}: String,`,
3268
3744
  "}",
3269
3745
  "",
@@ -3291,7 +3767,7 @@ function generateModRs(moduleNames) {
3291
3767
  }
3292
3768
  function generatePreludeRs(models) {
3293
3769
  return `${models.map((m) => {
3294
- return `pub use super::${toModuleName(m.name)}::Entity as ${m.name};`;
3770
+ return `pub use super::${makeSnakeCase(m.name)}::Entity as ${m.name};`;
3295
3771
  }).join("\n")}\n`;
3296
3772
  }
3297
3773
  function collectM2MPairs(models) {
@@ -3315,8 +3791,8 @@ function collectM2MPairs(models) {
3315
3791
  function seaOrmFiles(models, enums, serde = {}) {
3316
3792
  const useLines = ["use sea_orm::entity::prelude::*;", "use serde::{Deserialize, Serialize};"];
3317
3793
  const enumFiles = enums.map((e) => ({
3318
- fileName: `${toSnakeCase(e.name)}.rs`,
3319
- moduleName: toSnakeCase(e.name),
3794
+ fileName: `${makeSnakeCase(e.name)}.rs`,
3795
+ moduleName: makeSnakeCase(e.name),
3320
3796
  code: [
3321
3797
  ...useLines,
3322
3798
  "",
@@ -3325,12 +3801,12 @@ function seaOrmFiles(models, enums, serde = {}) {
3325
3801
  ].join("\n")
3326
3802
  }));
3327
3803
  const entityFiles = models.map((model) => ({
3328
- fileName: `${toModuleName(model.name)}.rs`,
3329
- moduleName: toModuleName(model.name),
3804
+ fileName: `${makeSnakeCase(model.name)}.rs`,
3805
+ moduleName: makeSnakeCase(model.name),
3330
3806
  code: generateEntityFile(model, models, enums, serde)
3331
3807
  })).filter((entry) => entry.code.trim().length > 0);
3332
3808
  const m2mFiles = collectM2MPairs(models).map((pair) => {
3333
- const moduleName = toSnakeCase(`${pair.left}To${pair.right}`);
3809
+ const moduleName = makeSnakeCase(`${pair.left}To${pair.right}`);
3334
3810
  return {
3335
3811
  fileName: `${moduleName}.rs`,
3336
3812
  moduleName,
@@ -3436,8 +3912,14 @@ const PYTHON_KEYWORDS = /* @__PURE__ */ new Set([
3436
3912
  "with",
3437
3913
  "yield"
3438
3914
  ]);
3915
+ const DECLARATIVE_RESERVED = /* @__PURE__ */ new Set([
3916
+ "self",
3917
+ "cls",
3918
+ "metadata",
3919
+ "registry"
3920
+ ]);
3439
3921
  function pythonAttrName(columnName) {
3440
- return PYTHON_KEYWORDS.has(columnName) ? `${columnName}_` : columnName;
3922
+ return PYTHON_KEYWORDS.has(columnName) || DECLARATIVE_RESERVED.has(columnName) ? `${columnName}_` : columnName;
3441
3923
  }
3442
3924
  function resolveNativeType(field) {
3443
3925
  const baseType = prismaTypeToSQLAlchemyType(field.type);
@@ -3455,14 +3937,16 @@ function resolveNativeType(field) {
3455
3937
  case "TinyInt": return "SmallInteger";
3456
3938
  case "MediumInt": return "Integer";
3457
3939
  case "DoublePrecision":
3458
- case "Double":
3459
- case "Real": return "Double";
3940
+ case "Double": return "Double";
3941
+ case "Real": return "REAL";
3460
3942
  case "Decimal":
3461
3943
  case "Money": return args.length >= 2 ? `Numeric(precision=${args[0]}, scale=${args[1]})` : "Numeric";
3462
3944
  case "Uuid": return "Uuid";
3463
3945
  case "Timestamp": return "DateTime";
3946
+ case "Timestamptz": return "DateTime(timezone=True)";
3464
3947
  case "Date": return "Date";
3465
3948
  case "Time": return "Time";
3949
+ case "Timetz": return "Time(timezone=True)";
3466
3950
  case "JsonB": return "JSON";
3467
3951
  case "Xml": return "String";
3468
3952
  default: return baseType;
@@ -3470,6 +3954,7 @@ function resolveNativeType(field) {
3470
3954
  }
3471
3955
  function needsExplicitSaType(field) {
3472
3956
  if (field.kind === "enum") return true;
3957
+ if (field.type === "Json") return true;
3473
3958
  if (field.nativeType) {
3474
3959
  if (resolveNativeType(field) !== prismaTypeToSQLAlchemyType(field.type)) return true;
3475
3960
  }
@@ -3483,7 +3968,7 @@ function pythonTypeForNative(field) {
3483
3968
  const [nativeName] = field.nativeType;
3484
3969
  if (nativeName === "Uuid") return "uuid_mod.UUID";
3485
3970
  if (nativeName === "Date") return "date";
3486
- if (nativeName === "Time") return "time_type";
3971
+ if (nativeName === "Time" || nativeName === "Timetz") return "time_type";
3487
3972
  const raw = prismaTypeToPythonType(field.type);
3488
3973
  return raw === "Decimal" ? "DecimalType" : raw;
3489
3974
  }
@@ -3499,7 +3984,8 @@ function getAssociations(model, allModels) {
3499
3984
  name: field.name,
3500
3985
  targetModel: field.type,
3501
3986
  foreignKey: field.relationFromFields[0],
3502
- references: field.relationToFields?.[0] ?? "id"
3987
+ references: field.relationToFields?.[0] ?? "id",
3988
+ optional: !field.isRequired
3503
3989
  });
3504
3990
  continue;
3505
3991
  }
@@ -3527,7 +4013,8 @@ function getAssociations(model, allModels) {
3527
4013
  name: field.name,
3528
4014
  targetModel: field.type,
3529
4015
  foreignKey,
3530
- isList: false
4016
+ isList: false,
4017
+ optional: !field.isRequired
3531
4018
  });
3532
4019
  }
3533
4020
  return {
@@ -3546,11 +4033,13 @@ function collectManyToManyTables(allModels) {
3546
4033
  const [leftName, rightName] = model.name < field.type ? [model.name, field.type] : [field.type, model.name];
3547
4034
  const leftModelObj = allModels.find((m) => m.name === leftName);
3548
4035
  const rightModelObj = allModels.find((m) => m.name === rightName);
4036
+ const relationName = field.relationName ?? `${leftName}To${rightName}`;
3549
4037
  return [{
3550
- relationName: field.relationName ?? `${model.name}To${field.type}`,
4038
+ relationName,
3551
4039
  info: {
3552
- tableName: `_${leftName}To${rightName}`,
3553
- varName: `${makeSnakeCase(leftName)}_to_${makeSnakeCase(rightName)}`,
4040
+ relationName,
4041
+ tableName: `_${relationName}`,
4042
+ varName: makeSnakeCase(relationName),
3554
4043
  leftModel: leftName,
3555
4044
  leftTable: leftModelObj?.dbName ?? makeSnakeCase(leftName),
3556
4045
  leftPkField: leftModelObj?.fields.find((f) => f.isId),
@@ -3594,6 +4083,13 @@ function isFunctionDefault(def) {
3594
4083
  function isAutoincrement(field) {
3595
4084
  return isFunctionDefault(field.default) && field.default.name === "autoincrement";
3596
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
+ }
3597
4093
  function needsForeignKeysParam(targetModel, assocs) {
3598
4094
  return assocs.filter((a) => a.targetModel === targetModel).length > 1;
3599
4095
  }
@@ -3643,12 +4139,20 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap) {
3643
4139
  if (isPk) colArgs.push("primary_key=True");
3644
4140
  if (isPk && isAutoincrement(field)) colArgs.push("autoincrement=True");
3645
4141
  if (field.isUnique) colArgs.push("unique=True");
4142
+ const uuidVersion = uuidDefaultVersion(field);
3646
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())");
3647
4148
  else if (!isPk || isAutoincrement(field)) {
3648
4149
  const defaultVal = formatDefault(field.default);
3649
4150
  if (defaultVal !== null && !isPk) colArgs.push(`default=${defaultVal}`);
3650
4151
  }
3651
- if (field.isUpdatedAt) colArgs.push("onupdate=func.now()");
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
+ }
3652
4156
  if (colArgs.length === 0) return ` ${attrName}: Mapped[${typeHint}]`;
3653
4157
  return ` ${attrName}: Mapped[${typeHint}] = mapped_column(${colArgs.join(", ")})`;
3654
4158
  }
@@ -3659,7 +4163,7 @@ function generateTableArgs(model, indexes) {
3659
4163
  }).join(", ")})`;
3660
4164
  });
3661
4165
  const indexConstraints = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
3662
- 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) => {
3663
4167
  return `"${model.fields.find((mf) => mf.name === f.name)?.dbName ?? makeSnakeCase(f.name)}"`;
3664
4168
  }).join(", ")})`;
3665
4169
  });
@@ -3680,7 +4184,7 @@ function generateBelongsToRelationships(associations, model, allModels) {
3680
4184
  const fkClause = needsForeignKeysParam(assoc.targetModel, associations.belongsTo) ? `foreign_keys=[${snakeFk}], ` : "";
3681
4185
  const pkField = model.fields.find((f) => f.isId);
3682
4186
  const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${pkField.dbName ?? makeSnakeCase(pkField.name)}], ` : "";
3683
- 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}")`;
3684
4188
  });
3685
4189
  }
3686
4190
  function generateHasManyRelationships(associations, model, allModels) {
@@ -3702,15 +4206,14 @@ function generateHasOneRelationships(associations, model, allModels) {
3702
4206
  const needsFkParam = targetModel ? needsForeignKeysParam(model.name, getAssociations(targetModel, allModels).belongsTo) : false;
3703
4207
  const targetFkSnake = makeSnakeCase(assoc.foreignKey);
3704
4208
  const fkClause = needsFkParam ? `foreign_keys="${assoc.targetModel}.${targetFkSnake}", ` : "";
3705
- return ` ${snakeName}: Mapped["${assoc.targetModel}"] = relationship(${fkClause}back_populates="${backPop}", uselist=False)`;
4209
+ return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${assoc.targetModel}"]` : `"${assoc.targetModel}"`}] = relationship(${fkClause}back_populates="${backPop}")`;
3706
4210
  });
3707
4211
  }
3708
4212
  function generateManyToManyRelationships(associations, model, allModels, m2mTables) {
3709
4213
  return associations.manyToMany.map((assoc) => {
3710
4214
  const snakeName = makeSnakeCase(assoc.name);
3711
4215
  const backPop = findM2MBackPopulates(assoc.targetModel, model.name, assoc.relationName, allModels);
3712
- const [leftName, rightName] = model.name < assoc.targetModel ? [model.name, assoc.targetModel] : [assoc.targetModel, model.name];
3713
- 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);
3714
4217
  return ` ${snakeName}: Mapped[list["${assoc.targetModel}"]] = relationship(secondary=${secondaryVar}, back_populates="${backPop}")`;
3715
4218
  });
3716
4219
  }
@@ -3754,10 +4257,13 @@ function collectGlobalImports(models, _enums, indexes, m2mTables) {
3754
4257
  const needsDecimal = models.some((m) => m.fields.some((f) => f.type === "Decimal"));
3755
4258
  const needsDatetime = models.some((m) => m.fields.some((f) => f.type === "DateTime"));
3756
4259
  const needsUuid = models.some((m) => m.fields.some((f) => {
4260
+ if (uuidDefaultVersion(f) === 4) return true;
3757
4261
  if (!f.nativeType) return false;
3758
4262
  const [n] = f.nativeType;
3759
4263
  return n === "Uuid";
3760
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)));
3761
4267
  const needsDate = models.some((m) => m.fields.some((f) => {
3762
4268
  if (!f.nativeType) return false;
3763
4269
  const [n] = f.nativeType;
@@ -3821,6 +4327,8 @@ function collectGlobalImports(models, _enums, indexes, m2mTables) {
3821
4327
  if (needsTime) dtParts.push("time as time_type");
3822
4328
  if (dtParts.length > 0) lines.push(`from datetime import ${dtParts.join(", ")}`);
3823
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");
3824
4332
  return lines;
3825
4333
  }
3826
4334
  //#endregion
@@ -4070,6 +4578,10 @@ async function zod(options) {
4070
4578
  //#endregion
4071
4579
  //#region src/bin/index.ts
4072
4580
  const GENERATORS = {
4581
+ activerecord: {
4582
+ prettyName: "Hekireki-ActiveRecord",
4583
+ handler: activerecord
4584
+ },
4073
4585
  ajv: {
4074
4586
  prettyName: "Hekireki-AJV",
4075
4587
  handler: ajv
@@ -4098,6 +4610,10 @@ const GENERATORS = {
4098
4610
  prettyName: "Hekireki-Effect",
4099
4611
  handler: effect
4100
4612
  },
4613
+ eloquent: {
4614
+ prettyName: "Hekireki-Eloquent",
4615
+ handler: eloquent
4616
+ },
4101
4617
  gorm: {
4102
4618
  prettyName: "Hekireki-GORM",
4103
4619
  handler: gorm