hekireki 0.30.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.
@@ -1,22 +1,1239 @@
1
1
  import { r as fileSystemLayer } from "./file-BPNqvwXD.js";
2
- import { _ as schemaFromFields, a as getStrings, c as isFields, d as makeCommentBlock, f as makePascalCase, h as parseDocumentWithoutAnnotations, i as getString, m as makeValidationExtractor, n as extractObjectType, o as groupByModel, p as makeSnakeCase, r as getBool, v as stripAnnotations } from "./utils-CH4KSdD_.js";
3
- import { n as emitMany, r as emitRaw, t as emit } from "./emit-Cg7AiLfc.js";
4
- import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-n8EV8GwT.js";
2
+ import { _ as schemaFromFields, a as getStrings, c as isFields, d as makeCommentBlock, f as makePascalCase, h as parseDocumentWithoutAnnotations, i as getString, m as makeValidationExtractor, n as extractObjectType, o as groupByModel, p as makeSnakeCase, r as getBool, s as isAnnotationLine, v as stripAnnotations } from "./utils-Cgi66Lfo.js";
3
+ import { n as emitMany, r as emitRaw, t as emit } from "./emit-CdFQK71O.js";
4
+ import { a as erRelations, i as erKey, n as makeSchema, o as inferredERRelations, r as annotatedERRelations } from "./schema-B-2ni3YF.js";
5
5
  import { Data, Effect } from "effect";
6
6
  import path from "node:path";
7
7
  import pkg from "@prisma/generator-helper";
8
8
  import { graphlib, layout } from "@dagrejs/dagre";
9
9
  import * as z from "zod";
10
10
  import { Resvg } from "@resvg/resvg-js";
