hekireki 0.10.2 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +179 -1189
  2. package/dist/bin/activerecord.js +1 -1
  3. package/dist/bin/ajv.js +1 -1
  4. package/dist/bin/arktype.js +1 -1
  5. package/dist/bin/atlas.js +1 -1
  6. package/dist/bin/django.js +1 -1
  7. package/dist/bin/drizzle.js +1 -1
  8. package/dist/bin/ecto.js +1 -1
  9. package/dist/bin/effect.js +1 -1
  10. package/dist/bin/eloquent.js +1 -1
  11. package/dist/bin/er.js +6 -0
  12. package/dist/bin/gorm.js +1 -1
  13. package/dist/bin/hekireki.js +176 -0
  14. package/dist/bin/kysely.js +1 -1
  15. package/dist/bin/pydantic.js +1 -1
  16. package/dist/bin/sea-orm.js +1 -1
  17. package/dist/bin/sqlalchemy.js +1 -1
  18. package/dist/bin/typebox.js +1 -1
  19. package/dist/bin/valibot.js +1 -1
  20. package/dist/bin/zod.js +1 -1
  21. package/dist/{bin-9aHkP_Bs.js → bin-CPb5ZV8W.js} +1436 -1751
  22. package/dist/file-yN0By3gn.js +48 -0
  23. package/dist/schema-DwMNeEei.js +823 -0
  24. package/dist/start-Blp4k61D.js +5764 -0
  25. package/dist/studio/assets/cells-lAj-v64A.js +2 -0
  26. package/dist/studio/assets/codicon-Brq4_Ui5.ttf +0 -0
  27. package/dist/studio/assets/docs-CpeTt3O2.js +34 -0
  28. package/dist/studio/assets/editor.worker-D9zwrD0f.js +30 -0
  29. package/dist/studio/assets/enums._name-My5PypWw.js +1 -0
  30. package/dist/studio/assets/hooks-CiUANSpJ.js +1 -0
  31. package/dist/studio/assets/index-C4wWEcwe.js +188 -0
  32. package/dist/studio/assets/index-ZSt1ppSG.css +2 -0
  33. package/dist/studio/assets/labels-DBXIkmbm.js +1 -0
  34. package/dist/studio/assets/lazyRouteComponent-DmCXXiGp.js +1 -0
  35. package/dist/studio/assets/models._name-oUX64rwK.js +1 -0
  36. package/dist/studio/assets/not-found-DxAsuyR5.js +1 -0
  37. package/dist/studio/assets/prisma-Bk53qnxm.js +891 -0
  38. package/dist/studio/assets/prisma-C2rAM-pV.css +1 -0
  39. package/dist/studio/assets/routes-ZmrohHNP.js +1 -0
  40. package/dist/studio/assets/schema-gate-DJ_-6NYR.js +1 -0
  41. package/dist/studio/assets/schema-view-BaoCWAL8.js +8 -0
  42. package/dist/studio/assets/sql-DpzkSc6F.js +1 -0
  43. package/dist/studio/assets/useMatch-D73HO_WB.js +1 -0
  44. package/dist/studio/index.html +16 -0
  45. package/package.json +55 -27
  46. package/dist/bin/dbml.js +0 -6
  47. package/dist/bin/docs.js +0 -6
  48. package/dist/bin/mermaid-er.d.ts +0 -1
  49. package/dist/bin/mermaid-er.js +0 -6
  50. package/dist/cli/index.d.ts +0 -138
  51. package/dist/cli/index.js +0 -134
  52. /package/dist/bin/{dbml.d.ts → er.d.ts} +0 -0
  53. /package/dist/bin/{docs.d.ts → hekireki.d.ts} +0 -0
package/README.md CHANGED
@@ -2,40 +2,17 @@
2
2
 
3
3
  # Hekireki
4
4
 
