hekireki 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,60 +56,18 @@ model User {
56
56
 
57
57
  ### Rails
58
58
 
59
- `hekireki-activerecord` writes `app/models` whole, for Rails 7.1 or later: `application_record.rb`
60
- as `rails new` writes it (when `output` is a directory named `models`) and one `.rb` file per
61
- model, so the directory can go in `.gitignore` and be regenerated with `prisma generate`. Each
62
- model is written as a Rails developer would write it, and what Rails derives on its own is left
63
- unsaid: `table_name` appears only when the table is not the plural of the class (without `@@map`
64
- it is the model's own name, `"Todo"`, as Prisma creates it), `class_name`, `foreign_key` and
65
- `inverse_of` only where the names depart from Rails' conventions (`has_many :todos` over `user_id`
66
- needs none of them; its `belongs_to :user` keeps `inverse_of: :todos`, the plural inverse Rails
67
- infers only with `automatically_invert_plural_associations`), and no comment at all: the `///`
68
- documentation stays in the schema. The files pass `rubocop-rails-omakase` and RuboCop's own
69
- defaults with `rubocop-rails` as written.
70
-
71
- What the model does carry: an `attribute` default for each literal `@default`, for `uuid()`,
72
- `ulid()`, `cuid()`, `cuid(2)` and `nanoid()` (the `ulid`, `cuid`, `cuid2` and `nanoid` gems) and an
73
- empty array for a list without one, as the Prisma client reads it; `implicit_order_column` on the
74
- created timestamp when the primary key is random (`uuid()`, `cuid()`, `nanoid()`); `alias_attribute`
75
- for a `createdAt` or `@updatedAt` column so Rails fills and bumps it as the Prisma client would;
76
- `enum` with snake_case keys (`PENDING_REVIEW` gives `record.pending_review?` and the
77
- `pending_review` scope, the stored value stays the database's), its `default:`, `prefix: true` when a
78
- key is a method Ruby or Active Record already has, and `validate: true` so a value outside the enum
79
- is a validation error rather than an `ArgumentError`; `dependent:` on every `has_many` and `has_one`
80
- as the foreign key's `onDelete` acts (`Cascade` destroys, `SetNull` nullifies, `Restrict` and
81
- `NoAction` refuse with an error); and validations from the columns: a required column without a
82
- default is `presence` (`inclusion` in `[ true, false ]` for a `Boolean`, `exclusion` of `nil` for
83
- `Json` and `Bytes`), `@unique` and `@@unique` are `uniqueness`, `@db.VarChar(n)` is `length`.
84
-
85
- Validation stays in the model, as Active Record has it. A `/// @ar.` call on a field is one
86
- validator on one `///` line, written as Rails spells it (`presence`, `length(maximum: 255)`), and
87
- becomes an option of that field's `validates`, replacing the one the schema implied when it names
88
- the same validator; a `/// @ar.` line on the model is written into the class as it is. A message
89
- given per locale, `message: { ja: "...", en: "..." }` or `too_long: { ja: "...", en: "..." }`, is
90
- not written into the model: it goes to `config/locales/models/todo/<locale>.yml` under the key the
91
- [Rails i18n guide](https://guides.rubyonrails.org/i18n.html#error-message-scopes) lists for that
92
- validator (`activerecord.errors.models.todo.attributes.title.blank`). `too_long` is a key already;
93
- `message` stands for every key the validator can raise: `blank` for `presence`, all three of
94
- `length`, and for `numericality` and `comparison` the keys of the options given
95
- (`greater_than: 0` raises `greater_than`), so the one translation covers whichever fails. A locale's
96
- value may be plural forms, `{ one: "...", other: "%{count} ..." }`, which I18n picks by `count`, and
97
- `%{count}`, `%{value}`, `%{model}` and `%{attribute}` interpolate as Rails' own messages do.
98
- `@ar.name(ja: "...", en: "...")` on a field or a model translates its name the same way
99
- (`activerecord.attributes.todo.title`, `activerecord.models.todo`), plural forms included.
100
- The files are laid out as the guide's
101
- [organization of locale files](https://guides.rubyonrails.org/i18n.html#organization-of-locale-files)
102
- has them, `models/<model>/<locale>.yml`, one directory per model and one file per locale it names,
103
- so model and attribute names stay apart from the text of the views and from the defaults; Rails
104
- loads `config/locales` through its subdirectories. `locales` names that directory; from
105
- `app/models` it is `config/locales`. The comment has one shape: the description first, then the
106
- `@ar.` calls, one to a `///` line. On a field each is `name` or `name(arguments)` with its
107
- parentheses closed on that line; on the model each is a Ruby line as the class body would have it
108
- (`validates :a, :b, presence: true`, `normalizes :title, with: ->(title) { title.strip }`), not
109
- ending in a comma. A description line after a call, a call that runs on to the next `///` or a
110
- call of another shape stops `prisma generate` with the model and field it is on. Rails joins attribute and message with a space (`errors.format`), which Japanese does not want: the
111
- `rails-i18n` gem's `ja.yml` sets it to `%{attribute}%{message}`, and the generated files sit beside
112
- it. Point `output` at `app/models`, and `todo.rb` is the model, nothing left to edit by hand:
59
+ `hekireki-activerecord` writes `app/models` from the schema: `application_record.rb` and one model
60
+ per Prisma model, as a Rails developer would write them. What Rails works out on its own
61
+ (`table_name`, `class_name`, `foreign_key`, `inverse_of` where the names follow its conventions)
62
+ is left unsaid; what the schema promises is written: `attribute` defaults, `enum`, timestamps,
63
+ associations with `dependent:` from `onDelete`, and validations from the columns (`presence`,
64
+ `uniqueness`, `length`).
65
+
66
+ A `/// @ar.` line on a field is a validator (`presence`, `length(maximum: 255)`) added to that
67
+ field's `validates`; on a model it is a Ruby line written into the class as it is
68
+ (`has_secure_password`, `has_many :tags, through: :post_tags`, `scope ...`). A message or name
69
+ given per locale, `message: { ja: "...", en: "..." }` or `@ar.name(ja: "...")`, goes to
70
+ `config/locales/models/<model>/<locale>.yml` under the key Rails reads.
113
71
 
114
72
  ```prisma
115
73
  generator Hekireki-ActiveRecord {
@@ -133,11 +91,6 @@ model Todo {
133
91
  ```
134
92
 
135
93
  ```ruby
136
- # app/models/application_record.rb
137
- class ApplicationRecord < ActiveRecord::Base
138
- primary_abstract_class
139
- end
140
-
141
94
  # app/models/todo.rb
142
95
  class Todo < ApplicationRecord
143
96
  attribute :completed, default: false
@@ -164,53 +117,40 @@ ja:
164
117
  too_long: '%{count}文字以内で入力してください'
165
118
  ```
166
119
 
167
- ```gitignore
168
- /app/models/
169
- /config/locales/models/
170
- ```
120
+ The tables stay Prisma's to create, so set `config.active_record.migration_error = false` and
121
+ create the test database with `prisma migrate deploy`. `examples/active-record` in the repository
122
+ runs a fuller schema against Active Record on SQLite, and is the place to read what each thing
123
+ becomes.
171
124
 
172
- Which file answers is the request's locale. The guide's
173
- [managing the locale across requests](https://guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests)
174
- sets it once per request with `I18n.with_locale`, which puts it back when the action ends rather
175
- than leaving it on the thread for the next request, and names the locales the application serves:
125
+ ## Studio
176
126
 
177
- ```ruby
178
- # config/application.rb
179
- config.i18n.available_locales = %i[ja en]
180
- config.i18n.default_locale = :ja
181
-
182
- # app/controllers/application_controller.rb
183
- class ApplicationController < ActionController::Base
184
- around_action :switch_locale
185
-
186
- private
187
- def switch_locale(&action)
188
- locale = params[:locale] || I18n.default_locale
189
- I18n.with_locale(locale, &action)
190
- end
191
- end
127
+ ```bash
128
+ npx hekireki studio # ./prisma/schema.prisma or ./schema.prisma, port 5555
129
+ npx hekireki studio --url file:./dev.db
192
130
  ```
193
131
 
194
- The tables stay Prisma's to create, so Rails must not run its own migrations against them:
132
+ Your schema and database in the browser, on SQLite, PostgreSQL and MySQL.
195
133
 
196
- ```ruby
197
- # config/application.rb
198
- config.active_record.migration_error = false
199
- config.active_record.maintain_test_schema = false
200
- ```
134
+ **Browse the rows** of each model: search, add, edit and export them.
201
135
 
202
- Create the test database with `prisma migrate deploy` (from `test_helper.rb`, or before the test
203
- run) rather than `db:test:prepare`.
136
+ ![The rows of the User model](https://raw.githubusercontent.com/nakita628/hekireki/refs/heads/main/assets/img/studio-data.png)
204
137
 
205
- ## Studio
138
+ **Run SQL** with completion from the schema. The ER diagram marks the tables a statement reads,
139
+ and the result comes with the TypeScript types of its rows.
206
140
 
207
- ```bash
208
- npx hekireki studio # ./prisma/schema.prisma or ./schema.prisma, port 5555
209
- npx hekireki studio --url file:./dev.db
210
- ```
141
+ ![A SELECT typed in the SQL console](https://raw.githubusercontent.com/nakita628/hekireki/refs/heads/main/assets/img/studio-sql.gif)
142
+
143
+ **Try Prisma Client calls** and see the SQL each one sends.
144
+
145
+ ![prisma.user.findMany() in the Prisma Client playground](https://raw.githubusercontent.com/nakita628/hekireki/refs/heads/main/assets/img/studio-prisma-client.gif)
146
+
147
+ **Edit the schema** beside its ER diagram, which follows the file as it changes.
148
+
149
+ ![The Prisma schema editor and the ER diagram](https://raw.githubusercontent.com/nakita628/hekireki/refs/heads/main/assets/img/studio-prisma-schema.png)
150
+
151
+ **Read the docs** of every model: its fields, and an example of each operation.
211
152
 
212
- The ER diagram, the rows of each model, a schema editor, a SQL console and a Prisma Client
213
- playground, in the browser. SQLite, PostgreSQL and MySQL.
153
+ ![The generated docs of the User model](https://raw.githubusercontent.com/nakita628/hekireki/refs/heads/main/assets/img/studio-docs.png)
214
154
 
215
155
  ## Seed
216
156
 
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/activerecord.ts
4
4
  registerGenerator("activerecord");
5
5
  //#endregion
package/dist/bin/ajv.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/ajv.ts
4
4
  registerGenerator("ajv");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/arktype.ts
4
4
  registerGenerator("arktype");
5
5
  //#endregion
package/dist/bin/atlas.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/atlas.ts
4
4
  registerGenerator("atlas");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/django.ts
4
4
  registerGenerator("django");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/drizzle.ts
4
4
  registerGenerator("drizzle");
5
5
  //#endregion
package/dist/bin/ecto.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/ecto.ts
4
4
  registerGenerator("ecto");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/efcore.ts
4
4
  registerGenerator("efcore");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/effect.ts
4
4
  registerGenerator("effect");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/eloquent.ts
4
4
  registerGenerator("eloquent");
5
5
  //#endregion
package/dist/bin/er.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/er.ts
4
4
  registerGenerator("er");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/exposed.ts
4
4
  registerGenerator("exposed");
5
5
  //#endregion
package/dist/bin/gorm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/gorm.ts
4
4
  registerGenerator("gorm");
5
5
  //#endregion
@@ -5,7 +5,7 @@ import { Console, Data, Effect, Option, Schema, Stdio } from "effect";
5
5
  import path from "node:path";
6
6
  import { CliError, Command, Flag } from "effect/unstable/cli";
7
7
  //#region package.json
8
- var version = "0.31.0";
8
+ var version = "0.32.0";
9
9
  //#endregion
10
10
  //#region src/studio/server/constants/index.ts
11
11
  /** Studio only listens on loopback: the API serves the raw schema and runs SQL without authentication. */
@@ -128,7 +128,7 @@ const seedFlags = {
128
128
  };
129
129
  function runSeedCommand(args) {
130
130
  return Effect.gen(function* () {
131
- const { runSeed, seedBanner } = yield* Effect.promise(() => import("../run-BMAnuiJ1.js"));
131
+ const { runSeed, seedBanner } = yield* Effect.promise(() => import("../run-DhCGgShc.js"));
132
132
  const report = yield* runSeed({
133
133
  config: Option.getOrNull(args.config),
134
134
  schema: Option.getOrNull(args.schema),
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/kysely.ts
4
4
  registerGenerator("kysely");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/pydantic.ts
4
4
  registerGenerator("pydantic");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/sea-orm.ts
4
4
  registerGenerator("sea-orm");
5
5
  //#endregion
package/dist/bin/seed.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/seed.ts
4
4
  registerGenerator("seed");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/sqlalchemy.ts
4
4
  registerGenerator("sqlalchemy");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/typebox.ts
4
4
  registerGenerator("typebox");
5
5
  //#endregion
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/valibot.ts
4
4
  registerGenerator("valibot");
5
5
  //#endregion
package/dist/bin/zod.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerGenerator } from "../bin-CiVKUVYM.js";
2
+ import { t as registerGenerator } from "../bin-CmwdzyIR.js";
3
3
  //#region src/bin/zod.ts
4
4
  registerGenerator("zod");
5
5
  //#endregion
@@ -993,7 +993,14 @@ function arCalls(documentation, on) {
993
993
  * validator. Each names the model or field it is on.
994
994
  */
995
995
  function activeRecordProblems(models) {
996
- return models.flatMap((model) => [...arCalls(model.documentation, "model").problems.map((problem) => `model ${model.name}: ${problem}`), ...model.fields.flatMap((field) => arCalls(field.documentation, "field").problems.map((problem) => `field ${model.name}.${field.name}: ${problem}`))]);
996
+ return models.flatMap((model) => [...arCalls(model.documentation, "model").problems.map((problem) => `model ${model.name}: ${problem}`), ...model.fields.flatMap((field) => {
997
+ const { calls, problems } = arCalls(field.documentation, "field");
998
+ const notNames = field.kind === "object" ? calls.filter((call) => {
999
+ const { validator } = validatorCall(call);
1000
+ return validator !== null && validator !== "name";
1001
+ }).map((call) => `the @ar. call "${call}" is on a relation field, which takes only @ar.name; validate the association with an @ar. line on the model`) : [];
1002
+ return [...problems, ...notNames].map((problem) => `field ${model.name}.${field.name}: ${problem}`);
1003
+ })]);
997
1004
  }
998
1005
  function splitArguments(text) {
999
1006
  const parts = [];
@@ -1119,6 +1126,11 @@ function validatorCall(call) {
1119
1126
  messages
1120
1127
  };
1121
1128
  }
1129
+ if (args.trim() === "false") return {
1130
+ validator,
1131
+ option: null,
1132
+ messages
1133
+ };
1122
1134
  const kept = [];
1123
1135
  const translated = [];
1124
1136
  for (const argument of splitArguments(args)) {
@@ -1192,10 +1204,10 @@ function activeRecordLocaleFiles(models) {
1192
1204
  ], m.text);
1193
1205
  }
1194
1206
  for (const field of model.fields) {
1195
- if (field.kind === "object") continue;
1196
- const attribute = field.dbName ?? field.name;
1207
+ const attribute = field.kind === "object" ? makeSnakeCase(field.name) : field.dbName ?? field.name;
1197
1208
  for (const call of arCalls(field.documentation, "field").calls) {
1198
1209
  const { validator, messages } = validatorCall(call);
1210
+ if (field.kind === "object" && validator !== "name") continue;
1199
1211
  for (const m of messages) setPath(tree(m.locale), validator === "name" ? [
1200
1212
  "activerecord",
1201
1213
  "attributes",
@@ -1395,30 +1407,43 @@ function activeRecordModels(models, allModels, enums) {
1395
1407
  }).lines;
1396
1408
  const foreignKeyFields = new Set(model.fields.flatMap((f) => f.kind === "object" ? f.relationFromFields ?? [] : []));
1397
1409
  const compositeKeyFields = new Set(model.primaryKey?.fields);
1398
- const uniqueSets = [...model.fields.filter((f) => f.isUnique && !f.isId).map((f) => [f.name]), ...model.uniqueFields];
1399
- const validationLines = [...model.fields.flatMap((f) => {
1410
+ const scalarColumns = new Set(model.fields.filter((f) => f.kind === "scalar" && !f.isList).map((f) => f.name));
1411
+ const taken = new Set(model.fields.filter((f) => f.isUnique && !f.isId).map((f) => f.name));
1412
+ const uniqueSets = [...model.fields.filter((f) => f.isUnique && !f.isId).map((f) => [f.name]), ...model.uniqueFields.map((set) => {
1413
+ const columns = set.filter((name) => scalarColumns.has(name));
1414
+ const own = columns.find((name) => !foreignKeyFields.has(name) && !taken.has(name)) ?? columns.find((name) => !foreignKeyFields.has(name)) ?? columns[0] ?? set[0] ?? "";
1415
+ taken.add(own);
1416
+ return [own, ...set.filter((name) => name !== own)];
1417
+ })];
1418
+ const modelLines = arCalls(model.documentation, "model").calls.filter((call) => validatorCall(call).validator !== "name");
1419
+ const digestColumns = new Set(modelLines.flatMap((line) => {
1420
+ const m = line.match(/^has_secure_password(?:\s*\(?\s*:([a-z_][a-z0-9_]*))?/u);
1421
+ return m && !/validations:\s*false/u.test(line) ? [`${m[1] ?? "password"}_digest`] : [];
1422
+ }));
1423
+ const validationLines = model.fields.flatMap((f) => {
1400
1424
  if (!(f.kind === "scalar" || f.kind === "enum")) return [];
1401
1425
  const column = f.kind === "scalar" && !f.isList;
1402
- const presence = !(column && f.isRequired && !f.hasDefaultValue && !f.isId && !f.isUpdatedAt && !foreignKeyFields.has(f.name) && !compositeKeyFields.has(f.name) && f !== createdField && f !== updatedField) ? [] : f.type === "Boolean" ? ["inclusion: { in: [ true, false ] }"] : f.type === "Json" || f.type === "Bytes" ? ["exclusion: { in: [ nil ] }"] : ["presence: true"];
1426
+ const own = arCalls(f.documentation, "field").calls.map((call) => validatorCall(call));
1427
+ const presence = !(column && !own.some(({ validator, option }) => validator === "presence" && option === null) && f.isRequired && !f.hasDefaultValue && !f.isId && !f.isUpdatedAt && !foreignKeyFields.has(f.name) && !compositeKeyFields.has(f.name) && !digestColumns.has(f.dbName ?? f.name) && f !== createdField && f !== updatedField) ? [] : f.type === "Boolean" ? ["inclusion: { in: [ true, false ] }"] : f.type === "Json" || f.type === "Bytes" ? ["exclusion: { in: [ nil ] }"] : ["presence: true"];
1403
1428
  const length = column && f.type === "String" ? nativeLength(f) : null;
1404
1429
  const lengthOpt = length === null ? [] : [`length: { maximum: ${length} }`];
1405
- const uniqueSet = column ? uniqueSets.find((set) => set[0] === f.name) : void 0;
1406
- const uniqueness = uniqueSet === void 0 ? [] : [(() => {
1407
- const scope = uniqueSet.slice(1).map((name) => `:${fieldColumn$1(model, name)}`);
1408
- const opts = [...scope.length === 0 ? [] : [`scope: ${scope.length === 1 ? scope[0] : rubyArray(scope)}`], ...f.isRequired ? [] : ["allow_nil: true"]];
1430
+ const uniqueness = (column ? uniqueSets.filter((set) => set[0] === f.name) : []).map((set) => {
1431
+ const scope = set.slice(1).map((name) => `:${fieldColumn$1(model, name)}`);
1432
+ const nullable = set.slice(1).filter((name) => model.fields.some((g) => g.name === name && !g.isRequired)).map((name) => `where.not(${fieldColumn$1(model, name)}: nil)`);
1433
+ const opts = [
1434
+ ...scope.length === 0 ? [] : [`scope: ${scope.length === 1 ? scope[0] : rubyArray(scope)}`],
1435
+ ...nullable.length === 0 ? [] : [`conditions: -> { ${nullable.join(".")} }`],
1436
+ ...f.isRequired ? [] : ["allow_nil: true"]
1437
+ ];
1409
1438
  return opts.length === 0 ? "uniqueness: true" : `uniqueness: { ${opts.join(", ")} }`;
1410
- })()];
1411
- const own = arCalls(f.documentation, "field").calls.flatMap((call) => {
1412
- const { option } = validatorCall(call);
1413
- return option === null ? [] : [option];
1414
1439
  });
1415
1440
  const rules = [...[
1416
1441
  ...presence,
1417
1442
  ...lengthOpt,
1418
- ...uniqueness
1419
- ].filter((rule) => !own.some((line) => new RegExp(`(^|[,\\s])${rule.split(":")[0]}:`, "u").test(line))), ...own];
1420
- return rules.length === 0 ? [] : [rubyCall("validates", [`:${f.dbName ?? f.name}`], rules)];
1421
- }), ...arCalls(model.documentation, "model").calls.filter((call) => validatorCall(call).validator !== "name")];
1443
+ ...uniqueness.slice(0, 1)
1444
+ ].filter((rule) => !own.some(({ validator }) => validator === rule.split(":")[0])), ...own.flatMap(({ option }) => option === null ? [] : [option])];
1445
+ return [...rules.length === 0 ? [] : [rubyCall("validates", [`:${f.dbName ?? f.name}`], rules)], ...uniqueness.slice(1).map((rule) => rubyCall("validates", [`:${f.dbName ?? f.name}`], [rule]))];
1446
+ });
1422
1447
  const modelSnake = makeSnakeCase(model.name);
1423
1448
  const belongsToLines = associations.belongsTo.map((a) => {
1424
1449
  const name = makeSnakeCase(a.name);
@@ -1472,7 +1497,8 @@ function activeRecordModels(models, allModels, enums) {
1472
1497
  [...attributeLines, ...timestampLines],
1473
1498
  enumLines,
1474
1499
  validationLines,
1475
- associationLines
1500
+ associationLines,
1501
+ modelLines
1476
1502
  ].filter((group) => group.length > 0).map((group) => group.join("\n")).join("\n\n").split("\n");
1477
1503
  return [
1478
1504
  `class ${className} < ApplicationRecord`,
@@ -382,14 +382,14 @@ function makeText(faker, name) {
382
382
  max: 3
383
383
  }) : match[1](faker);
384
384
  }
385
- function maxLength(field, rule) {
385
+ function maxLength(field, rule, stringLength) {
386
386
  const native = nativeTypeOf(field);
387
- const bounds = [native.name !== null && /^(Var|N|NVar)?Char$/u.test(native.name) ? native.args[0] : void 0, typeof rule.length === "number" ? rule.length : rule.length?.max].filter((n) => n !== void 0 && n > 0);
387
+ const bounds = [native.name === null ? stringLength ?? void 0 : /^(Var|N|NVar)?Char$/u.test(native.name) ? native.args[0] : void 0, typeof rule.length === "number" ? rule.length : rule.length?.max].filter((n) => n !== void 0 && n > 0);
388
388
  return bounds.length === 0 ? null : Math.min(...bounds);
389
389
  }
390
- function makeString(faker, field, rule) {
390
+ function makeString(faker, field, rule, bounds) {
391
391
  const text = nativeTypeOf(field).name === "Uuid" ? faker.string.uuid() : makeText(faker, normalizedName(field.name));
392
- const limit = maxLength(field, rule);
392
+ const limit = maxLength(field, rule, bounds.stringLength ?? null);
393
393
  return limit === null ? text : text.slice(0, limit);
394
394
  }
395
395
  function intRange(field, rule) {
@@ -482,7 +482,7 @@ function makeJson(faker) {
482
482
  function makeScalar(faker, field, enumValues, rule, bounds, index) {
483
483
  if (field.kind === "enum") return enumValues === null || enumValues.length === 0 ? null : faker.helpers.arrayElement(enumValues).name;
484
484
  switch (field.type) {
485
- case "String": return makeString(faker, field, rule);
485
+ case "String": return makeString(faker, field, rule, bounds);
486
486
  case "Int": return field.isId && rule.min === void 0 && rule.max === void 0 ? index + 1 : faker.number.int(intRange(field, rule));
487
487
  case "BigInt": {
488
488
  const range = intRange(field, rule);
@@ -504,7 +504,7 @@ function makeScalar(faker, field, enumValues, rule, bounds, index) {
504
504
  prefix: "",
505
505
  casing: "lower"
506
506
  }), "hex"));
507
- default: return makeString(faker, field, rule);
507
+ default: return makeString(faker, field, rule, bounds);
508
508
  }
509
509
  }
510
510
  function listLength(faker, rule) {
@@ -1053,7 +1053,8 @@ function defaultValue(input, field) {
1053
1053
  const { context, table, index } = input;
1054
1054
  const bounds = {
1055
1055
  nullRate: 0,
1056
- dates: context.config.dates
1056
+ dates: context.config.dates,
1057
+ stringLength: context.stringLength
1057
1058
  };
1058
1059
  const generated = fieldDefault(field);
1059
1060
  if (generated?.name === "autoincrement") return field.type === "BigInt" ? BigInt(index + 1) : index + 1;
@@ -1083,7 +1084,8 @@ function fillScalars(input, columns, skip, row) {
1083
1084
  rule: input.context.config.models[input.table.name]?.fields?.[column.field],
1084
1085
  bounds: {
1085
1086
  nullRate: input.context.config.nullRate,
1086
- dates: input.context.config.dates
1087
+ dates: input.context.config.dates,
1088
+ stringLength: input.context.stringLength
1087
1089
  },
1088
1090
  index: input.index,
1089
1091
  row
@@ -1324,6 +1326,7 @@ function generateSeedRows(input) {
1324
1326
  const context = {
1325
1327
  faker: input.faker,
1326
1328
  config: input.config,
1329
+ stringLength: input.dialect === "mysql" ? 191 : null,
1327
1330
  tables: input.tables,
1328
1331
  rowsByModel,
1329
1332
  pending: /* @__PURE__ */ new Map(),
@@ -1489,7 +1492,8 @@ function seedProgram(overrides, cwd) {
1489
1492
  const entries = yield* generateSeedRows({
1490
1493
  tables: yield* makeSeedPlan(schema.datamodel),
1491
1494
  config,
1492
- faker: yield* makeFaker(config.seed, config.locale)
1495
+ faker: yield* makeFaker(config.seed, config.locale),
1496
+ dialect: dialectOf(schema.provider)
1493
1497
  });
1494
1498
  const report = {
1495
1499
  seed: config.seed,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hekireki",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "Hekireki is a code generator from Prisma schema to validation schemas, ORM models and ER diagrams, with a Studio for your schema and its data",
5
5
  "keywords": [
6
6
  "activerecord",