11
+ //#region src/helper/activerecord-reserved.ts
12
+ const RAILS_RESERVED_NAMES = new Set(`abort
13
+ abstract_class
14
+ accepts_nested_attributes_for
15
+ acts_like
16
+ adapter_class
17
+ add_autosave_association_callbacks
18
+ add_length_validation_for_encrypted_columns
19
+ after_commit
20
+ after_create
21
+ after_create_commit
22
+ after_destroy
23
+ after_destroy_commit
24
+ after_find
25
+ after_initialize
26
+ after_rollback
27
+ after_save
28
+ after_save_commit
29
+ after_touch
30
+ after_update
31
+ after_update_commit
32
+ after_validation
33
+ aggregate_reflections
34
+ alias_attribute
35
+ alias_attribute_method_definition
36
+ alias_method
37
+ aliases_by_attribute_name
38
+ all
39
+ all_timestamp_attributes_in_model
40
+ allocate
41
+ allow_destroy
42
+ ancestors
43
+ and
44
+ annotate
45
+ append_to_connected_to_stack
46
+ apply_pending_attribute_modifications
47
+ apply_scoping
48
+ arel_table
49
+ around_create
50
+ around_destroy
51
+ around_save
52
+ around_update
53
+ as_json
54
+ assert_valid_enum_definition_values
55
+ assert_valid_enum_options
56
+ assert_valid_transaction_action
57
+ association_cached
58
+ association_foreign_key_changed
59
+ association_valid
60
+ async_average
61
+ async_count
62
+ async_count_by_sql
63
+ async_find_by_sql
64
+ async_ids
65
+ async_maximum
66
+ async_minimum
67
+ async_pick
68
+ async_pluck
69
+ async_sum
70
+ asynchronous_queries_session
71
+ asynchronous_queries_tracker
72
+ at_exit
73
+ attached_object
74
+ attr
75
+ attr_accessor
76
+ attr_internal
77
+ attr_internal_accessor
78
+ attr_internal_define
79
+ attr_internal_reader
80
+ attr_internal_writer
81
+ attr_reader
82
+ attr_readonly
83
+ attr_writer
84
+ attribute
85
+ attribute_alias
86
+ attribute_aliases
87
+ attribute_came_from_user
88
+ attribute_changed
89
+ attribute_changed_in_place
90
+ attribute_method
91
+ attribute_method_affix
92
+ attribute_method_patterns
93
+ attribute_method_patterns_cache
94
+ attribute_method_patterns_matching
95
+ attribute_method_prefix
96
+ attribute_method_suffix
97
+ attribute_names
98
+ attribute_present
99
+ attribute_previously_changed
100
+ attribute_types
101
+ attribute_will_change
102
+ attributes_builder
103
+ attributes_for_inspect
104
+ authenticate_by
105
+ autoload
106
+ automatic_scope_inversing
107
+ automatically_invert_plural_associations
108
+ autosaving_belongs_to_for
109
+ average
110
+ base_class
111
+ becomes
112
+ before_commit
113
+ before_committed
114
+ before_create
115
+ before_destroy
116
+ before_save
117
+ before_update
118
+ before_validation
119
+ belongs_to
120
+ belongs_to_required_by_default
121
+ benchmark
122
+ binding
123
+ blank
124
+ block_given
125
+ build
126
+ build_column_serializer
127
+ build_default_constraint
128
+ build_default_scope
129
+ build_explain_clause
130
+ build_mangled_name
131
+ cache
132
+ cache_timestamp_format
133
+ cache_versioning
134
+ cached_find_by
135
+ cached_find_by_statement
136
+ calculate
137
+ caller
138
+ caller_locations
139
+ can_use_fast_cache_version
140
+ catch
141
+ cattr_accessor
142
+ cattr_reader
143
+ cattr_writer
144
+ changed
145
+ changed_for_autosave
146
+ check_model_columns
147
+ check_record_limit
148
+ class
149
+ class_attribute
150
+ class_eval
151
+ class_exec
152
+ class_variable_get
153
+ class_variable_set
154
+ class_variables
155
+ clear_query_caches_for_current_thread
156
+ clear_reflections_cache
157
+ clone
158
+ collecting_queries_for_explain
159
+ collection_cache_key
160
+ collection_cache_versioning
161
+ column_defaults
162
+ column_for_attribute
163
+ column_names
164
+ columns
165
+ columns_hash
166
+ combine_signed_id_purposes
167
+ committed
168
+ composed_of
169
+ composite_query_constraints_list
170
+ compute_table_name
171
+ compute_type
172
+ concern
173
+ concerning
174
+ configurations
175
+ connected_to
176
+ connected_to_all_shards
177
+ connected_to_many
178
+ connected_to_stack
179
+ connecting_to
180
+ connection
181
+ connection_class
182
+ connection_class_for_self
183
+ connection_db_config
184
+ connection_handler
185
+ connection_pool
186
+ connection_specification_name
187
+ connects_to
188
+ const_added
189
+ const_get
190
+ const_missing
191
+ const_set
192
+ const_source_location
193
+ constants
194
+ content_columns
195
+ count
196
+ count_by_sql
197
+ counter_cached_association_names
198
+ create
199
+ create_or_find_by
200
+ create_with
201
+ current_preventing_writes
202
+ current_role
203
+ current_scope
204
+ current_shard
205
+ current_time_from_proper_timezone
206
+ current_transaction
207
+ custom_inspect_method_defined
208
+ custom_validation_context
209
+ decorate_attributes
210
+ decrement
211
+ decrement_counter
212
+ deep_dup
213
+ default_column_serializer
214
+ default_connection_handler
215
+ default_extensions
216
+ default_role
217
+ default_scope
218
+ default_scope_override
219
+ default_scoped
220
+ default_scopes
221
+ default_shard
222
+ define_attribute
223
+ define_attribute_method
224
+ define_attribute_method_pattern
225
+ define_attribute_methods
226
+ define_autosave_validation_callbacks
227
+ define_call
228
+ define_callbacks
229
+ define_default_attribute
230
+ define_delegated_type_methods
231
+ define_method
232
+ define_method_attribute
233
+ define_model_callbacks
234
+ define_non_cyclic_method
235
+ define_proxy_call
236
+ define_singleton_method
237
+ defined_enums
238
+ delegate
239
+ delegate_missing_to
240
+ delegated_type
241
+ delete
242
+ delete_all
243
+ delete_by
244
+ deprecate
245
+ deprecate_constant
246
+ descendants
247
+ destroy
248
+ destroy_all
249
+ destroy_association_async_batch_size
250
+ destroy_association_async_job
251
+ destroy_by
252
+ destroyed
253
+ deterministic_encrypted_attributes
254
+ discriminate_class_for_record
255
+ display
256
+ distinct
257
+ dup
258
+ duplicable
259
+ eager_load
260
+ eagerly_generate_alias_attribute_methods
261
+ encrypt_attribute
262
+ encrypted_attribute
263
+ encrypted_attributes
264
+ encrypts
265
+ enum
266
+ enum_for
267
+ enumerate_columns_in_select_statements
268
+ eql
269
+ equal
270
+ establish_connection
271
+ eval
272
+ evaluate_default_scope
273
+ except
274
+ excluding
275
+ exec
276
+ exec_explain
277
+ exit
278
+ extend
279
+ extended
280
+ extending
281
+ extract_associated
282
+ fail
283
+ false
284
+ fifth
285
+ filter_attributes
286
+ find
287
+ find_by
288
+ find_by_sql
289
+ find_by_token_for
290
+ find_each
291
+ find_in_batches
292
+ find_or_create_by
293
+ find_or_initialize_by
294
+ find_signed
295
+ find_sole_by
296
+ find_sti_class
297
+ first
298
+ first_or_create
299
+ first_or_initialize
300
+ fork
301
+ format
302
+ forty_two
303
+ fourth
304
+ freeze
305
+ from
306
+ frozen
307
+ full_table_name_prefix
308
+ full_table_name_suffix
309
+ gem
310
+ gem_original_require
311
+ generate_alias_attribute_methods
312
+ generate_alias_attributes
313
+ generate_association_writer
314
+ generate_relation_method
315
+ generate_unique_secure_token
316
+ generated_association_methods
317
+ generated_attribute_methods
318
+ generated_relation_methods
319
+ generated_token_verifier
320
+ generates_token_for
321
+ get_callbacks
322
+ get_primary_key
323
+ gets
324
+ global_current_scope
325
+ global_previous_schemes_for
326
+ global_variables
327
+ group
328
+ has_and_belongs_to_many
329
+ has_attribute
330
+ has_changes_to_save
331
+ has_defer_touch_attrs
332
+ has_destroy_flag
333
+ has_encrypted_attributes
334
+ has_many
335
+ has_many_inversing
336
+ has_one
337
+ has_secure_password
338
+ has_secure_token
339
+ has_transactional_callbacks
340
+ hash
341
+ having
342
+ hook_attribute_type
343
+ human_attribute_name
344
+ i18n_scope
345
+ id
346
+ ids
347
+ ignored_columns
348
+ immutable_strings_by_default
349
+ implicit_order_column
350
+ in
351
+ in_batches
352
+ in_order_of
353
+ include
354
+ include_relation_methods
355
+ include_root_in_json
356
+ included
357
+ included_modules
358
+ includes
359
+ increment
360
+ increment_counter
361
+ inheritance_column
362
+ inherited
363
+ initialize
364
+ initialize_clone
365
+ initialize_copy
366
+ initialize_dup
367
+ initialize_find_by_cache
368
+ initialize_generated_modules
369
+ initialize_load_schema_monitor
370
+ initialize_relation_delegate_cache
371
+ insert
372
+ insert_all
373
+ inspect
374
+ inspection_filter
375
+ instance_eval
376
+ instance_exec
377
+ instance_method
378
+ instance_methods
379
+ instance_of
380
+ instance_values
381
+ instance_variable_defined
382
+ instance_variable_get
383
+ instance_variable_names
384
+ instance_variable_set
385
+ instance_variables
386
+ instance_variables_to_inspect
387
+ instantiate
388
+ instantiate_instance_of
389
+ internal_metadata_table_name
390
+ invalid
391
+ inverse_polymorphic_association_changed
392
+ invert_where
393
+ is_a
394
+ iterator
395
+ itself
396
+ j
397
+ jj
398
+ joins
399
+ kind_of
400
+ lambda
401
+ last
402
+ lease_connection
403
+ left_joins
404
+ left_outer_joins
405
+ limit
406
+ load
407
+ load_schema
408
+ local_stored_attributes
409
+ local_variables
410
+ lock
411
+ lock_optimistically
412
+ locking_column
413
+ locking_enabled
414
+ logger
415
+ lookup_ancestors
416
+ loop
417
+ marked_for_destruction
418
+ mattr_accessor
419
+ mattr_reader
420
+ mattr_writer
421
+ maximum
422
+ merge
423
+ method
424
+ method_added
425
+ method_missing
426
+ method_removed
427
+ method_undefined
428
+ method_visibility
429
+ methods
430
+ minimum
431
+ model_name
432
+ module_eval
433
+ module_exec
434
+ module_parent
435
+ module_parent_name
436
+ module_parents
437
+ name
438
+ nested_attributes_options
439
+ nested_records_changed_for_autosave
440
+ new
441
+ new_record
442
+ next_sequence_value
443
+ nil
444
+ no_touching
445
+ no_warning_require
446
+ none
447
+ normalize_callback_params
448
+ normalize_value_for
449
+ normalized_attributes
450
+ normalized_reflections
451
+ normalizes
452
+ object_id
453
+ offset
454
+ only
455
+ only_columns
456
+ open
457
+ optimizer_hints
458
+ or
459
+ order
460
+ override_accessors_to_preserve_original
461
+ p
462
+ param_delimiter
463
+ partial_inserts
464
+ partial_updates
465
+ pending_attribute_modifications
466
+ persisted
467
+ pick
468
+ pk_attribute
469
+ pluck
470
+ pluralize_table_names
471
+ polymorphic_class_for
472
+ polymorphic_name
473
+ pool_transaction_isolation_level
474
+ pp
475
+ predicate_builder
476
+ predicate_for_validation_context
477
+ preload
478
+ prepend
479
+ prepend_option
480
+ prepended
481
+ presence
482
+ presence_in
483
+ present
484
+ preserve_original_encrypted
485
+ previously_new_record
486
+ previously_persisted
487
+ primary_abstract_class
488
+ primary_key
489
+ primary_key_prefix_type
490
+ primary_key_values_present
491
+ print
492
+ printf
493
+ private
494
+ private_class_method
495
+ private_constant
496
+ private_instance_methods
497
+ private_methods
498
+ proc
499
+ prohibit_shard_swapping
500
+ protected
501
+ protected_environments
502
+ protected_instance_methods
503
+ protected_methods
504
+ public
505
+ public_class_method
506
+ public_constant
507
+ public_instance_method
508
+ public_instance_methods
509
+ public_method
510
+ public_methods
511
+ public_send
512
+ putc
513
+ puts
514
+ query_constraints
515
+ query_constraints_list
516
+ quote_bound_value
517
+ quoted_primary_key
518
+ quoted_table_name
519
+ raise
520
+ raise_conflict_error
521
+ raise_if_bind_arity_mismatch
522
+ raise_nested_attributes_record_not_found
523
+ rand
524
+ reader_method
525
+ readline
526
+ readlines
527
+ readonly
528
+ readonly_attributes
529
+ record_timestamps
530
+ redefine_method
531
+ redefine_singleton_method
532
+ references
533
+ refinements
534
+ reflect_on_aggregation
535
+ reflect_on_all_aggregations
536
+ reflect_on_all_associations
537
+ reflect_on_all_autosave_associations
538
+ reflect_on_association
539
+ reflections
540
+ regroup
541
+ reject_new_record
542
+ relation
543
+ relation_delegate_class
544
+ release_connection
545
+ reload_schema_from_cache
546
+ remove_class_variable
547
+ remove_connection
548
+ remove_const
549
+ remove_instance_variable
550
+ remove_method
551
+ remove_possible_method
552
+ remove_possible_singleton_method
553
+ render_bind
554
+ reorder
555
+ replace_bind_variable
556
+ replace_bind_variables
557
+ replace_named_bind_variables
558
+ require
559
+ require_dependency
560
+ require_relative
561
+ reselect
562
+ reset_callbacks
563
+ reset_column_information
564
+ reset_counters
565
+ reset_default_attributes
566
+ reset_locking_column
567
+ reset_primary_key
568
+ reset_sequence_name
569
+ reset_table_name
570
+ resolve_attribute_name
571
+ resolve_config_for_connection
572
+ resolve_type_name
573
+ respond_to
574
+ respond_to_missing
575
+ respond_to_without_attributes
576
+ restore_attribute
577
+ retrieve_connection
578
+ rewhere
579
+ rolledback
580
+ ruby2_keywords
581
+ run_commit_callbacks_on_first_saved_instances_in_transaction
582
+ run_validations
583
+ sanitize_sql
584
+ sanitize_sql_array
585
+ sanitize_sql_for_assignment
586
+ sanitize_sql_for_conditions
587
+ sanitize_sql_for_order
588
+ sanitize_sql_hash_for_assignment
589
+ sanitize_sql_like
590
+ save
591
+ saved_change_to_attribute
592
+ saved_changes
593
+ schema_cache
594
+ schema_migrations_table_name
595
+ scheme_for
596
+ scope
597
+ scope_attributes
598
+ scope_for_association
599
+ scope_registry
600
+ second
601
+ second_to_last
602
+ select
603
+ self
604
+ send
605
+ sequence_name
606
+ serialize
607
+ set_base_class
608
+ set_callback
609
+ set_callbacks
610
+ set_options_for_callback
611
+ set_temporary_name
612
+ set_trace_func
613
+ shard_keys
614
+ shard_selector
615
+ should_record_timestamps
616
+ signed_id_verifier
617
+ signed_id_verifier_secret
618
+ silence_redefinition_of_method
619
+ singleton_class
620
+ singleton_method
621
+ singleton_method_added
622
+ singleton_method_removed
623
+ singleton_method_undefined
624
+ singleton_methods
625
+ skip_callback
626
+ skip_time_zone_conversion_for_attributes
627
+ sleep
628
+ sole
629
+ source_attribute_from_preserved_attribute
630
+ spawn
631
+ sprintf
632
+ srand
633
+ sti_class_for
634
+ sti_name
635
+ store
636
+ store_accessor
637
+ store_full_class_name
638
+ store_full_sti_class
639
+ stored_attributes
640
+ strict_loading
641
+ strict_loading_all
642
+ strict_loading_by_default
643
+ strict_loading_mode
644
+ strict_loading_n_plus_one_only
645
+ subclass_from_attributes
646
+ subclasses
647
+ sum
648
+ superclass
649
+ suppress
650
+ symbol_column_to_string
651
+ syscall
652
+ system
653
+ table_name
654
+ table_name_prefix
655
+ table_name_suffix
656
+ take
657
+ tap
658
+ test
659
+ then
660
+ third
661
+ third_to_last
662
+ thread_cattr_accessor
663
+ thread_cattr_reader
664
+ thread_cattr_writer
665
+ thread_mattr_accessor
666
+ thread_mattr_reader
667
+ thread_mattr_writer
668
+ throw
669
+ time_zone_aware_attributes
670
+ time_zone_aware_types
671
+ timestamp_attributes_for_create
672
+ timestamp_attributes_for_create_in_model
673
+ timestamp_attributes_for_update
674
+ timestamp_attributes_for_update_in_model
675
+ to_enum
676
+ to_json
677
+ to_param
678
+ to_query
679
+ to_s
680
+ to_yaml
681
+ toggle
682
+ token_definitions
683
+ touch_all
684
+ touch_attributes_with_time
685
+ trace_var
686
+ transaction
687
+ transaction_include_any_action
688
+ trap
689
+ trigger_transactional_callbacks
690
+ true
691
+ try
692
+ type_caster
693
+ type_condition
694
+ type_for_attribute
695
+ type_for_column
696
+ uncached
697
+ undecorated_table_name
698
+ undef_method
699
+ undefine_attribute_methods
700
+ undefined_instance_methods
701
+ unscope
702
+ unscoped
703
+ untrace_var
704
+ update
705
+ update_all
706
+ update_attribute
707
+ update_counters
708
+ upsert
709
+ upsert_all
710
+ using
711
+ valid
712
+ validate
713
+ validate_column_size
714
+ validates
715
+ validates_absence_of
716
+ validates_acceptance_of
717
+ validates_associated
718
+ validates_comparison_of
719
+ validates_confirmation_of
720
+ validates_each
721
+ validates_exclusion_of
722
+ validates_format_of
723
+ validates_inclusion_of
724
+ validates_length_of
725
+ validates_numericality_of
726
+ validates_presence_of
727
+ validates_size_of
728
+ validates_uniqueness_of
729
+ validates_with
730
+ validating_belongs_to_for
731
+ validators
732
+ validators_on
733
+ warn
734
+ where
735
+ while_preventing_writes
736
+ will_be_destroyed
737
+ will_save_change_to_attribute
738
+ with
739
+ with_connection
740
+ with_pool_transaction_isolation_level
741
+ with_recursive
742
+ with_role_and_shard
743
+ without
744
+ writer_method
745
+ yaml_encoder
746
+ yaml_tag
747
+ yield_self`.split("\n"));
748
+ //#endregion
749
+ //#region src/helper/humanizer.ts
750
+ function irregular(singular, plural) {
751
+ return {
752
+ plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
753
+ singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
754
+ };
755
+ }
756
+ function wholeWordIrregular(singular, plural) {
757
+ return {
758
+ plural: [`^${singular}$`, plural],
759
+ singular: [`^${plural}$`, singular]
760
+ };
761
+ }
762
+ const IRREGULARS = [
763
+ irregular("person", "people"),
764
+ irregular("man", "men"),
765
+ irregular("human", "humans"),
766
+ irregular("child", "children"),
767
+ irregular("sex", "sexes"),
768
+ irregular("glove", "gloves"),
769
+ irregular("move", "moves"),
770
+ irregular("goose", "geese"),
771
+ irregular("wave", "waves"),
772
+ irregular("foot", "feet"),
773
+ irregular("tooth", "teeth"),
774
+ irregular("curriculum", "curricula"),
775
+ irregular("database", "databases"),
776
+ irregular("zombie", "zombies"),
777
+ irregular("personnel", "personnel"),
778
+ irregular("cache", "caches"),
779
+ wholeWordIrregular("ex", "exes"),
780
+ wholeWordIrregular("is", "are"),
781
+ wholeWordIrregular("that", "those"),
782
+ wholeWordIrregular("this", "these"),
783
+ wholeWordIrregular("bus", "buses"),
784
+ wholeWordIrregular("die", "dice"),
785
+ wholeWordIrregular("tie", "ties")
786
+ ];
787
+ const PLURAL_RULES = [
788
+ ["$", "s"],
789
+ ["s$", "s"],
790
+ ["(ax|test)is$", "$1es"],
791
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
792
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
793
+ ["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
794
+ ["([dti])um$", "$1a"],
795
+ ["sis$", "ses"],
796
+ ["(?:([^f])fe|([lr])f)$", "$1$2ves"],
797
+ ["(hive)$", "$1s"],
798
+ ["([^aeiouy]|qu)y$", "$1ies"],
799
+ ["(x|ch|ss|sh)$", "$1es"],
800
+ ["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
801
+ ["(^[m|l])ouse$", "$1ice"],
802
+ ["^(ox)$", "$1en"],
803
+ ["(quiz)$", "$1zes"],
804
+ ["(buz|blit|walt)z$", "$1zes"],
805
+ ["(hoo|lea|loa|thie)f$", "$1ves"],
806
+ ["(alumn|alg|larv|vertebr)a$", "$1ae"],
807
+ ["(criteri|phenomen)on$", "$1a"],
808
+ ...IRREGULARS.map((rule) => rule.plural)
809
+ ].map(([pattern, replacement]) => ({
810
+ pattern: new RegExp(pattern, "iu"),
811
+ replacement
812
+ }));
813
+ const SINGULAR_RULES = [
814
+ ["s$", ""],
815
+ ["(n)ews$", "$1ews"],
816
+ ["([dti])a$", "$1um"],
817
+ ["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
818
+ ["([^f])ves$", "$1fe"],
819
+ ["(hive)s$", "$1"],
820
+ ["(tive)s$", "$1"],
821
+ ["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
822
+ ["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
823
+ ["(s)eries$", "$1eries"],
824
+ ["(m)ovies$", "$1ovie"],
825
+ ["(x|ch|ss|sh)es$", "$1"],
826
+ ["(^[m|l])ice$", "$1ouse"],
827
+ ["(?<!^[a-z])(o)es$", "$1"],
828
+ ["(shoe)s$", "$1"],
829
+ ["(cris|ax|test)es$", "$1is"],
830
+ ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
831
+ ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
832
+ ["^(ox)en", "$1"],
833
+ ["(matr|d)ices$", "$1ix"],
834
+ ["(vert|ind)ices$", "$1ex"],
835
+ ["(quiz)zes$", "$1"],
836
+ ["(buz|blit|walt)zes$", "$1z"],
837
+ ["(alumn|alg|larv|vertebr)ae$", "$1a"],
838
+ ["(criteri|phenomen)a$", "$1on"],
839
+ ["([b|r|c]ook|room|smooth)ies$", "$1ie"],
840
+ ...IRREGULARS.map((rule) => rule.singular)
841
+ ].map(([pattern, replacement]) => ({
842
+ pattern: new RegExp(pattern, "iu"),
843
+ replacement
844
+ }));
845
+ const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
846
+ "staff",
847
+ "training",
848
+ "equipment",
849
+ "information",
850
+ "corn",
851
+ "milk",
852
+ "rice",
853
+ "money",
854
+ "species",
855
+ "series",
856
+ "fish",
857
+ "sheep",
858
+ "deer",
859
+ "aircraft",
860
+ "oz",
861
+ "tsp",
862
+ "tbsp",
863
+ "ml",
864
+ "l",
865
+ "water",
866
+ "waters",
867
+ "semen",
868
+ "sperm",
869
+ "bison",
870
+ "grass",
871
+ "hair",
872
+ "mud",
873
+ "elk",
874
+ "luggage",
875
+ "moose",
876
+ "offspring",
877
+ "salmon",
878
+ "shrimp",
879
+ "someone",
880
+ "swine",
881
+ "trout",
882
+ "tuna",
883
+ "corps",
884
+ "scissors",
885
+ "means",
886
+ "mail",
887
+ "metadata"
888
+ ]);
889
+ function isUpperCaseLetter(char) {
890
+ return char !== char.toLowerCase() && char === char.toUpperCase();
891
+ }
892
+ function isLowerCaseLetter(char) {
893
+ return char !== char.toUpperCase() && char === char.toLowerCase();
894
+ }
895
+ function applyRules(rules, word) {
896
+ if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
897
+ const rule = rules.findLast((candidate) => candidate.pattern.test(word));
898
+ if (rule === void 0) return null;
899
+ const result = word.replace(rule.pattern, rule.replacement);
900
+ const first = result.charAt(0);
901
+ return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
902
+ }
903
+ /**
904
+ * Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
905
+ * is returned as it is.
906
+ *
907
+ * @param word - The word to pluralize.
908
+ * @returns The plural form Humanizer 2.14.1 gives.
909
+ */
910
+ function pluralize(word) {
911
+ const result = applyRules(PLURAL_RULES, word);
912
+ const asSingular = applyRules(SINGULAR_RULES, word);
913
+ const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
914
+ return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
915
+ }
916
+ //#endregion
11
917
  //#region src/helper/activerecord.ts
12
918
  function fieldColumn$1(model, fieldName) {
13
919
  return model.fields.find((f) => f.name === fieldName)?.dbName ?? fieldName;
14
920
  }
921
+ function primaryKeyFields(model) {
922
+ const idField = model.fields.find((f) => f.isId);
923
+ return idField ? [idField.name] : model.primaryKey?.fields ?? [];
924
+ }
925
+ function isSameList$1(a, b) {
926
+ return a.length === b.length && a.every((value, i) => value === b[i]);
927
+ }
928
+ function rubyArray(items) {
929
+ if (items.length === 0) return "[]";
930
+ if (items.every((item) => /^:[a-z_][a-z0-9_]*$/u.test(item))) return `%i[${items.map((item) => item.slice(1)).join(" ")}]`;
931
+ if (items.every((item) => /^"[^\s"\\#\]]+"$/u.test(item))) return `%w[${items.map((item) => item.slice(1, -1)).join(" ")}]`;
932
+ return `[ ${items.join(", ")} ]`;
933
+ }
934
+ function rubyInteger(value) {
935
+ const [sign, digits] = value.startsWith("-") ? ["-", value.slice(1)] : ["", value];
936
+ return digits.length < 5 ? value : `${sign}${digits.replaceAll(/\B(?=(\d{3})+(?!\d))/gu, "_")}`;
937
+ }
15
938
  function foreignKeyOpt(columns) {
16
- return columns.length > 1 ? `foreign_key: [${columns.map((c) => `:${c}`).join(", ")}]` : `foreign_key: "${columns[0]}"`;
939
+ return columns.length > 1 ? `foreign_key: ${rubyArray(columns.map((c) => `:${c}`))}` : `foreign_key: "${columns[0]}"`;
940
+ }
941
+ function primaryKeyOpt(columns, referencesPrimaryKey) {
942
+ return referencesPrimaryKey ? [] : columns.length > 1 ? [`primary_key: ${rubyArray(columns.map((c) => `:${c}`))}`] : [`primary_key: "${columns[0]}"`];
943
+ }
944
+ const DEPENDENT = {
945
+ Cascade: "destroy",
946
+ SetNull: "nullify",
947
+ Restrict: "restrict_with_error",
948
+ NoAction: "restrict_with_error"
949
+ };
950
+ function rubyCall(method, positional, keywords) {
951
+ const head = `${method} ${positional.join(", ")}`;
952
+ const [firstKeyword, ...rest] = keywords;
953
+ if (firstKeyword === void 0) return head;
954
+ const fits = `${head}, ${firstKeyword}`.length + 2 <= 120;
955
+ const indent = " ".repeat(fits ? head.length + 2 : method.length + 1);
956
+ const lines = fits ? [`${head}, ${firstKeyword}`] : [`${head},`, `${indent}${firstKeyword}`];
957
+ for (const opt of rest) {
958
+ const last = lines.length - 1;
959
+ const joined = `${lines[last]}, ${opt}`;
960
+ if (joined.length + 2 <= 120) lines[last] = joined;
961
+ else {
962
+ lines[last] = `${lines[last]},`;
963
+ lines.push(`${indent}${opt}`);
964
+ }
965
+ }
966
+ return lines.join("\n");
967
+ }
968
+ function arCalls(documentation, on) {
969
+ const calls = [];
970
+ const problems = [];
971
+ let annotated = false;
972
+ for (const raw of (documentation ?? "").split("\n")) {
973
+ const line = raw.trim();
974
+ if (line.startsWith("@ar.")) {
975
+ annotated = true;
976
+ const call = line.slice(4).trim();
977
+ calls.push(call);
978
+ if (on === "field") {
979
+ if (call.includes("(") && !call.endsWith(")")) problems.push(`the @ar. call "${call}" does not close its parentheses on its line; an @ar. call is one /// line`);
980
+ else if (!/^[a-z_][a-z0-9_]*(?:\s*\([\s\S]*\))?$/u.test(call)) problems.push(`the @ar. call "${call}" is not name or name(arguments)`);
981
+ } else if (call.endsWith(",")) problems.push(`the @ar. line "${call}" ends in a comma as if it went on; an @ar. call is one /// line`);
982
+ else if (!/^[a-z_][a-z0-9_]*[!?]?(?:\s*\([\s\S]*\)|\s[\s\S]*)?$/u.test(call)) problems.push(`the @ar. line "${call}" is not a Ruby call, name, name(arguments) or name arguments`);
983
+ } else if (line !== "" && !isAnnotationLine(line) && annotated) problems.push(`the line "${line}" comes after an @ar. call; write the description above them`);
984
+ }
985
+ return {
986
+ calls,
987
+ problems
988
+ };
989
+ }
990
+ /**
991
+ * What keeps the schema's `@ar.` comments from being read: a description
992
+ * written after the calls, a call left open, a call in a shape that is not a
993
+ * validator. Each names the model or field it is on.
994
+ */
995
+ function activeRecordProblems(models) {
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
+ })]);
1004
+ }
1005
+ function splitArguments(text) {
1006
+ const parts = [];
1007
+ let depth = 0;
1008
+ let quote = null;
1009
+ let start = 0;
1010
+ for (let i = 0; i < text.length; i += 1) {
1011
+ const ch = text[i];
1012
+ if (quote !== null) {
1013
+ if (ch === "\\") i += 1;
1014
+ else if (ch === quote) quote = null;
1015
+ } else if (ch === "\"" || ch === "'") quote = ch;
1016
+ else if (ch === "(" || ch === "{" || ch === "[") depth += 1;
1017
+ else if (ch === ")" || ch === "}" || ch === "]") depth -= 1;
1018
+ else if (ch === "," && depth === 0) {
1019
+ parts.push(text.slice(start, i));
1020
+ start = i + 1;
1021
+ }
1022
+ }
1023
+ parts.push(text.slice(start));
1024
+ return parts.map((part) => part.trim()).filter((part) => part.length > 0);
1025
+ }
1026
+ const PLURAL_FORMS = /* @__PURE__ */ new Set([
1027
+ "zero",
1028
+ "one",
1029
+ "two",
1030
+ "few",
1031
+ "many",
1032
+ "other"
1033
+ ]);
1034
+ function stringLiteral(value) {
1035
+ const m = value.match(/^(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')$/u);
1036
+ return m ? (m[1] ?? m[2] ?? "").replaceAll("\\\"", "\"") : null;
1037
+ }
1038
+ function translations(value) {
1039
+ const inner = value.match(/^\{([\s\S]*)\}$/u)?.[1];
1040
+ if (inner === void 0) return null;
1041
+ const found = [];
1042
+ for (const pair of splitArguments(inner)) {
1043
+ const m = pair.match(/^([a-z]{2,3}(?:[-_][A-Za-z0-9]+)?):\s*([\s\S]+)$/u);
1044
+ if (!m) return null;
1045
+ const [, locale = "", rest = ""] = m;
1046
+ const text = stringLiteral(rest);
1047
+ if (text !== null) {
1048
+ found.push({
1049
+ locale,
1050
+ form: null,
1051
+ text
1052
+ });
1053
+ continue;
1054
+ }
1055
+ const forms = rest.match(/^\{([\s\S]*)\}$/u)?.[1];
1056
+ if (forms === void 0) return null;
1057
+ for (const formPair of splitArguments(forms)) {
1058
+ const f = formPair.match(/^([a-z]+):\s*([\s\S]+)$/u);
1059
+ const formText = f ? stringLiteral(f[2] ?? "") : null;
1060
+ if (!f || formText === null || !PLURAL_FORMS.has(f[1] ?? "")) return null;
1061
+ found.push({
1062
+ locale,
1063
+ form: f[1] ?? "",
1064
+ text: formText
1065
+ });
1066
+ }
1067
+ }
1068
+ return found.length === 0 ? null : found;
1069
+ }
1070
+ const MESSAGE_KEYS = {
1071
+ presence: ["blank"],
1072
+ absence: ["present"],
1073
+ format: ["invalid"],
1074
+ uniqueness: ["taken"],
1075
+ inclusion: ["inclusion"],
1076
+ exclusion: ["exclusion"],
1077
+ acceptance: ["accepted"],
1078
+ confirmation: ["confirmation"],
1079
+ associated: ["invalid"],
1080
+ length: [
1081
+ "too_long",
1082
+ "too_short",
1083
+ "wrong_length"
1084
+ ]
1085
+ };
1086
+ const COMPARISON_KEYS = /* @__PURE__ */ new Set([
1087
+ "greater_than",
1088
+ "greater_than_or_equal_to",
1089
+ "equal_to",
1090
+ "less_than",
1091
+ "less_than_or_equal_to",
1092
+ "other_than",
1093
+ "in",
1094
+ "odd",
1095
+ "even"
1096
+ ]);
1097
+ function messageKeys(validator, options) {
1098
+ const found = MESSAGE_KEYS[validator];
1099
+ if (found !== void 0) return found;
1100
+ if (validator !== "numericality" && validator !== "comparison") return ["invalid"];
1101
+ const keys = options.flatMap((option) => {
1102
+ const name = option.match(/^([a-z_]+):/u)?.[1] ?? "";
1103
+ return COMPARISON_KEYS.has(name) ? [name] : name === "only_integer" && validator === "numericality" ? ["not_an_integer"] : [];
1104
+ });
1105
+ return validator === "numericality" ? ["not_a_number", ...keys] : keys;
1106
+ }
1107
+ function validatorCall(call) {
1108
+ const match = call.match(/^([a-z_][a-z0-9_]*)\s*(?:\(([\s\S]*)\))?$/u);
1109
+ if (!match) return {
1110
+ validator: null,
1111
+ option: call,
1112
+ messages: []
1113
+ };
1114
+ const [, validator = "", args = ""] = match;
1115
+ const messages = [];
1116
+ if (validator === "name") {
1117
+ for (const t of translations(`{ ${args} }`) ?? []) messages.push({
1118
+ key: "name",
1119
+ locale: t.locale,
1120
+ form: t.form,
1121
+ text: t.text
1122
+ });
1123
+ return {
1124
+ validator,
1125
+ option: null,
1126
+ messages
1127
+ };
1128
+ }
1129
+ if (args.trim() === "false") return {
1130
+ validator,
1131
+ option: null,
1132
+ messages
1133
+ };
1134
+ const kept = [];
1135
+ const translated = [];
1136
+ for (const argument of splitArguments(args)) {
1137
+ const pair = argument.match(/^([a-z_][a-z0-9_]*):\s*([\s\S]+)$/u);
1138
+ const found = pair ? translations(pair[2] ?? "") : null;
1139
+ if (pair && found) translated.push({
1140
+ name: pair[1] ?? "",
1141
+ found
1142
+ });
1143
+ else kept.push(argument);
1144
+ }
1145
+ for (const { name, found } of translated) for (const key of name === "message" ? messageKeys(validator, kept) : [name]) for (const t of found) messages.push({
1146
+ key,
1147
+ locale: t.locale,
1148
+ form: t.form,
1149
+ text: t.text
1150
+ });
1151
+ return {
1152
+ validator,
1153
+ option: kept.length === 0 ? `${validator}: true` : `${validator}: { ${kept.join(", ")} }`,
1154
+ messages
1155
+ };
1156
+ }
1157
+ function form(m) {
1158
+ return m.form === null ? [] : [m.form];
1159
+ }
1160
+ function setPath(tree, path, text) {
1161
+ const [head, ...rest] = path;
1162
+ if (head === void 0) return;
1163
+ if (rest.length === 0) {
1164
+ tree[head] = text;
1165
+ return;
1166
+ }
1167
+ const next = tree[head];
1168
+ const child = typeof next === "object" ? next : {};
1169
+ tree[head] = child;
1170
+ setPath(child, rest, text);
1171
+ }
1172
+ function yamlLines(tree, depth) {
1173
+ const lines = [];
1174
+ for (const [key, value] of Object.entries(tree)) if (typeof value === "string") lines.push(`${" ".repeat(depth)}${key}: "${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`);
1175
+ else lines.push(`${" ".repeat(depth)}${key}:`, ...yamlLines(value, depth + 1));
1176
+ return lines;
1177
+ }
1178
+ /**
1179
+ * The locale files of the schema's `@ar.` calls, laid out as the Rails i18n
1180
+ * guide organises them: `models/<model>/<locale>.yml`, one directory per
1181
+ * model and one file per locale it names, so model and attribute names stay
1182
+ * apart from the views' text and the defaults. Each holds that model's name
1183
+ * from `@ar.name(ja: "...")`, its attributes' names, and the error messages
1184
+ * of its validators' translated options, under the keys Rails reads
1185
+ * (`activerecord.errors.models.todo.attributes.title.blank`).
1186
+ */
1187
+ function activeRecordLocaleFiles(models) {
1188
+ return models.flatMap((model) => {
1189
+ const modelKey = makeSnakeCase(model.name);
1190
+ const trees = /* @__PURE__ */ new Map();
1191
+ const tree = (locale) => {
1192
+ const found = trees.get(locale) ?? {};
1193
+ trees.set(locale, found);
1194
+ return found;
1195
+ };
1196
+ for (const call of arCalls(model.documentation, "model").calls) {
1197
+ const { validator, messages } = validatorCall(call);
1198
+ if (validator !== "name") continue;
1199
+ for (const m of messages) setPath(tree(m.locale), [
1200
+ "activerecord",
1201
+ "models",
1202
+ modelKey,
1203
+ ...form(m)
1204
+ ], m.text);
1205
+ }
1206
+ for (const field of model.fields) {
1207
+ const attribute = field.kind === "object" ? makeSnakeCase(field.name) : field.dbName ?? field.name;
1208
+ for (const call of arCalls(field.documentation, "field").calls) {
1209
+ const { validator, messages } = validatorCall(call);
1210
+ if (field.kind === "object" && validator !== "name") continue;
1211
+ for (const m of messages) setPath(tree(m.locale), validator === "name" ? [
1212
+ "activerecord",
1213
+ "attributes",
1214
+ modelKey,
1215
+ attribute,
1216
+ ...form(m)
1217
+ ] : [
1218
+ "activerecord",
1219
+ "errors",
1220
+ "models",
1221
+ modelKey,
1222
+ "attributes",
1223
+ attribute,
1224
+ m.key,
1225
+ ...form(m)
1226
+ ], m.text);
1227
+ }
1228
+ }
1229
+ return [...trees].toSorted(([a], [b]) => a.localeCompare(b)).map(([locale, content]) => ({
1230
+ fileName: `models/${modelKey}/${locale}.yml`,
1231
+ code: `${yamlLines({ [locale]: content }, 0).join("\n")}\n`
1232
+ }));
1233
+ });
17
1234
  }
18
- function hasPrimaryKeyOpt(columns) {
19
- return columns.length > 1 ? `, primary_key: [${columns.map((c) => `:${c}`).join(", ")}]` : columns[0] === "id" ? "" : `, primary_key: "${columns[0]}"`;
1235
+ function symbolKey(name) {
1236
+ return /^[a-z_][a-z0-9_]*$/u.test(name) ? name : `"${name}"`;
20
1237
  }
21
1238
  function getAssociations$5(model, allModels) {
22
1239
  const belongsTo = [];
@@ -29,6 +1246,7 @@ function getAssociations$5(model, allModels) {
29
1246
  const targetModel = allModels.find((m) => m.name === field.type);
30
1247
  const referencedField = field.relationToFields?.[0] ?? "id";
31
1248
  const referencedFields = field.relationToFields ?? ["id"];
1249
+ const inverse = targetModel?.fields.find((f) => f.kind === "object" && f.relationName === field.relationName && !(f.relationFromFields && f.relationFromFields.length > 0));
32
1250
  belongsTo.push({
33
1251
  name: field.name,
34
1252
  targetModel: field.type,
@@ -36,7 +1254,10 @@ function getAssociations$5(model, allModels) {
36
1254
  primaryKeyColumn: targetModel ? fieldColumn$1(targetModel, referencedField) : referencedField,
37
1255
  foreignKeyColumns: field.relationFromFields.map((c) => fieldColumn$1(model, c)),
38
1256
  primaryKeyColumns: referencedFields.map((c) => targetModel ? fieldColumn$1(targetModel, c) : c),
39
- optional: !field.isRequired
1257
+ referencesPrimaryKey: isSameList$1(referencedFields, targetModel === void 0 ? ["id"] : primaryKeyFields(targetModel)),
1258
+ optional: !field.isRequired,
1259
+ inverse: inverse?.name ?? null,
1260
+ inverseIsList: inverse?.isList ?? false
40
1261
  });
41
1262
  continue;
42
1263
  }
@@ -57,23 +1278,31 @@ function getAssociations$5(model, allModels) {
57
1278
  }
58
1279
  const fkField = targetModel.fields.find((f) => f.relationName === field.relationName && f.relationFromFields && f.relationFromFields.length > 0);
59
1280
  const foreignKey = fkField?.relationFromFields?.[0];
60
- if (!foreignKey) continue;
1281
+ if (!(fkField && foreignKey)) continue;
61
1282
  const foreignKeyColumn = fieldColumn$1(targetModel, foreignKey);
62
- const foreignKeyColumns = (fkField?.relationFromFields ?? [foreignKey]).map((c) => fieldColumn$1(targetModel, c));
63
- const primaryKeyColumns = (fkField?.relationToFields ?? ["id"]).map((c) => fieldColumn$1(model, c));
1283
+ const foreignKeyColumns = (fkField.relationFromFields ?? [foreignKey]).map((c) => fieldColumn$1(targetModel, c));
1284
+ const primaryKeyColumns = (fkField.relationToFields ?? ["id"]).map((c) => fieldColumn$1(model, c));
1285
+ const referencesPrimaryKey = isSameList$1(fkField.relationToFields ?? ["id"], primaryKeyFields(model));
1286
+ const onDelete = fkField.relationOnDelete ?? (fkField.isRequired ? "Restrict" : "SetNull");
64
1287
  if (field.isList) hasMany.push({
65
1288
  name: field.name,
66
1289
  targetModel: field.type,
67
1290
  foreignKeyColumn,
68
1291
  foreignKeyColumns,
69
- primaryKeyColumns
1292
+ primaryKeyColumns,
1293
+ referencesPrimaryKey,
1294
+ inverse: fkField.name,
1295
+ onDelete
70
1296
  });
71
1297
  else hasOne.push({
72
1298
  name: field.name,
73
1299
  targetModel: field.type,
74
1300
  foreignKeyColumn,
75
1301
  foreignKeyColumns,
76
- primaryKeyColumns
1302
+ primaryKeyColumns,
1303
+ referencesPrimaryKey,
1304
+ inverse: fkField.name,
1305
+ onDelete
77
1306
  });
78
1307
  }
79
1308
  return {
@@ -83,70 +1312,214 @@ function getAssociations$5(model, allModels) {
83
1312
  habtm
84
1313
  };
85
1314
  }
1315
+ function rubyString(value) {
1316
+ return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("#", "\\#").replaceAll("\n", "\\n").replaceAll("\r", "\\r")}"`;
1317
+ }
1318
+ function rubyDefault(type, value) {
1319
+ if (typeof value === "object") return null;
1320
+ switch (type) {
1321
+ case "Boolean": return value === true || value === "true" ? "true" : "false";
1322
+ case "Int":
1323
+ case "BigInt": return rubyInteger(String(value));
1324
+ case "Float": return String(value);
1325
+ case "Decimal": return `BigDecimal(${rubyString(String(value))})`;
1326
+ case "String": return rubyString(String(value));
1327
+ case "DateTime": return `Time.iso8601(${rubyString(String(value))})`;
1328
+ case "Json": return `JSON.parse(${rubyString(String(value))})`;
1329
+ default: return null;
1330
+ }
1331
+ }
1332
+ function nativeLength(field) {
1333
+ if (!field.nativeType) return null;
1334
+ const [name, args] = field.nativeType;
1335
+ if (![
1336
+ "VarChar",
1337
+ "Char",
1338
+ "NVarChar",
1339
+ "NChar"
1340
+ ].includes(name)) return null;
1341
+ const length = Number(args[0]);
1342
+ return Number.isInteger(length) && length > 0 ? length : null;
1343
+ }
86
1344
  function activeRecordModels(models, allModels, enums) {
87
1345
  const contextModels = allModels ?? models;
88
1346
  const enumMap = new Map((enums ?? []).map((e) => [e.name, e.values]));
89
1347
  return models.map((model) => {
90
1348
  const associations = getAssociations$5(model, contextModels);
91
- const tableName = model.dbName ?? makeSnakeCase(model.name);
1349
+ const className = makePascalCase(model.name);
1350
+ const tableName = model.dbName ?? model.name;
1351
+ const tableNameLines = tableName === pluralize(makeSnakeCase(model.name)) ? [] : [`self.table_name = "${tableName}"`];
92
1352
  const idField = model.fields.find((f) => f.isId);
93
1353
  const compositePkColumns = (model.primaryKey?.fields ?? []).map((name) => fieldColumn$1(model, name));
94
- 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(", ")}]`] : [];
95
- const inheritanceColumnLines = model.fields.some((f) => (f.kind === "scalar" || f.kind === "enum") && (f.dbName ?? f.name) === "type") ? [" self.inheritance_column = nil"] : [];
96
- const attributeLines = model.fields.filter((f) => f.kind === "scalar" && f.type === "String").flatMap((f) => {
1354
+ const primaryKeyLines = idField ? (idField.dbName ?? idField.name) !== "id" ? [`self.primary_key = "${idField.dbName ?? idField.name}"`] : [] : compositePkColumns.length > 0 ? [`self.primary_key = ${rubyArray(compositePkColumns.map((c) => `"${c}"`))}`] : [];
1355
+ const inheritanceColumnLines = model.fields.some((f) => (f.kind === "scalar" || f.kind === "enum") && (f.dbName ?? f.name) === "type") ? ["self.inheritance_column = nil"] : [];
1356
+ const createdField = model.fields.find((f) => f.kind === "scalar" && f.type === "DateTime" && !f.isList && (f.name === "createdAt" || f.name === "created_at"));
1357
+ const updatedField = model.fields.find((f) => f.isUpdatedAt) ?? model.fields.find((f) => f.kind === "scalar" && f.type === "DateTime" && !f.isList && [
1358
+ "updatedAt",
1359
+ "updated_at",
1360
+ "modifiedAt",
1361
+ "modified_at"
1362
+ ].includes(f.name));
1363
+ const timestampLines = [...createdField && !["created_at", "created_on"].includes(createdField.dbName ?? createdField.name) ? [`alias_attribute :created_at, :${createdField.dbName ?? createdField.name}`] : [], ...updatedField && !["updated_at", "updated_on"].includes(updatedField.dbName ?? updatedField.name) ? [`alias_attribute :updated_at, :${updatedField.dbName ?? updatedField.name}`] : []];
1364
+ const idDefault = idField?.default;
1365
+ const orderColumnLines = typeof idDefault === "object" && "name" in idDefault && (idDefault.name === "uuid" && idDefault.args[0] !== 7 || idDefault.name === "cuid" || idDefault.name === "nanoid") && createdField ? [`self.implicit_order_column = "${createdField.dbName ?? createdField.name}"`] : [];
1366
+ const attributeLines = model.fields.filter((f) => (f.kind === "scalar" || f.kind === "enum") && (f.isList || f.kind === "scalar")).flatMap((f) => {
97
1367
  const def = f.default;
98
- if (!(def && typeof def === "object" && "name" in def)) return [];
99
- const generator = def.name === "uuid" ? "args" in def && def.args[0] === 7 ? "SecureRandom.uuid_v7" : "SecureRandom.uuid" : def.name === "ulid" ? "ULID.generate" : null;
100
- if (generator === null) return [];
101
- return [` attribute :${f.dbName ?? f.name}, default: -> { ${generator} }`];
1368
+ if (def === void 0) return f.isList ? [`attribute :${f.dbName ?? f.name}, default: -> { [] }`] : [];
1369
+ if (f.kind === "enum") return [];
1370
+ if (typeof def === "object" && "name" in def) {
1371
+ if (f.type !== "String") return [];
1372
+ const generator = def.name === "uuid" ? def.args[0] === 7 ? "SecureRandom.uuid_v7" : "SecureRandom.uuid" : def.name === "ulid" ? "ULID.generate" : def.name === "cuid" ? def.args[0] === 2 ? "Cuid2.call" : "Cuid.generate" : def.name === "nanoid" ? typeof def.args[0] === "number" ? `Nanoid.generate(size: ${def.args[0]})` : "Nanoid.generate" : null;
1373
+ if (generator === null) return [];
1374
+ return [`attribute :${f.dbName ?? f.name}, default: -> { ${generator} }`];
1375
+ }
1376
+ if (typeof def === "object") {
1377
+ const items = def.map((item) => rubyDefault(f.type, item));
1378
+ if (!f.isList || items.some((item) => item === null)) return [];
1379
+ return [`attribute :${f.dbName ?? f.name}, default: -> { ${rubyArray(items.map(String))} }`];
1380
+ }
1381
+ const literal = rubyDefault(f.type, def);
1382
+ if (literal === null) return [];
1383
+ return [`attribute :${f.dbName ?? f.name}, default: ${f.type === "Json" ? `-> { ${literal} }` : literal}`];
102
1384
  });
103
1385
  const enumLines = model.fields.filter((f) => f.kind === "enum" && !f.isList).reduce((acc, f) => {
104
- const values = enumMap.get(f.type) ?? [];
105
- const pairs = values.map((v) => `${v.name}: "${v.dbName ?? v.name}"`).join(", ");
106
- const prefixOpt = values.some((v) => acc.seenValues.has(v.name)) ? ", prefix: true" : "";
107
- for (const v of values) acc.seenValues.add(v.name);
1386
+ const values = (enumMap.get(f.type) ?? []).map((v) => ({
1387
+ key: makeSnakeCase(v.name),
1388
+ name: v.name,
1389
+ stored: v.dbName ?? v.name
1390
+ }));
1391
+ const pairs = values.map((v) => `${symbolKey(v.key)}: "${v.stored}"`).join(", ");
1392
+ const conflicts = values.some((v) => acc.seenKeys.has(v.key) || RAILS_RESERVED_NAMES.has(v.key));
1393
+ const defaultValue = values.find((v) => v.name === f.default);
1394
+ const opts = [
1395
+ ...typeof f.default === "string" && defaultValue !== void 0 ? [`default: :${symbolKey(defaultValue.key)}`] : [],
1396
+ ...conflicts ? ["prefix: true"] : [],
1397
+ f.isRequired ? "validate: true" : "validate: { allow_nil: true }"
1398
+ ];
1399
+ for (const v of values) acc.seenKeys.add(v.key);
108
1400
  return {
109
- lines: [...acc.lines, ` enum :${f.dbName ?? f.name}, { ${pairs} }${prefixOpt}`],
110
- seenValues: acc.seenValues
1401
+ lines: [...acc.lines, rubyCall("enum", [`:${f.dbName ?? f.name}`, `{ ${pairs} }`], opts)],
1402
+ seenKeys: acc.seenKeys
111
1403
  };
112
1404
  }, {
113
1405
  lines: [],
114
- seenValues: /* @__PURE__ */ new Set()
1406
+ seenKeys: /* @__PURE__ */ new Set()
115
1407
  }).lines;
1408
+ const foreignKeyFields = new Set(model.fields.flatMap((f) => f.kind === "object" ? f.relationFromFields ?? [] : []));
1409
+ const compositeKeyFields = new Set(model.primaryKey?.fields);
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) => {
1424
+ if (!(f.kind === "scalar" || f.kind === "enum")) return [];
1425
+ const column = f.kind === "scalar" && !f.isList;
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"];
1428
+ const length = column && f.type === "String" ? nativeLength(f) : null;
1429
+ const lengthOpt = length === null ? [] : [`length: { maximum: ${length} }`];
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
+ ];
1438
+ return opts.length === 0 ? "uniqueness: true" : `uniqueness: { ${opts.join(", ")} }`;
1439
+ });
1440
+ const rules = [...[
1441
+ ...presence,
1442
+ ...lengthOpt,
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
+ });
1447
+ const modelSnake = makeSnakeCase(model.name);
116
1448
  const belongsToLines = associations.belongsTo.map((a) => {
117
- const primaryKeyOpt = a.primaryKeyColumns.length > 1 ? `, primary_key: [${a.primaryKeyColumns.map((c) => `:${c}`).join(", ")}]` : a.primaryKeyColumn === "id" ? "" : `, primary_key: "${a.primaryKeyColumn}"`;
118
- const optionalOpt = a.optional ? ", optional: true" : "";
119
- return ` belongs_to :${makeSnakeCase(a.name)}, class_name: "${makePascalCase(a.targetModel)}", ${foreignKeyOpt(a.foreignKeyColumns)}${primaryKeyOpt}${optionalOpt}`;
1449
+ const name = makeSnakeCase(a.name);
1450
+ const conventional = name === makeSnakeCase(a.targetModel) && a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${name}_id` && a.referencesPrimaryKey && a.inverse !== null && !a.inverseIsList && makeSnakeCase(a.inverse) === modelSnake;
1451
+ return rubyCall("belongs_to", [`:${name}`], [
1452
+ ...makePascalCase(a.targetModel) === makePascalCase(name) ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1453
+ ...a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${name}_id` ? [] : [foreignKeyOpt(a.foreignKeyColumns)],
1454
+ ...primaryKeyOpt(a.primaryKeyColumns, a.referencesPrimaryKey),
1455
+ ...a.optional ? ["optional: true"] : [],
1456
+ ...a.inverse === null || conventional ? [] : [`inverse_of: :${makeSnakeCase(a.inverse)}`]
1457
+ ]);
1458
+ });
1459
+ const hasLines = (macro, list) => list.map((a) => {
1460
+ const name = makeSnakeCase(a.name);
1461
+ const inverse = makeSnakeCase(a.inverse);
1462
+ const conventional = a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${modelSnake}_id` && a.referencesPrimaryKey && inverse === modelSnake && name === (macro === "has_many" ? pluralize(makeSnakeCase(a.targetModel)) : makeSnakeCase(a.targetModel));
1463
+ const derivedClass = macro === "has_many" ? name === pluralize(makeSnakeCase(a.targetModel)) : makePascalCase(name) === makePascalCase(a.targetModel);
1464
+ const dependent = DEPENDENT[a.onDelete];
1465
+ return rubyCall(macro, [`:${name}`], [
1466
+ ...derivedClass ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1467
+ ...a.foreignKeyColumns.length === 1 && a.foreignKeyColumns[0] === `${modelSnake}_id` ? [] : [foreignKeyOpt(a.foreignKeyColumns)],
1468
+ ...primaryKeyOpt(a.primaryKeyColumns, a.referencesPrimaryKey),
1469
+ ...conventional ? [] : [`inverse_of: :${inverse}`],
1470
+ ...dependent === void 0 ? [] : [`dependent: :${dependent}`]
1471
+ ]);
1472
+ });
1473
+ const hasOneLines = hasLines("has_one", associations.hasOne);
1474
+ const hasManyLines = hasLines("has_many", associations.hasMany);
1475
+ const habtmLines = associations.habtm.map((a) => {
1476
+ const name = makeSnakeCase(a.name);
1477
+ return rubyCall("has_and_belongs_to_many", [`:${name}`], [
1478
+ ...name === pluralize(makeSnakeCase(a.targetModel)) ? [] : [`class_name: "${makePascalCase(a.targetModel)}"`],
1479
+ `join_table: "${a.joinTable}"`,
1480
+ `foreign_key: "${a.foreignKey}"`,
1481
+ `association_foreign_key: "${a.associationForeignKey}"`
1482
+ ]);
120
1483
  });
121
- const hasOneLines = associations.hasOne.map((a) => ` has_one :${makeSnakeCase(a.name)}, class_name: "${makePascalCase(a.targetModel)}", ${foreignKeyOpt(a.foreignKeyColumns)}${hasPrimaryKeyOpt(a.primaryKeyColumns)}`);
122
- const hasManyLines = associations.hasMany.map((a) => ` has_many :${makeSnakeCase(a.name)}, class_name: "${makePascalCase(a.targetModel)}", ${foreignKeyOpt(a.foreignKeyColumns)}${hasPrimaryKeyOpt(a.primaryKeyColumns)}`);
123
- const habtmLines = associations.habtm.map((a) => ` has_and_belongs_to_many :${makeSnakeCase(a.name)}, class_name: "${makePascalCase(a.targetModel)}", join_table: "${a.joinTable}", foreign_key: "${a.foreignKey}", association_foreign_key: "${a.associationForeignKey}"`);
124
1484
  const associationLines = [
125
1485
  ...belongsToLines,
126
1486
  ...hasOneLines,
127
1487
  ...hasManyLines,
128
1488
  ...habtmLines
129
1489
  ];
130
- const doc = stripAnnotations(model.documentation);
1490
+ const body = [
1491
+ [
1492
+ ...tableNameLines,
1493
+ ...primaryKeyLines,
1494
+ ...inheritanceColumnLines,
1495
+ ...orderColumnLines
1496
+ ],
1497
+ [...attributeLines, ...timestampLines],
1498
+ enumLines,
1499
+ validationLines,
1500
+ associationLines,
1501
+ modelLines
1502
+ ].filter((group) => group.length > 0).map((group) => group.join("\n")).join("\n\n").split("\n");
131
1503
  return [
132
- ...doc ? doc.split("\n").map((line) => `# ${line}`) : [],
133
- `class ${makePascalCase(model.name)} < ApplicationRecord`,
134
- ` self.table_name = "${tableName}"`,
135
- ...primaryKeyLines,
136
- ...inheritanceColumnLines,
137
- ...attributeLines.length > 0 ? ["", ...attributeLines] : [],
138
- ...enumLines.length > 0 ? ["", ...enumLines] : [],
139
- ...associationLines.length > 0 ? ["", ...associationLines] : [],
1504
+ `class ${className} < ApplicationRecord`,
1505
+ ...body.map((line) => line === "" ? "" : ` ${line}`),
140
1506
  "end"
141
1507
  ].join("\n");
142
1508
  }).filter(Boolean).join("\n\n");
143
1509
  }
144
1510
  //#endregion
145
1511
  //#region src/generator/activerecord.ts
1512
+ const APPLICATION_RECORD_FILE = {
1513
+ fileName: "application_record.rb",
1514
+ code: `class ApplicationRecord < ActiveRecord::Base
1515
+ primary_abstract_class
1516
+ end
1517
+ `
1518
+ };
146
1519
  function activeRecordModelFiles(models, enums) {
147
1520
  return models.map((model) => ({
148
1521
  fileName: `${makeSnakeCase(model.name)}.rb`,
149
- code: activeRecordModels([model], models, enums)
1522
+ code: `${activeRecordModels([model], models, enums)}\n`
150
1523
  })).filter((entry) => entry.code.trim().length > 0);
151
1524
  }
152
1525
  //#endregion
@@ -159,9 +1532,21 @@ function activerecord(options) {
159
1532
  return Effect.gen(function* () {
160
1533
  if (!(options.generator.isCustomOutput && options.generator.output?.value)) return yield* new GeneratorConfigError({ message: "output is required for Hekireki-ActiveRecord. Please specify output in your generator config." });
161
1534
  const outDir = options.generator.output.value;
1535
+ const problems = activeRecordProblems(options.dmmf.datamodel.models);
1536
+ if (problems.length > 0) return yield* new GeneratorConfigError({ message: `Hekireki-ActiveRecord cannot read this schema:\n${problems.map((p) => ` - ${p}`).join("\n")}` });
162
1537
  const enums = options.dmmf.datamodel.enums;
163
1538
  const files = activeRecordModelFiles(options.dmmf.datamodel.models, enums);
164
- return yield* emitMany(files, outDir);
1539
+ const withBase = path.basename(outDir) === "models" ? [APPLICATION_RECORD_FILE, ...files] : files;
1540
+ const localeFiles = activeRecordLocaleFiles(options.dmmf.datamodel.models);
1541
+ if (localeFiles.length > 0) {
1542
+ const locales = getString(options.generator.config?.locales);
1543
+ const localesDir = locales !== void 0 && locales !== "" ? path.resolve(outDir, locales) : path.basename(outDir) === "models" ? path.resolve(outDir, "..", "..", "config", "locales") : yield* new GeneratorConfigError({ message: "locales is required for Hekireki-ActiveRecord when a `@ar.` message names a locale: the directory config/locales is written to, relative to output." });
1544
+ yield* Effect.forEach(localeFiles, (f) => {
1545
+ const output = path.join(localesDir, f.fileName);
1546
+ return emitRaw(f.code, path.dirname(output), output);
1547
+ }, { discard: true });
1548
+ }
1549
+ return yield* emitMany(withBase, outDir);
165
1550
  });
166
1551
  }
167
1552
  //#endregion
@@ -1179,7 +2564,7 @@ function scalarElementLiteral(type, value) {
1179
2564
  return jsonToPythonLiteral$1(value);
1180
2565
  }
1181
2566
  function fieldColumnName(field) {
1182
- return field.dbName ?? makeSnakeCase(field.name);
2567
+ return field.dbName ?? field.name;
1183
2568
  }
1184
2569
  function nameKey(modelName, fieldName) {
1185
2570
  return `${modelName}.${fieldName}`;
@@ -1206,7 +2591,7 @@ function modelAttrNames(model, m2mTables) {
1206
2591
  names.set(field.name, attr);
1207
2592
  continue;
1208
2593
  }
1209
- names.set(field.name, claimName(djangoAttrName(fieldColumnName(field)), taken));
2594
+ names.set(field.name, claimName(djangoAttrName(makeSnakeCase(field.name)), taken));
1210
2595
  }
1211
2596
  return names;
1212
2597
  }
@@ -1233,7 +2618,7 @@ function attrNameOf(names, model, field) {
1233
2618
  return names.attr.get(nameKey(model.name, field.name)) ?? djangoAttrName(fieldColumnName(field));
1234
2619
  }
1235
2620
  function helperNameOf(names, model, field) {
1236
- return names.helper.get(nameKey(model.name, field.name)) ?? `${makeSnakeCase(model.name)}_${djangoAttrName(fieldColumnName(field))}_default`;
2621
+ return names.helper.get(nameKey(model.name, field.name)) ?? `${makeSnakeCase(model.name)}_${djangoAttrName(makeSnakeCase(field.name))}_default`;
1237
2622
  }
1238
2623
  function fieldDefaultHelper(model, field, names, enumMap) {
1239
2624
  const helperName = helperNameOf(names, model, field);
@@ -1465,11 +2850,11 @@ function singleColumnBelongsTo(model) {
1465
2850
  return model.fields.filter((f) => f.kind === "object" && f.relationFromFields?.length === 1 && f.relationToFields);
1466
2851
  }
1467
2852
  function generateMetaLines(model, indexes, names) {
1468
- const tableName = model.dbName ?? makeSnakeCase(model.name);
2853
+ const tableName = model.dbName ?? model.name;
1469
2854
  const fieldRef = (prismaFieldName) => names.attr.get(nameKey(model.name, prismaFieldName)) ?? makeSnakeCase(prismaFieldName);
1470
2855
  const columnRef = (prismaFieldName) => {
1471
2856
  const fieldObj = model.fields.find((f) => f.name === prismaFieldName);
1472
- return fieldObj ? fieldColumnName(fieldObj) : makeSnakeCase(prismaFieldName);
2857
+ return fieldObj ? fieldColumnName(fieldObj) : prismaFieldName;
1473
2858
  };
1474
2859
  const uniqueIndexes = indexes.filter((idx) => idx.model === model.name && idx.type === "unique" && !idx.isDefinedOnField);
1475
2860
  const constraints = model.uniqueFields.map((fields) => {
@@ -1510,32 +2895,12 @@ function compositePkLine(model, names) {
1510
2895
  }).join(", ")})`;
1511
2896
  }
1512
2897
  function findNameConflicts(models, enums) {
1513
- const byTable = /* @__PURE__ */ new Map();
1514
- for (const model of models) {
1515
- const table = model.dbName ?? makeSnakeCase(model.name);
1516
- byTable.set(table, [...byTable.get(table) ?? [], model.name]);
1517
- }
1518
- const tableConflicts = [...byTable].filter(([, owners]) => owners.length > 1).map(([table, owners]) => `models ${owners.join(" and ")} both map to the table "${table}". Add @@map to one of them.`);
1519
- const columnConflicts = models.flatMap((model) => {
1520
- const byColumn = /* @__PURE__ */ new Map();
1521
- for (const field of model.fields) {
1522
- if (field.kind === "object") continue;
1523
- const column = fieldColumnName(field);
1524
- byColumn.set(column, [...byColumn.get(column) ?? [], field.name]);
1525
- }
1526
- return [...byColumn].filter(([, owners]) => owners.length > 1).map(([column, owners]) => `fields ${owners.join(" and ")} of model ${model.name} both map to the column "${column}". Add @map to one of them.`);
1527
- });
1528
2898
  const byEnumClass = /* @__PURE__ */ new Map();
1529
2899
  for (const enumDef of enums ?? []) {
1530
2900
  const className = makePascalCase(enumDef.name);
1531
2901
  byEnumClass.set(className, [...byEnumClass.get(className) ?? [], enumDef.name]);
1532
2902
  }
1533
- const enumConflicts = [...byEnumClass].filter(([, owners]) => owners.length > 1).map(([className, owners]) => `enums ${owners.join(" and ")} both produce the Python class ${className}. Rename one of them.`);
1534
- return [
1535
- ...tableConflicts,
1536
- ...columnConflicts,
1537
- ...enumConflicts
1538
- ];
2903
+ return [...byEnumClass].filter(([, owners]) => owners.length > 1).map(([className, owners]) => `enums ${owners.join(" and ")} both produce the Python class ${className}. Rename one of them.`);
1539
2904
  }
1540
2905
  function hasPrimaryKey(model) {
1541
2906
  return model.fields.some((f) => f.isId) || (model.primaryKey?.fields.length ?? 0) > 0;
@@ -1773,14 +3138,15 @@ function snakeToCamel(name) {
1773
3138
  return name.replaceAll(/_+([a-zA-Z0-9])/gu, (_match, char) => char.toUpperCase());
1774
3139
  }
1775
3140
  function resolveTableName(model) {
1776
- return model.dbName ?? makeSnakeCase(model.name);
3141
+ return model.dbName ?? model.name;
1777
3142
  }
1778
3143
  function resolveVarName(model) {
1779
- return snakeToCamel(resolveTableName(model));
3144
+ const name = snakeToCamel(resolveTableName(model));
3145
+ return `${name.charAt(0).toLowerCase()}${name.slice(1)}`;
1780
3146
  }
1781
3147
  function resolveVarNameByType(type, models) {
1782
3148
  const target = models.find((m) => m.name === type);
1783
- return snakeToCamel(target ? resolveTableName(target) : makeSnakeCase(type));
3149
+ return target ? resolveVarName(target) : `${type.charAt(0).toLowerCase()}${type.slice(1)}`;
1784
3150
  }
1785
3151
  function isFieldDefault(v) {
1786
3152
  return typeof v === "object" && v !== null && "name" in v;
@@ -2529,7 +3895,7 @@ function ectoSchemas(models, app, allModels, enums) {
2529
3895
  "",
2530
3896
  ...typeSpecLines,
2531
3897
  "",
2532
- ` schema "${model.dbName ?? makeSnakeCase(model.name)}" do`,
3898
+ ` schema "${model.dbName ?? model.name}" do`,
2533
3899
  ...schemaFields,
2534
3900
  ...fkFieldLines,
2535
3901
  ...belongsToLines,
@@ -2563,174 +3929,6 @@ function ecto(options) {
2563
3929
  });
2564
3930
  }
2565
3931
  //#endregion
2566
- //#region src/helper/humanizer.ts
2567
- function irregular(singular, plural) {
2568
- return {
2569
- plural: [`(${singular[0]})${singular.slice(1)}$`, `$1${plural.slice(1)}`],
2570
- singular: [`(${plural[0]})${plural.slice(1)}$`, `$1${singular.slice(1)}`]
2571
- };
2572
- }
2573
- function wholeWordIrregular(singular, plural) {
2574
- return {
2575
- plural: [`^${singular}$`, plural],
2576
- singular: [`^${plural}$`, singular]
2577
- };
2578
- }
2579
- const IRREGULARS = [
2580
- irregular("person", "people"),
2581
- irregular("man", "men"),
2582
- irregular("human", "humans"),
2583
- irregular("child", "children"),
2584
- irregular("sex", "sexes"),
2585
- irregular("glove", "gloves"),
2586
- irregular("move", "moves"),
2587
- irregular("goose", "geese"),
2588
- irregular("wave", "waves"),
2589
- irregular("foot", "feet"),
2590
- irregular("tooth", "teeth"),
2591
- irregular("curriculum", "curricula"),
2592
- irregular("database", "databases"),
2593
- irregular("zombie", "zombies"),
2594
- irregular("personnel", "personnel"),
2595
- irregular("cache", "caches"),
2596
- wholeWordIrregular("ex", "exes"),
2597
- wholeWordIrregular("is", "are"),
2598
- wholeWordIrregular("that", "those"),
2599
- wholeWordIrregular("this", "these"),
2600
- wholeWordIrregular("bus", "buses"),
2601
- wholeWordIrregular("die", "dice"),
2602
- wholeWordIrregular("tie", "ties")
2603
- ];
2604
- const PLURAL_RULES = [
2605
- ["$", "s"],
2606
- ["s$", "s"],
2607
- ["(ax|test)is$", "$1es"],
2608
- ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i"],
2609
- ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es"],
2610
- ["(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes"],
2611
- ["([dti])um$", "$1a"],
2612
- ["sis$", "ses"],
2613
- ["(?:([^f])fe|([lr])f)$", "$1$2ves"],
2614
- ["(hive)$", "$1s"],
2615
- ["([^aeiouy]|qu)y$", "$1ies"],
2616
- ["(x|ch|ss|sh)$", "$1es"],
2617
- ["(matr|vert|ind|d)(ix|ex)$", "$1ices"],
2618
- ["(^[m|l])ouse$", "$1ice"],
2619
- ["^(ox)$", "$1en"],
2620
- ["(quiz)$", "$1zes"],
2621
- ["(buz|blit|walt)z$", "$1zes"],
2622
- ["(hoo|lea|loa|thie)f$", "$1ves"],
2623
- ["(alumn|alg|larv|vertebr)a$", "$1ae"],
2624
- ["(criteri|phenomen)on$", "$1a"],
2625
- ...IRREGULARS.map((rule) => rule.plural)
2626
- ].map(([pattern, replacement]) => ({
2627
- pattern: new RegExp(pattern, "iu"),
2628
- replacement
2629
- }));
2630
- const SINGULAR_RULES = [
2631
- ["s$", ""],
2632
- ["(n)ews$", "$1ews"],
2633
- ["([dti])a$", "$1um"],
2634
- ["(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis"],
2635
- ["([^f])ves$", "$1fe"],
2636
- ["(hive)s$", "$1"],
2637
- ["(tive)s$", "$1"],
2638
- ["([lr]|hoo|lea|loa|thie)ves$", "$1f"],
2639
- ["(^zomb)?([^aeiouy]|qu)ies$", "$2y"],
2640
- ["(s)eries$", "$1eries"],
2641
- ["(m)ovies$", "$1ovie"],
2642
- ["(x|ch|ss|sh)es$", "$1"],
2643
- ["(^[m|l])ice$", "$1ouse"],
2644
- ["(?<!^[a-z])(o)es$", "$1"],
2645
- ["(shoe)s$", "$1"],
2646
- ["(cris|ax|test)es$", "$1is"],
2647
- ["(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us"],
2648
- ["(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1"],
2649
- ["^(ox)en", "$1"],
2650
- ["(matr|d)ices$", "$1ix"],
2651
- ["(vert|ind)ices$", "$1ex"],
2652
- ["(quiz)zes$", "$1"],
2653
- ["(buz|blit|walt)zes$", "$1z"],
2654
- ["(alumn|alg|larv|vertebr)ae$", "$1a"],
2655
- ["(criteri|phenomen)a$", "$1on"],
2656
- ["([b|r|c]ook|room|smooth)ies$", "$1ie"],
2657
- ...IRREGULARS.map((rule) => rule.singular)
2658
- ].map(([pattern, replacement]) => ({
2659
- pattern: new RegExp(pattern, "iu"),
2660
- replacement
2661
- }));
2662
- const UNCOUNTABLE_WORDS = /* @__PURE__ */ new Set([
2663
- "staff",
2664
- "training",
2665
- "equipment",
2666
- "information",
2667
- "corn",
2668
- "milk",
2669
- "rice",
2670
- "money",
2671
- "species",
2672
- "series",
2673
- "fish",
2674
- "sheep",
2675
- "deer",
2676
- "aircraft",
2677
- "oz",
2678
- "tsp",
2679
- "tbsp",
2680
- "ml",
2681
- "l",
2682
- "water",
2683
- "waters",
2684
- "semen",
2685
- "sperm",
2686
- "bison",
2687
- "grass",
2688
- "hair",
2689
- "mud",
2690
- "elk",
2691
- "luggage",
2692
- "moose",
2693
- "offspring",
2694
- "salmon",
2695
- "shrimp",
2696
- "someone",
2697
- "swine",
2698
- "trout",
2699
- "tuna",
2700
- "corps",
2701
- "scissors",
2702
- "means",
2703
- "mail",
2704
- "metadata"
2705
- ]);
2706
- function isUpperCaseLetter(char) {
2707
- return char !== char.toLowerCase() && char === char.toUpperCase();
2708
- }
2709
- function isLowerCaseLetter(char) {
2710
- return char !== char.toUpperCase() && char === char.toLowerCase();
2711
- }
2712
- function applyRules(rules, word) {
2713
- if (word.length === 0 || UNCOUNTABLE_WORDS.has(word.toLowerCase())) return word;
2714
- const rule = rules.findLast((candidate) => candidate.pattern.test(word));
2715
- if (rule === void 0) return null;
2716
- const result = word.replace(rule.pattern, rule.replacement);
2717
- const first = result.charAt(0);
2718
- return isUpperCaseLetter(word.charAt(0)) && isLowerCaseLetter(first) ? `${first.toUpperCase()}${result.slice(1)}` : result;
2719
- }
2720
- /**
2721
- * Humanizer's `Pluralize(inputIsKnownToBeSingular: false)`: a word that already reads as a plural
2722
- * is returned as it is.
2723
- *
2724
- * @param word - The word to pluralize.
2725
- * @returns The plural form Humanizer 2.14.1 gives.
2726
- */
2727
- function pluralize(word) {
2728
- const result = applyRules(PLURAL_RULES, word);
2729
- const asSingular = applyRules(SINGULAR_RULES, word);
2730
- const asSingularAsPlural = asSingular === null ? null : applyRules(PLURAL_RULES, asSingular);
2731
- return asSingular !== null && asSingular !== word && `${asSingular}s` !== word && asSingularAsPlural === word && result !== word ? word : result ?? word;
2732
- }
2733
- //#endregion
2734
3932
  //#region src/helper/naming.ts
2735
3933
  /**
2736
3934
  * A Prisma name as a type name: the underscores join words, each word starts in upper case, and a
@@ -4136,7 +5334,7 @@ function eloquentModels(models, namespace, allModels, enums) {
4136
5334
  const enumNames = new Set((enums ?? []).map((e) => e.name));
4137
5335
  return models.map((model) => {
4138
5336
  const associations = getAssociations$3(model, contextModels);
4139
- const tableName = model.dbName ?? makeSnakeCase(model.name);
5337
+ const tableName = model.dbName ?? model.name;
4140
5338
  const idField = model.fields.find((f) => f.isId);
4141
5339
  const compositePkFields = model.primaryKey?.fields ?? [];
4142
5340
  const timestamps = findTimestamps(model.fields);
@@ -7982,7 +9180,7 @@ function formatGoDefault(def) {
7982
9180
  return null;
7983
9181
  }
7984
9182
  function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums) {
7985
- const columnName = field.dbName ?? makeSnakeCase(field.name);
9183
+ const columnName = field.dbName ?? field.name;
7986
9184
  const isUuidDefault = isFunctionDefault$3(field.default) && field.default.name === "uuid";
7987
9185
  const isUlidDefault = isFunctionDefault$3(field.default) && field.default.name === "ulid";
7988
9186
  const isNowDefault = field.type === "DateTime" && isFunctionDefault$3(field.default) && field.default.name === "now";
@@ -8012,16 +9210,16 @@ function buildGormTags(field, isPk, isCompositePk, compositeIndexTags, enums) {
8012
9210
  ].filter((p) => p !== null).join(";")}" json:"${columnName}"\``;
8013
9211
  }
8014
9212
  function collectCompositeIndexTags(model, indexes) {
8015
- const tableName = model.dbName ?? makeSnakeCase(model.name);
9213
+ const tableName = model.dbName ?? model.name;
8016
9214
  const uniqueTags = model.uniqueFields.filter((fields) => fields.length > 1).flatMap((fields) => {
8017
9215
  const cols = fields.map((f) => {
8018
- return model.fields.find((mf) => mf.name === f)?.dbName ?? makeSnakeCase(f);
9216
+ return model.fields.find((mf) => mf.name === f)?.dbName ?? f;
8019
9217
  });
8020
- const idxName = `idx_${tableName}_${cols.join("_")}_unique`;
9218
+ const idxName = `${tableName}_${cols.join("_")}_key`;
8021
9219
  return fields.map((f) => [f, `uniqueIndex:${idxName}`]);
8022
9220
  });
8023
9221
  const indexTags = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).flatMap((idx) => {
8024
- const idxName = idx.dbName ?? idx.name ?? `idx_${tableName}_${idx.fields.map((f) => makeSnakeCase(f.name)).join("_")}`;
9222
+ const idxName = idx.dbName ?? idx.name ?? `${tableName}_${idx.fields.map((f) => model.fields.find((mf) => mf.name === f.name)?.dbName ?? f.name).join("_")}_idx`;
8025
9223
  return idx.fields.map((f) => [f.name, `index:${idxName}`]);
8026
9224
  });
8027
9225
  return [...uniqueTags, ...indexTags].reduce((map, [fieldName, tag]) => {
@@ -8186,19 +9384,19 @@ function generateModelStruct(model, allModels, enums, indexes) {
8186
9384
  if (!(idField || isCompositePk)) return null;
8187
9385
  const associations = getAssociations$2(model, allModels);
8188
9386
  const compositeTagMap = collectCompositeIndexTags(model, indexes);
8189
- const tableName = model.dbName ?? makeSnakeCase(model.name);
9387
+ const tableName = model.dbName ?? model.name;
8190
9388
  const fieldLines = model.fields.filter((f) => f.kind !== "object").map((field) => {
8191
9389
  const isPk = field.isId || compositePkFieldNames.has(field.name);
8192
9390
  const fieldIndexTags = compositeTagMap.get(field.name) ?? [];
8193
9391
  return generateStructField(field, isPk, isCompositePk, fieldIndexTags, enums);
8194
9392
  });
8195
9393
  const relationLines = generateRelationFields(model, associations);
8196
- const tableNameMethod = tableName !== makeSnakeCase(model.name) ? [
9394
+ const tableNameMethod = [
8197
9395
  "",
8198
9396
  `func (${goModelName(model.name)}) TableName() string {`,
8199
9397
  `\treturn "${tableName}"`,
8200
9398
  "}"
8201
- ] : [];
9399
+ ];
8202
9400
  return [
8203
9401
  `type ${goModelName(model.name)} struct {`,
8204
9402
  ...fieldLines,
@@ -8766,7 +9964,7 @@ function buildSeaOrmAttributes(field, isPk, isCompositePk, derivedColumn, enums)
8766
9964
  }
8767
9965
  if (field.isUnique) attrs.push("#[sea_orm(unique)]");
8768
9966
  const columnParts = [];
8769
- const columnName = field.dbName ?? makeSnakeCase(field.name);
9967
+ const columnName = field.dbName ?? field.name;
8770
9968
  if (columnName !== (derivedColumn ?? makeSnakeCase(field.name))) columnParts.push(`column_name = "${columnName}"`);
8771
9969
  const colType = resolveSeaOrmColumnType(field);
8772
9970
  if (colType) columnParts.push(`column_type = "${colType}"`);
@@ -8966,7 +10164,7 @@ function generateEntityFile(model, allModels, enums, serde = {}) {
8966
10164
  const compositePkFieldNames = new Set(model.primaryKey?.fields);
8967
10165
  const isCompositePk = !idField && compositePkFieldNames.size > 0;
8968
10166
  if (!(idField || isCompositePk)) return "";
8969
- const tableName = model.dbName ?? makeSnakeCase(model.name);
10167
+ const tableName = model.dbName ?? model.name;
8970
10168
  const associations = getAssociations$1(model, allModels);
8971
10169
  const enumNames = new Set(enums.map((e) => e.name));
8972
10170
  const scalarFields = model.fields.filter((f) => f.kind !== "object");
@@ -9431,10 +10629,10 @@ function collectManyToManyTables(allModels) {
9431
10629
  tableName: `_${relationName}`,
9432
10630
  varName: makeSnakeCase(relationName),
9433
10631
  leftModel: leftName,
9434
- leftTable: leftModelObj?.dbName ?? makeSnakeCase(leftName),
10632
+ leftTable: leftModelObj?.dbName ?? leftName,
9435
10633
  leftPkField: leftModelObj?.fields.find((f) => f.isId),
9436
10634
  rightModel: rightName,
9437
- rightTable: rightModelObj?.dbName ?? makeSnakeCase(rightName),
10635
+ rightTable: rightModelObj?.dbName ?? rightName,
9438
10636
  rightPkField: rightModelObj?.fields.find((f) => f.isId)
9439
10637
  }
9440
10638
  }];
@@ -9449,8 +10647,8 @@ function collectManyToManyTables(allModels) {
9449
10647
  function generateAssociationTable(info) {
9450
10648
  const leftSaType = info.leftPkField ? resolveNativeType(info.leftPkField) : "String";
9451
10649
  const rightSaType = info.rightPkField ? resolveNativeType(info.rightPkField) : "String";
9452
- const leftPkCol = info.leftPkField?.dbName ?? (info.leftPkField ? makeSnakeCase(info.leftPkField.name) : "id");
9453
- const rightPkCol = info.rightPkField?.dbName ?? (info.rightPkField ? makeSnakeCase(info.rightPkField.name) : "id");
10650
+ const leftPkCol = info.leftPkField?.dbName ?? info.leftPkField?.name ?? "id";
10651
+ const rightPkCol = info.rightPkField?.dbName ?? info.rightPkField?.name ?? "id";
9454
10652
  return [
9455
10653
  `${info.varName} = Table(`,
9456
10654
  ` "${info.tableName}",`,
@@ -9539,8 +10737,8 @@ function findM2MBackPopulates(targetModelName, sourceModelName, relationName, al
9539
10737
  return backField ? makeSnakeCase(backField.name) : makeSnakeCase(sourceModelName);
9540
10738
  }
9541
10739
  function generateColumn(field, isPk, isFk, associations, allModels, enumMap) {
9542
- const columnName = field.dbName ?? makeSnakeCase(field.name);
9543
- const attrName = pythonAttrName(columnName);
10740
+ const columnName = field.dbName ?? field.name;
10741
+ const attrName = pythonAttrName(makeSnakeCase(field.name));
9544
10742
  const elemPythonType = field.kind === "enum" ? "str" : pythonTypeForNative(field);
9545
10743
  const pythonType = field.isList ? `list[${elemPythonType}]` : elemPythonType;
9546
10744
  const typeHint = field.isList || field.isRequired ? pythonType : `Optional[${pythonType}]`;
@@ -9555,8 +10753,9 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap) {
9555
10753
  if (isFk) {
9556
10754
  const assoc = associations.belongsTo.find((a) => a.foreignKey === field.name);
9557
10755
  if (assoc?.foreignKeys.length === 1) {
9558
- const targetTable = allModels.find((m) => m.name === assoc.targetModel)?.dbName ?? makeSnakeCase(assoc.targetModel);
9559
- const targetCol = makeSnakeCase(assoc.references);
10756
+ const targetModelObj = allModels.find((m) => m.name === assoc.targetModel);
10757
+ const targetTable = targetModelObj?.dbName ?? assoc.targetModel;
10758
+ const targetCol = (targetModelObj?.fields.find((f) => f.name === assoc.references))?.dbName ?? assoc.references;
9560
10759
  const fkActions = [assoc.onDelete && SQL_ACTION[assoc.onDelete] ? `, ondelete="${SQL_ACTION[assoc.onDelete]}"` : "", assoc.onUpdate && SQL_ACTION[assoc.onUpdate] ? `, onupdate="${SQL_ACTION[assoc.onUpdate]}"` : ""].join("");
9561
10760
  colArgs.push(`ForeignKey("${targetTable}.${targetCol}"${fkActions})`);
9562
10761
  }
@@ -9586,23 +10785,23 @@ function generateColumn(field, isPk, isFk, associations, allModels, enumMap) {
9586
10785
  function generateTableArgs(model, allModels, indexes) {
9587
10786
  const uniqueConstraints = model.uniqueFields.map((fields) => {
9588
10787
  return `UniqueConstraint(${fields.map((f) => {
9589
- return `"${model.fields.find((mf) => mf.name === f)?.dbName ?? makeSnakeCase(f)}"`;
10788
+ return `"${model.fields.find((mf) => mf.name === f)?.dbName ?? f}"`;
9590
10789
  }).join(", ")})`;
9591
10790
  });
9592
10791
  const indexConstraints = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
9593
- return `Index("${idx.dbName ?? idx.name ?? `idx_${model.dbName ?? makeSnakeCase(model.name)}_${idx.fields.map((f) => makeSnakeCase(f.name)).join("_")}`}", ${idx.fields.map((f) => {
9594
- return `"${model.fields.find((mf) => mf.name === f.name)?.dbName ?? makeSnakeCase(f.name)}"`;
10792
+ return `Index("${idx.dbName ?? idx.name ?? `${model.dbName ?? model.name}_${idx.fields.map((f) => model.fields.find((mf) => mf.name === f.name)?.dbName ?? f.name).join("_")}_idx`}", ${idx.fields.map((f) => {
10793
+ return `"${model.fields.find((mf) => mf.name === f.name)?.dbName ?? f.name}"`;
9595
10794
  }).join(", ")})`;
9596
10795
  });
9597
10796
  const fkConstraints = model.fields.filter((f) => f.kind === "object" && f.relationFromFields && f.relationFromFields.length > 1 && f.relationToFields).map((f) => {
9598
10797
  const target = allModels.find((m) => m.name === f.type);
9599
- const targetTable = target?.dbName ?? makeSnakeCase(f.type);
10798
+ const targetTable = target?.dbName ?? f.type;
9600
10799
  const localCols = (f.relationFromFields ?? []).map((c) => {
9601
- return `"${model.fields.find((mf) => mf.name === c)?.dbName ?? makeSnakeCase(c)}"`;
10800
+ return `"${model.fields.find((mf) => mf.name === c)?.dbName ?? c}"`;
9602
10801
  });
9603
10802
  const targetCols = (f.relationToFields ?? []).map((c) => {
9604
10803
  const fieldObj = target?.fields.find((mf) => mf.name === c);
9605
- return `"${targetTable}.${fieldObj?.dbName ?? makeSnakeCase(c)}"`;
10804
+ return `"${targetTable}.${fieldObj?.dbName ?? c}"`;
9606
10805
  });
9607
10806
  const actions = [f.relationOnDelete && SQL_ACTION[f.relationOnDelete] ? `, ondelete="${SQL_ACTION[f.relationOnDelete]}"` : "", f.relationOnUpdate && SQL_ACTION[f.relationOnUpdate] ? `, onupdate="${SQL_ACTION[f.relationOnUpdate]}"` : ""].join("");
9608
10807
  return `ForeignKeyConstraint([${localCols.join(", ")}], [${targetCols.join(", ")}]${actions})`;
@@ -9623,11 +10822,11 @@ function generateTableArgs(model, allModels, indexes) {
9623
10822
  function generateBelongsToRelationships(associations, model, allModels) {
9624
10823
  return associations.belongsTo.map((assoc) => {
9625
10824
  const snakeName = makeSnakeCase(assoc.name);
9626
- const snakeFk = model.fields.find((f) => f.name === assoc.foreignKey)?.dbName ?? makeSnakeCase(assoc.foreignKey);
10825
+ const snakeFk = makeSnakeCase(assoc.foreignKey);
9627
10826
  const backPop = findBackPopulates(assoc.targetModel, model.name, assoc.foreignKey, allModels, assoc.name);
9628
10827
  const fkClause = needsForeignKeysParam(assoc.targetModel, associations.belongsTo) ? `foreign_keys=[${snakeFk}], ` : "";
9629
10828
  const pkField = model.fields.find((f) => f.isId);
9630
- const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${pkField.dbName ?? makeSnakeCase(pkField.name)}], ` : "";
10829
+ const remoteClause = assoc.targetModel === model.name && pkField ? `remote_side=[${makeSnakeCase(pkField.name)}], ` : "";
9631
10830
  return ` ${snakeName}: Mapped[${assoc.optional ? `Optional["${makePascalCase(assoc.targetModel)}"]` : `"${makePascalCase(assoc.targetModel)}"`}] = relationship(${remoteClause}${fkClause}back_populates="${backPop}")`;
9632
10831
  });
9633
10832
  }
@@ -9669,7 +10868,7 @@ function generateModelBody(model, allModels, enums, indexes, m2mTables) {
9669
10868
  const associations = getAssociations(model, allModels);
9670
10869
  const belongsToFkFields = new Set(associations.belongsTo.map((a) => a.foreignKey));
9671
10870
  const enumMap = new Map((enums ?? []).map((e) => [e.name, e]));
9672
- const tableName = model.dbName ?? makeSnakeCase(model.name);
10871
+ const tableName = model.dbName ?? model.name;
9673
10872
  const columnLines = model.fields.filter((f) => f.kind !== "object").map((field) => {
9674
10873
  return generateColumn(field, field.isId || compositePkFieldNames.has(field.name), belongsToFkFields.has(field.name), associations, allModels, enumMap);
9675
10874
  });