5
- **[Hekireki](https://www.npmjs.com/package/hekireki)** is a tool that generates validation schemas, ORM models, and ER diagrams from [Prisma](https://www.prisma.io/) schemas — supporting TypeScript, Python, Go, Rust, Elixir, Ruby, and PHP.
5
+ **[Hekireki](https://www.npmjs.com/package/hekireki)** generates validation schemas, ORM models and
6
+ ER diagrams from a [Prisma](https://www.prisma.io/) schema — for TypeScript, Python, Go, Rust,
7
+ Elixir, Ruby and PHP — and opens the schema, its documentation and its data in the browser with
8
+ [Hekireki Studio](#studio).
6
9
 
7
10
  ## Features
8
11
 
9
- ### TypeScript Validation Libraries
10
-
11
- - 💎 Automatically generates [Zod](https://zod.dev/) schemas from your Prisma schema
12
- - 🤖 Automatically generates [Valibot](https://valibot.dev/) schemas from your Prisma schema
13
- - 🏹 Automatically generates [ArkType](https://arktype.io/) schemas from your Prisma schema
14
- - ⚡ Automatically generates [Effect Schema](https://effect.website/docs/schema/introduction/) from your Prisma schema
15
- - 📦 Automatically generates [TypeBox](https://github.com/sinclairzx81/typebox) schemas from your Prisma schema
16
- - 📋 Automatically generates [AJV](https://ajv.js.org/)-compatible JSON Schema objects from your Prisma schema
17
-
18
- ### Python Validation
19
-
20
- - 🐍 Automatically generates [Pydantic](https://docs.pydantic.dev/) v2 models from your Prisma schema — with `@p.` field annotations, `Literal` enums, `@p.ConfigDict(...)` model config passthrough (`extra='forbid'` / `'ignore'` / `'allow'` and any other `ConfigDict` arguments), and `relation = true` for `<Model>Relations` subclasses
21
-
22
- ### ORM / Schema Generation (Multi-Language)
23
-
24
- - 🗄️ Automatically generates [Drizzle ORM](https://orm.drizzle.team/) table schemas and relations from your Prisma schema
25
- - 🐟 Automatically generates [Kysely](https://kysely.dev/) type definitions (`DB` interface) from your Prisma schema — with database-side-only `Generated` columns, enum value unions, `@map`/`@@map` support, and implicit m2m join tables
26
- - 🐍 Automatically generates [SQLAlchemy](https://www.sqlalchemy.org/) models (Python) — with `Mapped[T]` type hints, relationships, enums, composite keys, and index support
27
- - 🎸 Automatically generates [Django ORM](https://www.djangoproject.com/) models (Python, Django ≥ 5.2) — with `ForeignKey` / `OneToOneField` / `ManyToManyField` relations (`related_name` from the Prisma back-relation), `TextChoices` enums, composite primary keys (`CompositePrimaryKey`), migration-serializable defaults, `db_default` for `now()` / `dbgenerated(...)`, and `Meta` constraints / indexes
28
- - 🐹 Automatically generates [GORM](https://gorm.io/) models (Go) — with struct tags, JSON tags, relationships, enums, composite keys, and index support
29
- - 🦀 Automatically generates [Sea-ORM](https://www.sea-ql.org/SeaORM/) entities (Rust) — with `DeriveEntityModel`, relations, enums, serde support, and `rename_all`
30
- - 🧪 Generates [Ecto](https://hexdocs.pm/ecto/Ecto.Schema.html) schemas (Elixir) — with associations (`belongs_to`, `has_many`, `has_one`), composite primary keys, `@type t` typespecs, array fields, `@@map`/`@map` support, and `@moduledoc`
31
- - 💎 Generates [Active Record](https://guides.rubyonrails.org/active_record_basics.html) models (Ruby on Rails) — with associations (`belongs_to`, `has_one`, `has_many`, `has_and_belongs_to_many`), enums, composite primary keys, and `@@map`/`@map` support
32
- - 🐘 Generates [Eloquent](https://laravel.com/docs/eloquent) models (Laravel / PHP) — with relations (`belongsTo`, `hasOne`, `hasMany`, `belongsToMany`), `$fillable`, `$casts`, string-backed PHP enums, timestamp constants, and `@@map`/`@map` support
33
- - 🌍 Generates [Atlas](https://atlasgo.io/) HCL database schemas — with native `@db.*` type mapping (PostgreSQL / MySQL / SQLite), enum blocks, defaults (including `dbgenerated(...)` and scalar-list defaults), foreign keys with Prisma's referential-action defaults, unique / descending / fulltext indexes, implicit m2m join tables, and `@@schema` support — output is `atlas schema fmt` canonical
34
-
35
- ### Diagrams & Documentation
36
-
37
- - 📊 Creates [Mermaid](https://mermaid.js.org/) ER diagrams with PK/FK markers
38
- - 📝 Generates [DBML](https://dbml.dbdiagram.io/) (Database Markup Language) files and **PNG** ER diagrams via [dbml-renderer](https://github.com/softwaretechnik-berlin/dbml-renderer) — output format is determined by the file extension (`.dbml` or `.png`)
12
+ - **Validation schemas** — [Zod](https://zod.dev/), [Valibot](https://valibot.dev/), [ArkType](https://arktype.io/), [Effect Schema](https://effect.website/docs/schema/introduction/), [TypeBox](https://github.com/sinclairzx81/typebox), [AJV](https://ajv.js.org/) (JSON Schema) and [Pydantic](https://docs.pydantic.dev/) v2, written from the `///` [annotations](#annotations) on each field
13
+ - **ORM models and DDL** — [Drizzle](https://orm.drizzle.team/), [Kysely](https://kysely.dev/), [SQLAlchemy](https://www.sqlalchemy.org/), [Django](https://www.djangoproject.com/), [GORM](https://gorm.io/), [Sea-ORM](https://www.sea-ql.org/SeaORM/), [Ecto](https://hexdocs.pm/ecto/Ecto.Schema.html), [Active Record](https://guides.rubyonrails.org/active_record_basics.html), [Eloquent](https://laravel.com/docs/eloquent) and [Atlas](https://atlasgo.io/) HCL — with relations, enums, composite keys, indexes and `@@map` / `@map` throughout
14
+ - **ER diagrams** — [Mermaid](https://mermaid.js.org/), [DBML](https://dbml.dbdiagram.io/), PNG and SVG from one generator block, with crow's-foot cardinality and `PK` / `FK` / `UK` markers
15
+ - **[Hekireki Studio](#studio)** — the ER diagram, a reference docs page, every model's data, a Prisma editor and a SQL console, live from `schema.prisma`
39
16
 
40
17
  ## Installation
41
18
 
@@ -45,7 +22,9 @@ npm install -D hekireki
45
22
 
46
23
  ## Usage
47
24
 
48
- Prepare `schema.prisma`:
25
+ Each generator is a `generator` block in `schema.prisma`. `output` is **required**: point it at a
26
+ directory to get the default file name of that generator, or at a path with an extension to name
27
+ the file yourself.
49
28
 
50
29
  ```prisma
51
30
  datasource db {
@@ -60,188 +39,31 @@ generator Hekireki-Zod {
60
39
  relation = true
61
40
  }
62
41
 
63
- generator Hekireki-Valibot {
64
- provider = "hekireki-valibot"
65
- output = "./valibot"
66
- type = true
67
- comment = true
68
- relation = true
69
- }
70
-
71
- generator Hekireki-ArkType {
72
- provider = "hekireki-arktype"
73
- output = "./arktype"
74
- type = true
75
- comment = true
76
- relation = true
77
- }
78
-
79
- generator Hekireki-Effect {
80
- provider = "hekireki-effect"
81
- output = "./effect"
82
- type = true
83
- comment = true
84
- relation = true
85
- }
86
-
87
- generator Hekireki-TypeBox {
88
- provider = "hekireki-typebox"
89
- output = "./typebox"
90
- type = true
91
- comment = true
92
- relation = true
93
- }
94
-
95
- generator Hekireki-AJV {
96
- provider = "hekireki-ajv"
97
- output = "./ajv"
98
- type = true
99
- comment = true
100
- relation = true
101
- }
102
-
103
- generator Hekireki-Pydantic {
104
- provider = "hekireki-pydantic"
105
- output = "./pydantic"
106
- comment = true
107
- }
108
-
109
- generator Hekireki-Drizzle {
110
- provider = "hekireki-drizzle"
111
- output = "./drizzle"
112
- }
113
-
114
- generator Hekireki-Kysely {
115
- provider = "hekireki-kysely"
116
- output = "./kysely"
117
- }
118
-
119
- generator Hekireki-Atlas {
120
- provider = "hekireki-atlas"
121
- output = "./atlas"
122
- }
123
-
124
- generator Hekireki-SQLAlchemy {
125
- provider = "hekireki-sqlalchemy"
126
- output = "./sqlalchemy"
127
- }
128
-
129
- generator Hekireki-Django {
130
- provider = "hekireki-django"
131
- output = "./django"
132
- }
133
-
134
- generator Hekireki-GORM {
135
- provider = "hekireki-gorm"
136
- output = "./gorm"
137
- package = "model"
138
- }
139
-
140
- generator Hekireki-SeaORM {
141
- provider = "hekireki-sea-orm"
142
- output = "./sea_orm"
143
- renameAll = "camelCase"
144
- }
145
-
146
- generator Hekireki-Ecto {
147
- provider = "hekireki-ecto"
148
- output = "./ecto"
149
- app = "DBSchema"
150
- }
151
-
152
- generator Hekireki-ActiveRecord {
153
- provider = "hekireki-activerecord"
154
- output = "./activerecord"
155
- }
156
-
157
- generator Hekireki-Eloquent {
158
- provider = "hekireki-eloquent"
159
- output = "./eloquent"
160
- namespace = "App.Models"
161
- }
162
-
163
- generator Hekireki-ER {
164
- provider = "hekireki-mermaid-er"
165
- output = "./mermaid-er"
166
- }
167
-
168
- generator Hekireki-DBML {
169
- provider = "hekireki-dbml"
170
- output = "docs/schema.dbml"
171
- }
172
-
173
- generator Hekireki-Docs {
174
- provider = "hekireki-docs"
175
- output = "./docs"
176
- }
177
-
178
42
  model User {
179
43
  /// Primary key
180
44
  /// @z.uuid()
181
- /// @v.pipe(v.string(), v.uuid())
182
- /// @a."string.uuid"
183
- /// @e.Schema.UUID
184
- /// @t.Type.String({ format: 'uuid' })
185
- /// @j.{ type: 'string' as const, format: 'uuid' as const }
186
- /// @p.UUID4
187
45
  id String @id @default(uuid())
188
46
  /// Display name
189
47
  /// @z.string().min(1).max(50)
190
- /// @v.pipe(v.string(), v.minLength(1), v.maxLength(50))
191
- /// @a."1 <= string <= 50"
192
- /// @e.Schema.String.pipe(Schema.minLength(1), Schema.maxLength(50))
193
- /// @t.Type.String({ minLength: 1, maxLength: 50 })
194
- /// @j.{ type: 'string' as const, minLength: 1, maxLength: 50 }
195
- /// @p.Annotated[str, StringConstraints(min_length=1, max_length=50)]
196
48
  name String
197
- /// One-to-many relation to Post
198
49
  posts Post[]
199
50
  }
200
51
 
201
52
  model Post {
202
53
  /// Primary key
203
54
  /// @z.uuid()
204
- /// @v.pipe(v.string(), v.uuid())
205
- /// @a."string.uuid"
206
- /// @e.Schema.UUID
207
- /// @t.Type.String({ format: 'uuid' })
208
- /// @j.{ type: 'string' as const, format: 'uuid' as const }
209
- /// @p.UUID4
210
- id String @id @default(uuid())
55
+ id String @id @default(uuid())
211
56
  /// Article title
212
57
  /// @z.string().min(1).max(100)
213
- /// @v.pipe(v.string(), v.minLength(1), v.maxLength(100))
214
- /// @a."1 <= string <= 100"
215
- /// @e.Schema.String.pipe(Schema.minLength(1), Schema.maxLength(100))
216
- /// @t.Type.String({ minLength: 1, maxLength: 100 })
217
- /// @j.{ type: 'string' as const, minLength: 1, maxLength: 100 }
218
- /// @p.Annotated[str, StringConstraints(min_length=1, max_length=100)]
219
- title String
220
- /// Body content (no length limit)
221
- /// @z.string()
222
- /// @v.string()
223
- /// @a."string"
224
- /// @e.Schema.String
225
- /// @t.Type.String()
226
- /// @j.{ type: 'string' as const }
227
- content String
58
+ title String
228
59
  /// Foreign key referencing User.id
229
60
  /// @z.uuid()
230
- /// @v.pipe(v.string(), v.uuid())
231
- /// @a."string.uuid"
232
- /// @e.Schema.UUID
233
- /// @t.Type.String({ format: 'uuid' })
234
- /// @j.{ type: 'string' as const, format: 'uuid' as const }
235
- /// @p.UUID4
236
- userId String
237
- /// Prisma relation definition
238
- user User @relation(fields: [userId], references: [id])
61
+ userId String
62
+ user User @relation(fields: [userId], references: [id])
239
63
  }
240
64
  ```
241
65
 
242
- ## Generated Output
243
-
244
- ### Zod
66
+ `npx prisma generate` writes `./zod/index.ts`:
245
67
 
246
68
  ```ts
247
69
  import * as z from 'zod'
@@ -268,10 +90,6 @@ export const PostSchema = z.object({
268
90
  * Article title
269
91
  */
270
92
  title: z.string().min(1).max(100),
271
- /**
272
- * Body content (no length limit)
273
- */
274
- content: z.string(),
275
93
  /**
276
94
  * Foreign key referencing User.id
277
95
  */
@@ -295,861 +113,35 @@ export const PostRelationsSchema = z.object({
295
113
  export type PostRelations = z.infer<typeof PostRelationsSchema>
296
114
  ```
297
115
 
298
- ### Valibot
116
+ Every other generator reads the same schema. What each one writes is easiest to read as real
117
+ output: [`example/schema.prisma`](https://github.com/nakita628/hekireki/blob/main/example/schema.prisma)
118
+ exercises all of them at once — enums, `@@map`, composite keys, self-relations, implicit
119
+ many-to-many, native `@db.*` types — and the output of every generator for it is committed under
120
+ [`example/generated/`](https://github.com/nakita628/hekireki/tree/main/example/generated).
299
121
 
300
- ```ts
301
- import * as v from 'valibot'
122
+ ## Annotations
302
123
 
303
- export const UserSchema = v.object({
304
- /**
305
- * Primary key
306
- */
307
- id: v.pipe(v.string(), v.uuid()),
308
- /**
309
- * Display name
310
- */
311
- name: v.pipe(v.string(), v.minLength(1), v.maxLength(50)),
312
- })
124
+ A `///` comment on a field is its documentation. A `///` line that begins with one of the prefixes
125
+ below is the validation the matching generator emits for that field, used verbatim:
313
126
 
314
- export type User = v.InferOutput<typeof UserSchema>
127
+ | Prefix | Generator | Example |
128
+ | ------ | ----------------- | ----------------------------------------- |
129
+ | `@z.` | Zod | `/// @z.string().min(1).max(50)` |
130
+ | `@v.` | Valibot | `/// @v.pipe(v.string(), v.minLength(1))` |
131
+ | `@a.` | ArkType | `/// @a."1 <= string <= 50"` |
132
+ | `@e.` | Effect Schema | `/// @e.Schema.UUID` |
133
+ | `@t.` | TypeBox | `/// @t.Type.String({ format: 'uuid' })` |
134
+ | `@j.` | AJV / JSON Schema | `/// @j.{ type: 'string' as const }` |
135
+ | `@p.` | Pydantic | `/// @p.EmailStr` |
315
136
 
316
- export const PostSchema = v.object({
317
- /**
318
- * Primary key
319
- */
320
- id: v.pipe(v.string(), v.uuid()),
321
- /**
322
- * Article title
323
- */
324
- title: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
325
- /**
326
- * Body content (no length limit)
327
- */
328
- content: v.string(),
329
- /**
330
- * Foreign key referencing User.id
331
- */
332
- userId: v.pipe(v.string(), v.uuid()),
333
- })
334
-
335
- export type Post = v.InferOutput<typeof PostSchema>
336
-
337
- export const UserRelationsSchema = v.object({
338
- ...UserSchema.entries,
339
- posts: v.array(PostSchema),
340
- })
341
-
342
- export type UserRelations = v.InferOutput<typeof UserRelationsSchema>
343
-
344
- export const PostRelationsSchema = v.object({
345
- ...PostSchema.entries,
346
- user: UserSchema,
347
- })
348
-
349
- export type PostRelations = v.InferOutput<typeof PostRelationsSchema>
350
- ```
351
-
352
- ### ArkType
137
+ A field without an annotation falls back to the Prisma type. `@p.ConfigDict(...)` on a **model** is
138
+ passed through as Pydantic's `model_config`.
353
139
 
354
- ```ts
355
- import { type } from 'arktype'
356
-
357
- export const UserSchema = type({
358
- /**
359
- * Primary key
360
- */
361
- id: 'string.uuid',
362
- /**
363
- * Display name
364
- */
365
- name: '1 <= string <= 50',
366
- })
367
-
368
- export type User = typeof UserSchema.infer
369
-
370
- export const PostSchema = type({
371
- /**
372
- * Primary key
373
- */
374
- id: 'string.uuid',
375
- /**
376
- * Article title
377
- */
378
- title: '1 <= string <= 100',
379
- /**
380
- * Body content (no length limit)
381
- */
382
- content: 'string',
383
- /**
384
- * Foreign key referencing User.id
385
- */
386
- userId: 'string.uuid',
387
- })
388
-
389
- export type Post = typeof PostSchema.infer
390
-
391
- export const UserRelationsSchema = type({ ...UserSchema.t, posts: PostSchema.array() })
392
-
393
- export type UserRelations = typeof UserRelationsSchema.infer
394
-
395
- export const PostRelationsSchema = type({ ...PostSchema.t, user: UserSchema })
396
-
397
- export type PostRelations = typeof PostRelationsSchema.infer
398
- ```
399
-
400
- ### Effect Schema
401
-
402
- ```ts
403
- import { Schema } from 'effect'
404
-
405
- export const UserSchema = Schema.Struct({
406
- /**
407
- * Primary key
408
- */
409
- id: Schema.UUID,
410
- /**
411
- * Display name
412
- */
413
- name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(50)),
414
- })
415
-
416
- export type User = typeof UserSchema.Type
417
-
418
- export const PostSchema = Schema.Struct({
419
- /**
420
- * Primary key
421
- */
422
- id: Schema.UUID,
423
- /**
424
- * Article title
425
- */
426
- title: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(100)),
427
- /**
428
- * Body content (no length limit)
429
- */
430
- content: Schema.String,
431
- /**
432
- * Foreign key referencing User.id
433
- */
434
- userId: Schema.UUID,
435
- })
436
-
437
- export type Post = typeof PostSchema.Type
438
-
439
- export const UserRelationsSchema = Schema.Struct({
440
- ...UserSchema.fields,
441
- posts: Schema.Array(PostSchema),
442
- })
443
-
444
- export type UserRelations = typeof UserRelationsSchema.Type
445
-
446
- export const PostRelationsSchema = Schema.Struct({ ...PostSchema.fields, user: UserSchema })
447
-
448
- export type PostRelations = typeof PostRelationsSchema.Type
449
- ```
450
-
451
- ### TypeBox
452
-
453
- ```ts
454
- import { type Static, Type } from '@sinclair/typebox'
455
-
456
- export const UserSchema = Type.Object({
457
- /**
458
- * Primary key
459
- */
460
- id: Type.String({ format: 'uuid' }),
461
- /**
462
- * Display name
463
- */
464
- name: Type.String({ minLength: 1, maxLength: 50 }),
465
- })
466
-
467
- export type User = Static<typeof UserSchema>
468
-
469
- export const PostSchema = Type.Object({
470
- /**
471
- * Primary key
472
- */
473
- id: Type.String({ format: 'uuid' }),
474
- /**
475
- * Article title
476
- */
477
- title: Type.String({ minLength: 1, maxLength: 100 }),
478
- /**
479
- * Body content (no length limit)
480
- */
481
- content: Type.String(),
482
- /**
483
- * Foreign key referencing User.id
484
- */
485
- userId: Type.String({ format: 'uuid' }),
486
- })
487
-
488
- export type Post = Static<typeof PostSchema>
489
-
490
- export const UserRelationsSchema = Type.Object({
491
- ...UserSchema.properties,
492
- posts: Type.Array(PostSchema),
493
- })
494
-
495
- export type UserRelations = Static<typeof UserRelationsSchema>
496
-
497
- export const PostRelationsSchema = Type.Object({
498
- ...PostSchema.properties,
499
- user: UserSchema,
500
- })
501
-
502
- export type PostRelations = Static<typeof PostRelationsSchema>
503
- ```
504
-
505
- ### AJV
506
-
507
- ```ts
508
- import type { FromSchema } from 'json-schema-to-ts'
509
-
510
- export const UserSchema = {
511
- type: 'object' as const,
512
- properties: {
513
- /**
514
- * Primary key
515
- */
516
- id: { type: 'string' as const, format: 'uuid' as const },
517
- /**
518
- * Display name
519
- */
520
- name: { type: 'string' as const, minLength: 1, maxLength: 50 },
521
- },
522
- required: ['id', 'name'] as const,
523
- additionalProperties: false,
524
- } as const
525
-
526
- export type User = FromSchema<typeof UserSchema>
527
-
528
- export const PostSchema = {
529
- type: 'object' as const,
530
- properties: {
531
- /**
532
- * Primary key
533
- */
534
- id: { type: 'string' as const, format: 'uuid' as const },
535
- /**
536
- * Article title
537
- */
538
- title: { type: 'string' as const, minLength: 1, maxLength: 100 },
539
- /**
540
- * Body content (no length limit)
541
- */
542
- content: { type: 'string' as const },
543
- /**
544
- * Foreign key referencing User.id
545
- */
546
- userId: { type: 'string' as const, format: 'uuid' as const },
547
- },
548
- required: ['id', 'title', 'content', 'userId'] as const,
549
- additionalProperties: false,
550
- } as const
551
-
552
- export type Post = FromSchema<typeof PostSchema>
553
-
554
- export const UserRelationsSchema = {
555
- type: 'object' as const,
556
- properties: {
557
- ...UserSchema.properties,
558
- posts: { type: 'array' as const, items: PostSchema },
559
- },
560
- additionalProperties: false,
561
- } as const
562
-
563
- export type UserRelations = FromSchema<typeof UserRelationsSchema>
564
-
565
- export const PostRelationsSchema = {
566
- type: 'object' as const,
567
- properties: {
568
- ...PostSchema.properties,
569
- user: UserSchema,
570
- },
571
- additionalProperties: false,
572
- } as const
573
-
574
- export type PostRelations = FromSchema<typeof PostRelationsSchema>
575
- ```
576
-
577
- ### Drizzle
578
-
579
- ```ts
580
- import { sqliteTable, text } from 'drizzle-orm/sqlite-core'
581
- import { relations } from 'drizzle-orm'
582
-
583
- export const user = sqliteTable('user', {
584
- id: text('id')
585
- .primaryKey()
586
- .$defaultFn(() => crypto.randomUUID()),
587
- name: text('name').notNull(),
588
- })
589
-
590
- export const post = sqliteTable('post', {
591
- id: text('id')
592
- .primaryKey()
593
- .$defaultFn(() => crypto.randomUUID()),
594
- title: text('title').notNull(),
595
- content: text('content').notNull(),
596
- userId: text('userId')
597
- .notNull()
598
- .references(() => user.id),
599
- })
600
-
601
- export const userRelations = relations(user, ({ many }) => ({ posts: many(post) }))
602
-
603
- export const postRelations = relations(post, ({ one }) => ({
604
- user: one(user, { fields: [post.userId], references: [user.id] }),
605
- }))
606
- ```
607
-
608
- ### Kysely
609
-
610
- Pure type definitions for the [Kysely](https://kysely.dev/) query builder. The `DB` interface is keyed by the actual database table names (`@@map` respected), columns use `@map`-ped names, and enums become value unions of their `@map`-ped database values. Reach for Kysely's own `Selectable` / `Insertable` / `Updateable` wrappers when you need to name a row type; query results are inferred and need no annotation.
611
-
612
- Only **database-side** defaults become `Generated<T>`. `autoincrement()`, `now()` and `dbgenerated(...)` are evaluated by the database, so they are optional on insert; `uuid()`, `cuid()`, `ulid()` and `nanoid()` are evaluated by the Prisma Client and leave the column without a DDL default, so a raw Kysely insert must still supply them.
613
-
614
- ```ts
615
- export interface User {
616
- id: string
617
- name: string
618
- }
619
-
620
- export interface Post {
621
- id: string
622
- title: string
623
- content: string
624
- userId: string
625
- }
626
-
627
- export interface DB {
628
- User: User
629
- Post: Post
630
- }
631
- ```
632
-
633
- Both ids above are `@default(uuid())`, which Prisma evaluates in the client — hence plain `string`, required on insert. A database-side default instead emits `Generated<T>` (and, for `DateTime`, the `Timestamp` alias), which Kysely makes optional on insert:
140
+ `/// @relation <Parent>.<field> <Child>.<field> <cardinality>` on a **model** declares a relation
141
+ that has no physical foreign key — it is drawn in the Mermaid, DBML and image output (dashed in the
142
+ drawing) even though the column carries no `@relation(...)`:
634
143
 
635
144
  ```prisma
636
- model Comment {
637
- id Int @id @default(autoincrement())
638
- createdAt DateTime @default(now())
639
- }
640
- ```
641
-
642
- ```ts
643
- import type { ColumnType } from 'kysely'
644
-
645
- export type Generated<T> =
646
- T extends ColumnType<infer S, infer I, infer U>
647
- ? ColumnType<S, I | undefined, U>
648
- : ColumnType<T, T | undefined, T>
649
-
650
- export type Timestamp = ColumnType<Date, Date | string, Date | string>
651
-
652
- export interface Comment {
653
- id: Generated<number>
654
- createdAt: Generated<Timestamp>
655
- }
656
- ```
657
-
658
- ```ts
659
- import { Kysely, type Insertable } from 'kysely'
660
- import type { DB, Post } from './kysely/types'
661
-
662
- declare const db: Kysely<DB>
663
- declare const userId: string
664
-
665
- // Query results are inferred — no annotation needed.
666
- const posts = await db.selectFrom('Post').selectAll().execute()
667
-
668
- const draft: Insertable<Post> = {
669
- id: crypto.randomUUID(),
670
- title: 'Hello',
671
- content: '...',
672
- userId,
673
- }
674
- await db.insertInto('Post').values(draft).execute()
675
- ```
676
-
677
- ### Atlas
678
-
679
- A declarative [Atlas](https://atlasgo.io/) HCL schema (`schema.hcl`). Table and column names use their `@@map`/`@map` database names, foreign keys and indexes follow Prisma's naming conventions (`<table>_<columns>_fkey` / `_key` / `_idx`), referential actions fall back to Prisma's defaults (`onUpdate: Cascade`, `onDelete: Restrict` for required and `SetNull` for optional relations), and client-side defaults such as `uuid()` and `cuid()` emit no database `DEFAULT` — the file describes exactly what `prisma migrate` would create. The output is already `atlas schema fmt` canonical.
680
-
681
- The schema label defaults to `public` (PostgreSQL / MySQL) or `main` (SQLite); on MySQL, set `schemaName` to your database name since MySQL schemas are databases.
682
-
683
- > [!WARNING]
684
- > Declarative `atlas schema apply` drops whatever is missing from the HCL, and three things can never appear in it: Prisma's own `_prisma_migrations` table (exclude it with `--exclude '_prisma_migrations'`), and columns or tables marked `@ignore`/`@@ignore` or typed `Unsupported(...)` — Prisma omits those from the DMMF that hekireki reads. When applying to an existing database, always dry-run first and keep Atlas's destructive-change linting enabled.
685
-
686
- Known limitations: the implicit m2m primary key is an unnamed constraint (Prisma names it `_X_AB_pkey`; the column set is identical, so this only surfaces as a constraint rename if you later hand the database back to `prisma migrate`), all enum blocks land in the default schema under `multiSchema` (Prisma exposes no schema for enums), Prisma's 63-byte truncation of very long constraint names is not reproduced, and removing or renaming enum values is a type rebuild in Atlas, as in any PostgreSQL workflow.
687
-
688
- ```hcl
689
- table "User" {
690
- schema = schema.main
691
- column "id" {
692
- null = false
693
- type = text
694
- }
695
- column "name" {
696
- null = false
697
- type = text
698
- }
699
- primary_key {
700
- columns = [column.id]
701
- }
702
- }
703
-
704
- table "Post" {
705
- schema = schema.main
706
- column "id" {
707
- null = false
708
- type = text
709
- }
710
- column "title" {
711
- null = false
712
- type = text
713
- }
714
- column "content" {
715
- null = false
716
- type = text
717
- }
718
- column "userId" {
719
- null = false
720
- type = text
721
- }
722
- primary_key {
723
- columns = [column.id]
724
- }
725
- foreign_key "Post_userId_fkey" {
726
- columns = [column.userId]
727
- ref_columns = [table.User.column.id]
728
- on_update = CASCADE
729
- on_delete = RESTRICT
730
- }
731
- }
732
-
733
- schema "main" {}
734
- ```
735
-
736
- ```bash
737
- # Apply the schema declaratively (dry-run first), or diff versioned migrations from it
738
- atlas schema apply --url "$DATABASE_URL" --to file://atlas/schema.hcl --exclude '_prisma_migrations' --dry-run
739
- atlas schema apply --url "$DATABASE_URL" --to file://atlas/schema.hcl --exclude '_prisma_migrations'
740
- atlas migrate diff --dev-url "docker://postgres/17/dev" --to file://atlas/schema.hcl
741
- ```
742
-
743
- ### Ecto
744
-
745
- Each model is output as a separate `.ex` file (1 model = 1 file), following Elixir conventions.
746
-
747
- ```elixir
748
- defmodule DBSchema.User do
749
- use Ecto.Schema
750
- @moduledoc false
751
-
752
- @primary_key {:id, :binary_id, autogenerate: true}
753
- @foreign_key_type :binary_id
754
-
755
- @type t :: %__MODULE__{
756
- id: Ecto.UUID.t(),
757
- name: String.t(),
758
- posts: [DBSchema.Post.t()]
759
- }
760
-
761
- schema "user" do
762
- field(:name, :string)
763
- has_many(:posts, DBSchema.Post, foreign_key: :user_id)
764
- end
765
- end
766
- ```
767
-
768
- ```elixir
769
- defmodule DBSchema.Post do
770
- use Ecto.Schema
771
- @moduledoc false
772
-
773
- @primary_key {:id, :binary_id, autogenerate: true}
774
- @foreign_key_type :binary_id
775
-
776
- @type t :: %__MODULE__{
777
- id: Ecto.UUID.t(),
778
- title: String.t(),
779
- content: String.t(),
780
- user: DBSchema.User.t() | nil
781
- }
782
-
783
- schema "post" do
784
- field(:title, :string)
785
- field(:content, :string)
786
- field(:user_id, :binary_id, source: :userId)
787
- belongs_to(:user, DBSchema.User, foreign_key: :user_id, define_field: false)
788
- end
789
- end
790
- ```
791
-
792
- ### Active Record
793
-
794
- Each model is output as a separate `.rb` file (1 model = 1 file), following Rails conventions. `class_name` and `foreign_key` are always spelled out so the generated associations never rely on Rails inflection. The generated code targets Rails 7.1+ (positional `enum` syntax, composite primary keys) and is continuously syntax-checked (`ruby -c`) and loaded against the real `activerecord` gem in CI.
795
-
796
- ```ruby
797
- class User < ApplicationRecord
798
- self.table_name = "user"
799
-
800
- attribute :id, default: -> { SecureRandom.uuid }
801
-
802
- has_many :posts, class_name: "Post", foreign_key: "userId"
803
- end
804
- ```
805
-
806
- ```ruby
807
- class Post < ApplicationRecord
808
- self.table_name = "post"
809
-
810
- attribute :id, default: -> { SecureRandom.uuid }
811
-
812
- belongs_to :user, class_name: "User", foreign_key: "userId"
813
- end
814
- ```
815
-
816
- ### Eloquent
817
-
818
- Each model is output as a separate `.php` file (1 model = 1 file, PSR-4 friendly). Prisma enums become string-backed PHP enums with matching `$casts` entries. The generated code targets PHP 8.1+ (backed enums) and is continuously syntax-checked (`php -l`) and loaded against the real `illuminate/database` package in CI. Composite primary keys are emitted as `protected $primaryKey = null;` because Eloquent has no native composite key support.
819
-
820
- ```php
821
- <?php
822
-
823
- namespace App\Models;
824
-
825
- use Illuminate\Database\Eloquent\Concerns\HasVersion4Uuids;
826
- use Illuminate\Database\Eloquent\Model;
827
- use Illuminate\Database\Eloquent\Relations\HasMany;
828
-
829
- class User extends Model
830
- {
831
- use HasVersion4Uuids;
832
-
833
- protected $table = 'user';
834
-
835
- protected $keyType = 'string';
836
-
837
- public $incrementing = false;
838
-
839
- public $timestamps = false;
840
-
841
- protected $fillable = [
842
- 'name',
843
- ];
844
-
845
- public function posts(): HasMany
846
- {
847
- return $this->hasMany(Post::class, 'userId');
848
- }
849
- }
850
- ```
851
-
852
- ```php
853
- <?php
854
-
855
- namespace App\Models;
856
-
857
- use Illuminate\Database\Eloquent\Concerns\HasVersion4Uuids;
858
- use Illuminate\Database\Eloquent\Model;
859
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
860
-
861
- class Post extends Model
862
- {
863
- use HasVersion4Uuids;
864
-
865
- protected $table = 'post';
866
-
867
- protected $keyType = 'string';
868
-
869
- public $incrementing = false;
870
-
871
- public $timestamps = false;
872
-
873
- protected $fillable = [
874
- 'title',
875
- 'content',
876
- 'userId',
877
- ];
878
-
879
- public function user(): BelongsTo
880
- {
881
- return $this->belongsTo(User::class, 'userId');
882
- }
883
- }
884
- ```
885
-
886
- ### SQLAlchemy
887
-
888
- ```python
889
- from sqlalchemy import ForeignKey
890
- from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
891
- import uuid as uuid_mod
892
-
893
-
894
- class Base(DeclarativeBase):
895
- pass
896
-
897
-
898
- class User(Base):
899
- __tablename__ = "user"
900
-
901
- id: Mapped[str] = mapped_column(primary_key=True, default=lambda: str(uuid_mod.uuid4()))
902
- name: Mapped[str]
903
-
904
- posts: Mapped[list["Post"]] = relationship(back_populates="user")
905
-
906
- class Post(Base):
907
- __tablename__ = "post"
908
-
909
- id: Mapped[str] = mapped_column(primary_key=True, default=lambda: str(uuid_mod.uuid4()))
910
- title: Mapped[str]
911
- content: Mapped[str]
912
- user_id: Mapped[str] = mapped_column(ForeignKey("user.id"))
913
-
914
- user: Mapped["User"] = relationship(back_populates="posts")
915
- ```
916
-
917
- ### Django
918
-
919
- [Django ORM](https://www.djangoproject.com/) models (Python, Django ≥ 5.2). The foreign-key scalar and its relation field collapse into a single `ForeignKey` (a unique FK becomes `OneToOneField`, an implicit m2m becomes `ManyToManyField` plus an explicit through model over Prisma's `_Join` table), `related_name` comes from the Prisma back-relation, and Prisma's implicit referential actions apply when none is given (`RESTRICT` for required, `SET_NULL` for optional). Enums become `TextChoices` storing the `@map`-ped values, composite `@@id` becomes `CompositePrimaryKey`, `@default(now())` / `dbgenerated(...)` become `db_default`, `@updatedAt` becomes `auto_now=True`, and every generated default is migration-serializable (module-level helper functions, never lambdas).
920
-
921
- ```python
922
- import uuid
923
-
924
- from django.db import models
925
-
926
-
927
- def uuid4_str() -> str:
928
- return str(uuid.uuid4())
929
-
930
-
931
- class User(models.Model):
932
- id = models.TextField(primary_key=True, default=uuid4_str)
933
- name = models.TextField()
934
-
935
- class Meta:
936
- db_table = "user"
937
-
938
-
939
- class Post(models.Model):
940
- id = models.TextField(primary_key=True, default=uuid4_str)
941
- title = models.TextField()
942
- content = models.TextField()
943
- user = models.ForeignKey("User", on_delete=models.RESTRICT, related_name="posts", db_index=False)
944
-
945
- class Meta:
946
- db_table = "post"
947
- ```
948
-
949
- Names follow the same rule as the other ORM generators: a table or column is `@@map` / `@map` when given, otherwise the `snake_case` of the Prisma name. Prisma itself leaves an unmapped name verbatim (`Profile`, `accountId`), so **map every model and field whose Prisma name is not already `snake_case`** if the models are to run against a database Prisma created. Attribute names stay `snake_case` for PEP 8 either way, with `db_column` carrying the real column.
950
-
951
- Things Django cannot express, and what is emitted instead:
952
-
953
- | Prisma | Django | Why |
954
- | ------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
955
- | A foreign key to a composite `@@unique` or `@@id` | The scalar columns, no relation | `CompositePrimaryKey` cannot be a `ForeignKey` target, and a half-join on one column would be wrong |
956
- | `enum` | `TextChoices` + `TextField(choices=…)` | Django has no native PostgreSQL enum type. Reads work through the implicit cast; `OPTIONS={"server_side_binding": True}` and `__startswith`-style lookups on an enum column do not |
957
- | `@id @default(cuid())` / `nanoid()` | `TextField(primary_key=True, default=None)` | No generator is emitted, so the value must be assigned. `None` is what makes an unassigned one raise on INSERT instead of overwriting the row whose key is `""` |
958
- | `onUpdate` | dropped | Django models referential actions in Python and has no `onUpdate` concept |
959
- | Plain `DateTime` | `DateTimeField` | Prisma maps it to `timestamp` (no zone) while Django expects `timestamptz`; annotate it `@db.Timestamptz` to keep `USE_TZ = True` reads aware |
960
-
961
- The models are written for a database Prisma owns, so they are read and written through, not migrated from. `makemigrations` still runs, but its DDL differs from Prisma's: Django writes no `ON DELETE` clause (it cascades in Python), marks foreign keys `DEFERRABLE INITIALLY DEFERRED`, and adds a `text_pattern_ops` companion index beside every text primary key and unique column.
962
-
963
- ### Pydantic
964
-
965
- [Pydantic](https://docs.pydantic.dev/) v2 models (Python). `@p.` field annotations are used verbatim as the base type — list fields wrap it in `list[...]` and optional fields append `| None = None` — and imports for the known pydantic / typing names they reference (`EmailStr`, `Annotated`, `StringConstraints`, …) are added automatically; names outside that set are emitted as-is without an import. Fields without an annotation fall back to the built-in Prisma → Python type mapping, enums become `Literal[...]` of their Prisma-level value names, and relation fields are omitted.
966
-
967
- ```python
968
- from pydantic import BaseModel, StringConstraints, UUID4
969
- from typing import Annotated
970
-
971
-
972
- class User(BaseModel):
973
- id: UUID4
974
- """Primary key"""
975
- name: Annotated[str, StringConstraints(min_length=1, max_length=50)]
976
- """Display name"""
977
-
978
-
979
- class Post(BaseModel):
980
- id: UUID4
981
- """Primary key"""
982
- title: Annotated[str, StringConstraints(min_length=1, max_length=100)]
983
- """Article title"""
984
- content: str
985
- """Body content (no length limit)"""
986
- userId: UUID4
987
- """Foreign key referencing User.id"""
988
- ```
989
-
990
- To configure the model itself, annotate it with pydantic's own `ConfigDict` — the expression is passed through verbatim as `model_config`. `@p.ConfigDict(extra='forbid')` rejects unknown keys, `@p.ConfigDict(extra='allow')` keeps them, `@p.ConfigDict(extra='ignore')` states pydantic's default explicitly, and any other `ConfigDict` arguments (e.g. `frozen=True`) work the same way. No annotation leaves pydantic's default (`extra="ignore"`):
991
-
992
- ```prisma
993
- /// @p.ConfigDict(extra='forbid')
994
- model ApiKey {
995
- id String @id
996
- }
997
- ```
998
-
999
- ```python
1000
- from pydantic import BaseModel, ConfigDict
1001
-
1002
-
1003
- class ApiKey(BaseModel):
1004
- model_config = ConfigDict(extra='forbid')
1005
-
1006
- id: str
1007
- ```
1008
-
1009
- With `relation = true`, each model that has relation fields also gets a `<Model>Relations` subclass — the Pydantic counterpart of the validator generators' relation schemas. Relation fields reference the base classes, so a payload fetched with its relations validates in one call:
1010
-
1011
- ```python
1012
- class UserRelations(User):
1013
- posts: list[Post]
1014
- ```
1015
-
1016
- ### GORM
1017
-
1018
- ```go
1019
- package model
1020
-
1021
- import (
1022
- "github.com/google/uuid"
1023
- "gorm.io/gorm"
1024
- )
1025
-
1026
- type User struct {
1027
- ID string `gorm:"column:id;primaryKey;type:char(36)" json:"id"`
1028
- Name string `gorm:"column:name;not null" json:"name"`
1029
- Posts []Post `gorm:"foreignKey:UserID"`
1030
- }
1031
-
1032
- func (m *User) BeforeCreate(_ *gorm.DB) error {
1033
- if m.ID == "" {
1034
- m.ID = uuid.NewString()
1035
- }
1036
- return nil
1037
- }
1038
-
1039
- type Post struct {
1040
- ID string `gorm:"column:id;primaryKey;type:char(36)" json:"id"`
1041
- Title string `gorm:"column:title;not null" json:"title"`
1042
- Content string `gorm:"column:content;not null" json:"content"`
1043
- UserID string `gorm:"column:user_id;not null" json:"user_id"`
1044
- User User
1045
- }
1046
-
1047
- func (m *Post) BeforeCreate(_ *gorm.DB) error {
1048
- if m.ID == "" {
1049
- m.ID = uuid.NewString()
1050
- }
1051
- return nil
1052
- }
1053
- ```
1054
-
1055
- ### Sea-ORM
1056
-
1057
- Each model is output as a separate `.rs` file with `mod.rs` and `prelude.rs`, following Sea-ORM conventions.
1058
-
1059
- **user.rs:**
1060
-
1061
- ```rust
1062
- use sea_orm::entity::prelude::*;
1063
- use sea_orm::Set;
1064
- use serde::{Deserialize, Serialize};
1065
-
1066
- #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
1067
- #[serde(rename_all = "camelCase")]
1068
- #[sea_orm(table_name = "user")]
1069
- pub struct Model {
1070
- #[sea_orm(primary_key, auto_increment = false)]
1071
- pub id: String,
1072
- pub name: String,
1073
- }
1074
-
1075
- #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
1076
- pub enum Relation {
1077
- #[sea_orm(has_many = "super::post::Entity")]
1078
- Posts,
1079
- }
1080
-
1081
- impl Related<super::post::Entity> for Entity {
1082
- fn to() -> RelationDef {
1083
- Relation::Posts.def()
1084
- }
1085
- }
1086
-
1087
- impl ActiveModelBehavior for ActiveModel {
1088
- fn new() -> Self {
1089
- Self {
1090
- id: Set(uuid::Uuid::new_v4().to_string()),
1091
- ..ActiveModelTrait::default()
1092
- }
1093
- }
1094
- }
1095
- ```
1096
-
1097
- ### Mermaid
1098
-
1099
- ```mermaid
1100
- erDiagram
1101
- User ||--}| Post : "(id) - (userId)"
1102
- User {
1103
- string id PK "Primary key"
1104
- string name "Display name"
1105
- }
1106
- Post {
1107
- string id PK "Primary key"
1108
- string title "Article title"
1109
- string content "Body content (no length limit)"
1110
- string userId FK "Foreign key referencing User.id"
1111
- }
1112
- ```
1113
-
1114
- ### DBML
1115
-
1116
- ```dbml
1117
- Table User {
1118
- id String [pk, note: 'Primary key']
1119
- name String [not null, note: 'Display name']
1120
- }
1121
-
1122
- Table Post {
1123
- id String [pk, note: 'Primary key']
1124
- title String [not null, note: 'Article title']
1125
- content String [not null, note: 'Body content (no length limit)']
1126
- userId String [not null, note: 'Foreign key referencing User.id']
1127
- }
1128
-
1129
- Ref Post_userId_fk: Post.userId > User.id
1130
- ```
1131
-
1132
- ### PNG
1133
-
1134
- The `hekireki-dbml` generator also outputs ER diagrams as PNG images when the `output` path ends with `.png`:
1135
-
1136
- ```prisma
1137
- generator Hekireki-PNG {
1138
- provider = "hekireki-dbml"
1139
- output = "docs/er-diagram.png"
1140
- }
1141
- ```
1142
-
1143
- ### Logical Relations (without a Foreign Key)
1144
-
1145
- To draw a relation that has **no physical foreign key**, add a `/// @relation <Parent>.<field> <Child>.<field> <cardinality>` doc-comment on the model:
1146
-
1147
- ```prisma
1148
- model User {
1149
- id String @id @default(uuid())
1150
- name String
1151
- }
1152
-
1153
145
  /// @relation User.id Post.userId one-to-many
1154
146
  model Post {
1155
147
  id String @id @default(uuid())
@@ -1157,197 +149,195 @@ model Post {
1157
149
  }
1158
150
  ```
1159
151
 
1160
- The relation is drawn in both the Mermaid and DBML output even though `Post.userId` has no `@relation(...)` foreign key. When a physical FK and an annotation describe the same pair, the annotation's cardinality wins in the Mermaid diagram.
1161
-
1162
- ### Docs
1163
-
1164
- The `hekireki-docs` generator creates an HTML documentation page from your Prisma schema. Serve it locally with `hekireki docs serve`:
1165
-
1166
- ```prisma
1167
- generator Hekireki-Docs {
1168
- provider = "hekireki-docs"
1169
- output = "./docs"
1170
- }
1171
- ```
152
+ ## Generators
153
+
154
+ | `provider` | Target | Default output | Options |
155
+ | ----------------------- | -------------------------- | ------------------------------------------- | ------------------------------------ |
156
+ | `hekireki-zod` | TypeScript | `index.ts` | `type`, `comment`, `relation`, `zod` |
157
+ | `hekireki-valibot` | TypeScript | `index.ts` | `type`, `comment`, `relation` |
158
+ | `hekireki-arktype` | TypeScript | `index.ts` | `type`, `comment`, `relation` |
159
+ | `hekireki-effect` | TypeScript | `index.ts` | `type`, `comment`, `relation` |
160
+ | `hekireki-typebox` | TypeScript | `index.ts` | `type`, `comment`, `relation` |
161
+ | `hekireki-ajv` | TypeScript | `index.ts` | `type`, `comment`, `relation` |
162
+ | `hekireki-drizzle` | TypeScript | `schema.ts` | — |
163
+ | `hekireki-kysely` | TypeScript | `types.ts` | — |
164
+ | `hekireki-pydantic` | Python | `models.py` | `comment`, `relation` |
165
+ | `hekireki-sqlalchemy` | Python | `models.py` | — |
166
+ | `hekireki-django` | Python (Django ≥ 5.2) | `models.py` | — |
167
+ | `hekireki-gorm` | Go | `models.go` | `package` |
168
+ | `hekireki-sea-orm` | Rust | one `.rs` per model, `mod.rs`, `prelude.rs` | `renameAll` |
169
+ | `hekireki-ecto` | Elixir | one `.ex` per model | `app` |
170
+ | `hekireki-activerecord` | Ruby (Rails ≥ 7.1) | one `.rb` per model | — |
171
+ | `hekireki-eloquent` | PHP (Laravel, PHP ≥ 8.1) | one `.php` per model and enum | `namespace` |
172
+ | `hekireki-atlas` | Atlas HCL | `schema.hcl` | `schemaName`, `comment` |
173
+ | `hekireki-er` | Mermaid / DBML / PNG / SVG | — (see [ER diagrams](#er-diagrams)) | `outputs`, `mapToDbSchema`, `theme` |
1172
174
 
1173
175
  ## Configuration
1174
176
 
1175
- Configure each generator directly in your `schema.prisma` file.
1176
-
1177
- > `output` is **required** for every generator — there is no implicit default directory.
1178
- > Point it at a directory to get the file name shown below, or at a path with an
1179
- > extension to choose the file name yourself.
1180
-
1181
177
  ```prisma
1182
- // Zod Generator
1183
178
  generator Hekireki-Zod {
1184
179
  provider = "hekireki-zod"
1185
180
  output = "./zod" // Required. A directory here yields ./zod/index.ts
1186
- type = true // Generate TypeScript types (default: false)
1187
- comment = true // Include schema documentation (default: false)
1188
- zod = "v4" // Zod import: "v4", "mini", or "@hono/zod-openapi" (default: v4)
1189
- relation = true // Generate relation schemas (default: false)
181
+ type = true // TypeScript types (default: false)
182
+ comment = true // /// comments as doc comments (default: false)
183
+ relation = true // <Model>Relations schemas (default: false)
184
+ zod = "v4" // "v4" | "mini" | "@hono/zod-openapi" (default: v4)
1190
185
  }
1191
186
 
1192
- // Valibot Generator
187
+ // Valibot, ArkType, Effect Schema, TypeBox and AJV take the same type / comment / relation options.
1193
188
  generator Hekireki-Valibot {
1194
189
  provider = "hekireki-valibot"
1195
- output = "./valibot" // Required. A directory here yields ./valibot/index.ts
1196
- type = true // Generate TypeScript types (default: false)
1197
- comment = true // Include schema documentation (default: false)
1198
- relation = true // Generate relation schemas (default: false)
1199
- }
1200
-
1201
- // ArkType Generator
1202
- generator Hekireki-ArkType {
1203
- provider = "hekireki-arktype"
1204
- output = "./arktype" // Required. A directory here yields ./arktype/index.ts
1205
- type = true // Generate TypeScript types (default: false)
1206
- comment = true // Include schema documentation (default: false)
1207
- relation = true // Generate relation schemas (default: false)
1208
- }
1209
-
1210
- // Effect Schema Generator
1211
- generator Hekireki-Effect {
1212
- provider = "hekireki-effect"
1213
- output = "./effect" // Required. A directory here yields ./effect/index.ts
1214
- type = true // Generate TypeScript types (default: false)
1215
- comment = true // Include schema documentation (default: false)
1216
- relation = true // Generate relation schemas (default: false)
1217
- }
1218
-
1219
- // TypeBox Generator
1220
- generator Hekireki-TypeBox {
1221
- provider = "hekireki-typebox"
1222
- output = "./typebox" // Required. A directory here yields ./typebox/index.ts
1223
- type = true // Generate TypeScript types (default: false)
1224
- comment = true // Include schema documentation (default: false)
1225
- relation = true // Generate relation schemas (default: false)
190
+ output = "./valibot"
191
+ type = true
192
+ comment = true
193
+ relation = true
1226
194
  }
1227
195
 
1228
- // AJV (JSON Schema) Generator
1229
- generator Hekireki-AJV {
1230
- provider = "hekireki-ajv"
1231
- output = "./ajv" // Required. A directory here yields ./ajv/index.ts
1232
- type = true // Generate TypeScript types (default: false)
1233
- comment = true // Include schema documentation (default: false)
1234
- relation = true // Generate relation schemas (default: false)
196
+ generator Hekireki-Pydantic {
197
+ provider = "hekireki-pydantic"
198
+ output = "./pydantic" // A directory here yields ./pydantic/models.py
199
+ comment = true // /// comments as docstrings (default: false)
200
+ relation = true // <Model>Relations subclasses (default: false)
1235
201
  }
1236
202
 
1237
- // Drizzle ORM Schema Generator
203
+ // Drizzle, Kysely, SQLAlchemy, Django and Active Record take output alone.
1238
204
  generator Hekireki-Drizzle {
1239
205
  provider = "hekireki-drizzle"
1240
- output = "./drizzle" // Required. A directory here yields ./drizzle/schema.ts
206
+ output = "./drizzle" // A directory here yields ./drizzle/schema.ts
1241
207
  }
1242
208
 
1243
- // Kysely Type Definitions Generator
1244
- generator Hekireki-Kysely {
1245
- provider = "hekireki-kysely"
1246
- output = "./kysely" // Required. A directory here yields ./kysely/types.ts
1247
- }
1248
-
1249
- // Atlas HCL Schema Generator
1250
209
  generator Hekireki-Atlas {
1251
210
  provider = "hekireki-atlas"
1252
- output = "./atlas" // Required. A directory here yields ./atlas/schema.hcl
1253
- schemaName = "public" // Schema label (default: postgresql/mysql "public", sqlite "main")
1254
- comment = true // Emit /// docs as comment attributes (default: false)
1255
- }
1256
-
1257
- // SQLAlchemy Generator (Python)
1258
- generator Hekireki-SQLAlchemy {
1259
- provider = "hekireki-sqlalchemy"
1260
- output = "./sqlalchemy" // Required. A directory here yields ./sqlalchemy/models.py
211
+ output = "./atlas" // A directory here yields ./atlas/schema.hcl
212
+ schemaName = "public" // Schema label (default: postgresql/mysql "public", sqlite "main")
213
+ comment = true // /// comments as comment attributes (default: false)
1261
214
  }
1262
215
 
1263
- // Django Generator (Python, Django >= 5.2)
1264
- generator Hekireki-Django {
1265
- provider = "hekireki-django"
1266
- output = "./django" // Required. A directory here yields ./django/models.py
1267
- }
1268
-
1269
- // Pydantic Generator (Python)
1270
- generator Hekireki-Pydantic {
1271
- provider = "hekireki-pydantic"
1272
- output = "./pydantic" // Required. A directory here yields ./pydantic/models.py
1273
- comment = true // Include docstrings from /// comments (default: false)
1274
- relation = true // Generate <Model>Relations subclasses (default: false)
1275
- }
1276
-
1277
- // GORM Generator (Go)
1278
216
  generator Hekireki-GORM {
1279
217
  provider = "hekireki-gorm"
1280
- output = "./gorm" // Required. A directory here yields ./gorm/models.go
1281
- package = "model" // Go package name (default: model)
218
+ output = "./gorm" // A directory here yields ./gorm/models.go
219
+ package = "model" // Go package name (default: model)
1282
220
  }
1283
221
 
1284
- // Sea-ORM Generator (Rust)
1285
222
  generator Hekireki-SeaORM {
1286
- provider = "hekireki-sea-orm"
1287
- output = "./sea_orm" // Required. Output directory for .rs files
1288
- renameAll = "camelCase" // #[serde(rename_all = "...")] attribute (optional)
223
+ provider = "hekireki-sea-orm"
224
+ output = "./sea_orm"
225
+ renameAll = "camelCase" // #[serde(rename_all = "...")] (optional)
1289
226
  }
1290
227
 
1291
- // Ecto Generator (Elixir)
1292
228
  generator Hekireki-Ecto {
1293
229
  provider = "hekireki-ecto"
1294
- output = "./ecto" // Required. A directory here yields ./ecto/
1295
- app = "MyApp" // App name (default: MyApp)
1296
- }
1297
-
1298
- // Active Record Generator (Ruby on Rails)
1299
- generator Hekireki-ActiveRecord {
1300
- provider = "hekireki-activerecord"
1301
- output = "./activerecord" // Required. Output directory for .rb files
230
+ output = "./ecto"
231
+ app = "MyApp" // Module prefix (default: MyApp)
1302
232
  }
1303
233
 
1304
- // Eloquent Generator (Laravel / PHP)
1305
234
  generator Hekireki-Eloquent {
1306
235
  provider = "hekireki-eloquent"
1307
- output = "./eloquent" // Required. Output directory for .php files
1308
- namespace = "App.Models" // PHP namespace, "." becomes "\" (default: App\Models)
236
+ output = "./eloquent"
237
+ namespace = "App.Models" // PHP namespace, "." becomes "\" (default: App\Models)
1309
238
  }
1310
239
 
1311
- // Mermaid ER Generator
1312
240
  generator Hekireki-ER {
1313
- provider = "hekireki-mermaid-er"
1314
- output = "./mermaid-er" // Required. A directory here yields ./mermaid-er/ER.md
241
+ provider = "hekireki-er"
242
+ output = "docs" // The directory the files in outputs go in
243
+ outputs = ["er.md", "schema.dbml", "er.svg"] // .md, .dbml, .png or .svg (optional)
244
+ mapToDbSchema = true // .dbml only. @@map/@map names (default: true)
245
+ theme = "light" // .png / .svg only. "light" (default) or "dark"
1315
246
  }
247
+ ```
1316
248
 
1317
- // DBML Generator (output extension determines format: .dbml or .png)
1318
- generator Hekireki-DBML {
1319
- provider = "hekireki-dbml"
1320
- output = "docs/schema.dbml" // Required. File path ending in .dbml or .png
1321
- mapToDbSchema = true // Map to DB schema names (default: true)
1322
- }
249
+ ## ER diagrams
1323
250
 
1324
- // PNG output (same provider, different extension)
1325
- generator Hekireki-PNG {
1326
- provider = "hekireki-dbml"
1327
- output = "docs/er-diagram.png" // Required. .png extension → PNG output
1328
- mapToDbSchema = true // Map to DB schema names (default: true)
1329
- }
251
+ `hekireki-er` writes the ER model of the schema in four formats, and the extension of each file
252
+ picks which — so the file you name is the file you get, and an extension it has no format for is an
253
+ error rather than a guess. `outputs` is the list of files and `output` the directory they go in; for
254
+ a single file, point `output` straight at it and leave `outputs` out.
1330
255
 
1331
- // Docs Generator
1332
- generator Hekireki-Docs {
1333
- provider = "hekireki-docs"
1334
- output = "./docs" // Required. A directory here yields ./docs
1335
- }
1336
- ```
256
+ Every option belongs to a format (`mapToDbSchema` to `.dbml`, `theme` to `.png` and `.svg`), and
257
+ setting one that no chosen format reads is an error — so an option never looks like it did something
258
+ it did not.
259
+
260
+ `.md` writes a Mermaid diagram:
1337
261
 
1338
- ## Docs Server
262
+ ```mermaid
263
+ erDiagram
264
+ User ||--o{ Post : "(id) - (userId)"
265
+ User {
266
+ string id PK "Primary key"
267
+ string name "Display name"
268
+ }
269
+ Post {
270
+ string id PK "Primary key"
271
+ string title "Article title"
272
+ string userId FK "Foreign key referencing User.id"
273
+ }
274
+ ```
1339
275
 
1340
- Hekireki includes a built-in documentation server powered by [Hono](https://hono.dev/). After generating docs with `prisma generate`, you can preview them locally:
276
+ `.dbml` writes the same model for [dbdiagram.io](https://dbml.dbdiagram.io/); `.png` and `.svg`
277
+ draw the diagram Hekireki Studio shows, laid out automatically: a card per model and enum, its
278
+ fields with `🔑` / `🔗` / `UK` marks, the attributes and `///` prose under each, the `@@id` /
279
+ `@@unique` / `@@index` block attributes, and an edge per relation in crow's-foot notation captioned
280
+ with its cardinality and referential action. No external renderer is involved, and the PNG is
281
+ rasterised at 2x. Use `.svg` for files in the repository and `.png` where images are embedded.
282
+ Studio's Schema page exports both with the models where you dragged them.
1341
283
 
1342
- ```bash
1343
- # Start the docs server (default: http://localhost:5858)
1344
- hekireki docs serve
284
+ ## Studio
1345
285
 
1346
- # Specify a custom port
1347
- hekireki docs serve -p 3000
1348
- ```
286
+ `hekireki studio` opens the schema in the browser, served locally by [Hono](https://hono.dev/).
287
+ Nothing is generated first — Studio reads `schema.prisma` itself and reloads on every edit to it:
1349
288
 
1350
- > **Note:** Run `prisma generate` first to generate the `docs/` directory with `index.html`.
289
+ ```bash
290
+ # Open ./prisma/schema.prisma, then ./schema.prisma (default: http://localhost:5555)
291
+ hekireki studio
292
+
293
+ # Read a multi-file schema: every .prisma file directly in the directory, together
294
+ hekireki studio --schema prisma/schema
295
+
296
+ # Browse a database of your choosing
297
+ hekireki studio --url file:./dev.db
298
+
299
+ # Listen on another port
300
+ hekireki studio -p 3000
301
+ ```
302
+
303
+ | Page | What it is |
304
+ | ---------------- | --------------------------------------------------------------------------------- |
305
+ | `/` — Schema | The ER diagram, laid out automatically, with **PNG** / **SVG** export |
306
+ | `/docs` — Docs | The reference page: every model and enum with its fields, attributes and comments |
307
+ | `/models/<name>` | A model's rows, editable, next to its fields |
308
+ | `/enums/<name>` | An enum with its members and the fields that hold it |
309
+ | `/prisma` | The schema in a Prisma editor, with the language server's diagnostics |
310
+ | `/sql` | A SQL console against the connected database |
311
+
312
+ `--schema` takes either a `schema.prisma` file or a directory — every `.prisma` file directly in the
313
+ directory (subdirectories are not descended into) is read as one schema, which is how Prisma's
314
+ [multi-file schema](https://www.prisma.io/docs/orm/prisma-schema/overview/location#multi-file-prisma-schema)
315
+ (`prisma/schema/`) is opened. Without the flag, `./prisma/schema.prisma` then `./schema.prisma` are
316
+ looked for — the same two paths the Prisma CLI defaults to. Either way the whole directory is
317
+ watched, so a `.prisma` file added to it appears in Studio without a restart.
318
+
319
+ The database is the one `--url` names, or `DATABASE_URL` from the environment or `.env`, then
320
+ `datasource.url` in `prisma.config.ts`; `postgres://`, `mysql://` and `file:` are understood. A
321
+ relative `file:` path is resolved from the schema directory, as Prisma resolves it — with the
322
+ default `prisma/schema.prisma`, `file:./dev.db` is `prisma/dev.db`. Without a database, Studio
323
+ serves the schema alone — the diagram, the docs and the editor still work.
324
+
325
+ The HTTP API behind it is documented in [docs/studio-api.md](https://github.com/nakita628/hekireki/blob/main/packages/hekireki/docs/studio-api.md).
326
+
327
+ ## Notes
328
+
329
+ - **Atlas** — declarative `atlas schema apply` drops whatever is missing from the HCL, and Prisma's
330
+ `_prisma_migrations` table, `@ignore`d columns and `Unsupported(...)` types can never appear in it.
331
+ Dry-run first and exclude the migrations table: `--exclude '_prisma_migrations'`.
332
+ - **Kysely** — only **database-side** defaults become `Generated<T>`. `uuid()`, `cuid()`, `ulid()`
333
+ and `nanoid()` are evaluated by the Prisma Client, so a raw Kysely insert must still supply them.
334
+ - **Django** — enums become `TextChoices` + `TextField(choices=…)` (Django has no native PostgreSQL
335
+ enum type), a foreign key to a composite `@@id` / `@@unique` is emitted as the scalar columns
336
+ without a relation, `onUpdate` is dropped, and a plain `DateTime` maps to `DateTimeField` while
337
+ Prisma stores `timestamp` — annotate it `@db.Timestamptz` to keep `USE_TZ = True` reads aware.
338
+ - **Eloquent** — a composite primary key is emitted as `protected $primaryKey = null;`, because
339
+ Eloquent has no native support for one. Active Record writes the real
340
+ `self.primary_key = [...]` (Rails ≥ 7.1).
1351
341
 
1352
342
  ## License
1353
343