Skip to main content

vespertide_naming/
lib.rs

1//! Naming conventions and helpers for vespertide database schema management.
2//!
3//! This crate provides consistent naming functions for database objects like
4//! indexes, constraints, and foreign keys. It has no dependencies and can be
5//! used by any other vespertide crate.
6
7// ============================================================================
8// Relation Naming (for ORM exporters)
9// ============================================================================
10
11/// Extract semantic prefix from FK column for reverse relation naming.
12///
13/// Given an FK column name, the current (target) table name, and the referenced
14/// column name (e.g., "id", "idx"), extracts the semantic role portion.
15///
16/// # Arguments
17/// * `fk_column` - The FK column name (e.g., "`user_id`", "`answered_by_user_id`", "`author_id`")
18/// * `current_table` - The table being referenced (e.g., "user")
19/// * `ref_column` - The referenced column name (e.g., "id", "idx", "pk")
20///
21/// # Returns
22/// The semantic prefix (empty string for default FK, or the role/prefix for others)
23///
24/// # Examples
25/// ```
26/// use vespertide_naming::extract_relation_prefix;
27///
28/// // Default FK: column matches table name + ref_column suffix
29/// assert_eq!(extract_relation_prefix("user_id", "user", "id"), "");
30/// assert_eq!(extract_relation_prefix("user_idx", "user", "idx"), "");
31///
32/// // Prefixed FK: has semantic prefix before table name
33/// assert_eq!(extract_relation_prefix("answered_by_user_id", "user", "id"), "answered_by");
34/// assert_eq!(extract_relation_prefix("target_user_id", "user", "id"), "target");
35///
36/// // Role FK: column doesn't end with table name
37/// assert_eq!(extract_relation_prefix("author_id", "user", "id"), "author");
38/// assert_eq!(extract_relation_prefix("owner_id", "user", "id"), "owner");
39/// ```
40pub fn extract_relation_prefix(fk_column: &str, current_table: &str, ref_column: &str) -> String {
41    // Build the suffix to strip: _{ref_column} (e.g., "_id", "_idx")
42    let ref_suffix = format!("_{ref_column}");
43
44    // Remove the ref_column suffix if present
45    let without_ref = if let Some(stripped) = fk_column.strip_suffix(&ref_suffix) {
46        stripped
47    } else {
48        fk_column
49    };
50
51    let current_lower = current_table.to_lowercase();
52    let without_ref_lower = without_ref.to_lowercase();
53
54    // Case 1: FK column exactly matches current table (e.g., "user_id" for table "user")
55    // This is the "default" FK - return empty prefix
56    if without_ref_lower == current_lower {
57        return String::new();
58    }
59
60    // Case 2: FK column ends with _{current_table} (e.g., "answered_by_user_id" for table "user")
61    // Strip the _{table} suffix to get the semantic prefix
62    let table_suffix = format!("_{current_lower}");
63    if without_ref_lower.ends_with(&table_suffix) {
64        let prefix_chars = without_ref_lower.chars().count() - table_suffix.chars().count();
65        return without_ref.chars().take(prefix_chars).collect();
66    }
67
68    // Case 3: FK column is a different role (e.g., "author_id" for table "user")
69    // Use the column name as the prefix
70    without_ref.to_string()
71}
72
73/// Generate reverse relation field name for `has_many/has_one` relations.
74///
75/// # Arguments
76/// * `fk_columns` - The FK column names
77/// * `current_table` - The table being referenced (e.g., "user")
78/// * `source_table` - The table that has the FK (e.g., "inquiry")
79/// * `ref_column` - The referenced column name (e.g., "id")
80/// * `has_multiple_fks` - Whether `source_table` has multiple FKs to `current_table`
81/// * `is_one_to_one` - Whether this is a `has_one` relation
82///
83/// # Returns
84/// The field name (e.g., "inquiries", "`answered_by_inquiries`")
85pub fn build_reverse_relation_field_name(
86    fk_columns: &[String],
87    current_table: &str,
88    source_table: &str,
89    ref_column: &str,
90    has_multiple_fks: bool,
91    is_one_to_one: bool,
92) -> String {
93    let base_name = if is_one_to_one {
94        source_table.to_string()
95    } else {
96        pluralize(source_table)
97    };
98
99    if !has_multiple_fks || fk_columns.is_empty() {
100        return base_name;
101    }
102
103    let prefix = extract_relation_prefix(&fk_columns[0], current_table, ref_column);
104
105    if prefix.is_empty() {
106        base_name
107    } else {
108        format!("{prefix}_{base_name}")
109    }
110}
111
112/// Generate relation enum name for FK relations.
113///
114/// Uses the same logic as field naming but converts to `PascalCase`.
115/// This ensures `relation_enum` aligns with field names for consistency.
116///
117/// # Examples
118/// ```
119/// use vespertide_naming::build_relation_enum_name;
120///
121/// assert_eq!(build_relation_enum_name(&["user_id".into()], "user", "id"), "");
122/// assert_eq!(build_relation_enum_name(&["answered_by_user_id".into()], "user", "id"), "AnsweredBy");
123/// assert_eq!(build_relation_enum_name(&["author_id".into()], "user", "id"), "Author");
124/// ```
125pub fn build_relation_enum_name(
126    fk_columns: &[String],
127    current_table: &str,
128    ref_column: &str,
129) -> String {
130    if fk_columns.is_empty() {
131        return String::new();
132    }
133
134    let prefix = extract_relation_prefix(&fk_columns[0], current_table, ref_column);
135
136    if prefix.is_empty() {
137        String::new()
138    } else {
139        to_pascal_case(&prefix)
140    }
141}
142
143/// Convert `snake_case` to `PascalCase`.
144///
145/// # Examples
146/// ```
147/// use vespertide_naming::to_pascal_case;
148///
149/// assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
150/// assert_eq!(to_pascal_case("answered_by"), "AnsweredBy");
151/// assert_eq!(to_pascal_case("user"), "User");
152/// ```
153pub fn to_pascal_case(s: &str) -> String {
154    let mut result = String::new();
155    let mut capitalize = true;
156    for c in s.chars() {
157        let is_separator = c == '_' || c == '-';
158        if is_separator {
159            capitalize = true;
160            continue;
161        }
162        let ch = if capitalize {
163            c.to_ascii_uppercase()
164        } else {
165            c
166        };
167        capitalize = false;
168        result.push(ch);
169    }
170    result
171}
172
173/// Convert an arbitrary schema value into `SCREAMING_SNAKE_CASE`.
174///
175/// Word boundaries are detected on the lower→upper transition rather than on
176/// character position, so a value that is already `SCREAMING_SNAKE_CASE`
177/// survives unchanged. Non-alphanumeric characters become separators and
178/// trailing separators are trimmed.
179///
180/// This is case conversion only — the result can still be an invalid identifier
181/// (a value such as `1critical` keeps its leading digit). Pass it through
182/// [`sanitize_identifier`] with the target language's rule before emitting it.
183///
184/// # Examples
185/// ```
186/// use vespertide_naming::to_screaming_snake_case;
187///
188/// assert_eq!(to_screaming_snake_case("inProgress"), "IN_PROGRESS");
189/// assert_eq!(to_screaming_snake_case("order-status"), "ORDER_STATUS");
190/// assert_eq!(to_screaming_snake_case("ERROR_LEVEL"), "ERROR_LEVEL");
191/// assert_eq!(to_screaming_snake_case("1critical"), "1CRITICAL");
192/// ```
193pub fn to_screaming_snake_case(s: &str) -> String {
194    let mut result = String::new();
195    let mut prev_lower = false;
196    for ch in s.chars() {
197        if ch.is_uppercase() && prev_lower {
198            result.push('_');
199        }
200        if ch.is_alphanumeric() {
201            result.push(ch.to_ascii_uppercase());
202            prev_lower = ch.is_lowercase();
203        } else {
204            result.push('_');
205            prev_lower = false;
206        }
207    }
208    result.trim_end_matches('_').to_string()
209}
210
211/// What a target language accepts as the first character of an identifier.
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub enum IdentifierStart {
214    /// Rust modules, Java, SQLAlchemy's Python models and ERD node ids all
215    /// accept a leading `_`.
216    Underscore,
217    /// Prisma's schema parser and Pydantic (SQLModel fields) reject a leading
218    /// `_` outright, and `SeaORM`'s `DeriveEntityModel` drops it while building
219    /// the `Column` variant name. All three need a letter instead.
220    Letter,
221}
222
223/// Rewrite `name` into an identifier the target language will accept.
224///
225/// Characters that cannot appear in an identifier become `_`, and a name that
226/// would otherwise begin with a digit gains a prefix chosen by `start`. The
227/// letter prefix follows the case of the name it precedes, so it reads the same
228/// as its surroundings in both `PascalCase` and `snake_case` output.
229///
230/// Renaming loses the database name, so a caller that gets back something other
231/// than what it passed in **must** emit the original alongside it — Prisma
232/// `@map`, `SeaORM` `column_name`, SQLAlchemy's positional column name.
233///
234/// # Examples
235/// ```
236/// use vespertide_naming::{IdentifierStart, sanitize_identifier};
237///
238/// assert_eq!(sanitize_identifier("user-id", IdentifierStart::Underscore), "user_id");
239/// assert_eq!(sanitize_identifier("1st_place", IdentifierStart::Underscore), "_1st_place");
240/// assert_eq!(sanitize_identifier("1st_place", IdentifierStart::Letter), "x1st_place");
241/// assert_eq!(sanitize_identifier("1CRITICAL", IdentifierStart::Letter), "X1CRITICAL");
242/// assert_eq!(sanitize_identifier("email", IdentifierStart::Letter), "email");
243/// ```
244pub fn sanitize_identifier(name: &str, start: IdentifierStart) -> String {
245    let mut result: String = name
246        .chars()
247        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
248        .collect();
249
250    let needs_prefix = match start {
251        IdentifierStart::Underscore => {
252            result.is_empty() || result.starts_with(|c: char| c.is_ascii_digit())
253        }
254        IdentifierStart::Letter => !result.starts_with(|c: char| c.is_ascii_alphabetic()),
255    };
256    if !needs_prefix {
257        return result;
258    }
259
260    let prefix = match start {
261        IdentifierStart::Underscore => '_',
262        // Match the case of the name's first letter so the escape blends into
263        // `PascalCase`, `snake_case` and `SCREAMING_SNAKE_CASE` alike.
264        IdentifierStart::Letter => {
265            if result
266                .chars()
267                .find(char::is_ascii_alphabetic)
268                .is_some_and(char::is_uppercase)
269            {
270                'X'
271            } else {
272                'x'
273            }
274        }
275    };
276    result.insert(0, prefix);
277    result
278}
279
280/// Module name for a `SeaORM` entity file.
281///
282/// The exporter writes `super::{module}::Entity` in relation fields while the
283/// CLI writes `pub mod {module};` and names the file `{module}.rs`. All three
284/// have to agree, so the rule lives here rather than in either caller.
285///
286/// Rust would accept a leading `_`, but `sea-orm` infers the `Relation` variant
287/// of a relation field from the target's module name by `PascalCase`-ing it —
288/// which drops the `_` and leaves `1users`, so the derive panics. Hence the
289/// same letter rule the entity's own fields use.
290///
291/// # Examples
292/// ```
293/// use vespertide_naming::seaorm_module_name;
294///
295/// assert_eq!(seaorm_module_name("users"), "users");
296/// assert_eq!(seaorm_module_name("1users"), "x1users");
297/// assert_eq!(seaorm_module_name("user-profile"), "user_profile");
298/// ```
299pub fn seaorm_module_name(name: &str) -> String {
300    sanitize_identifier(name, IdentifierStart::Letter)
301}
302
303/// Simple pluralization for relation field names.
304///
305/// # Examples
306/// ```
307/// use vespertide_naming::pluralize;
308///
309/// assert_eq!(pluralize("inquiry"), "inquiries");
310/// assert_eq!(pluralize("comment"), "comments");
311/// assert_eq!(pluralize("status"), "status");
312/// ```
313pub fn pluralize(name: &str) -> String {
314    if name.ends_with('s') || name.ends_with("es") {
315        name.to_string()
316    } else if name.ends_with('y')
317        && !name.ends_with("ay")
318        && !name.ends_with("ey")
319        && !name.ends_with("oy")
320        && !name.ends_with("uy")
321    {
322        // e.g., category -> categories, inquiry -> inquiries
323        format!("{}ies", name.strip_suffix('y').unwrap_or(name))
324    } else {
325        format!("{name}s")
326    }
327}
328
329// ============================================================================
330// Constraint Naming (for SQL generation)
331// ============================================================================
332
333/// Generate index name from table name, columns, and optional user-provided key.
334/// Always includes table name to avoid conflicts across tables.
335/// Uses double underscore to separate table name from the rest.
336/// Format: ix_{table}__{key} or ix_{table}__{col1}_{col2}...
337pub fn build_index_name<T: AsRef<str>>(table: &str, columns: &[T], key: Option<&str>) -> String {
338    build_constraint_name("ix_", table, columns, key)
339}
340
341/// Generate unique constraint name from table name, columns, and optional user-provided key.
342/// Always includes table name to avoid conflicts across tables.
343/// Uses double underscore to separate table name from the rest.
344/// Format: uq_{table}__{key} or uq_{table}__{col1}_{col2}...
345pub fn build_unique_constraint_name<T: AsRef<str>>(
346    table: &str,
347    columns: &[T],
348    key: Option<&str>,
349) -> String {
350    build_constraint_name("uq_", table, columns, key)
351}
352
353/// Generate foreign key constraint name from table name, columns, and optional user-provided key.
354/// Always includes table name to avoid conflicts across tables.
355/// Uses double underscore to separate table name from the rest.
356/// Format: fk_{table}__{key} or fk_{table}__{col1}_{col2}...
357pub fn build_foreign_key_name<T: AsRef<str>>(
358    table: &str,
359    columns: &[T],
360    key: Option<&str>,
361) -> String {
362    build_constraint_name("fk_", table, columns, key)
363}
364
365/// Shared body for the three constraint name builders above.
366///
367/// Folds the `{prefix}{table}__{key|sorted-columns}` template into a single
368/// pre-sized `String` so the auto-named branch ( `key.is_none()`) does only
369/// two allocations: the column-sort scratchpad (`Vec<&str>`) and the final
370/// `String`. The previous implementation went through `format!(... join("_"))`
371/// which allocated an extra intermediate `String` for the joined columns
372/// before formatting them into the final result.
373fn build_constraint_name<T: AsRef<str>>(
374    prefix: &str,
375    table: &str,
376    columns: &[T],
377    key: Option<&str>,
378) -> String {
379    if let Some(k) = key {
380        let mut out = String::with_capacity(prefix.len() + table.len() + 2 + k.len());
381        out.push_str(prefix);
382        out.push_str(table);
383        out.push_str("__");
384        out.push_str(k);
385        out
386    } else {
387        let cols_capacity: usize = columns
388            .iter()
389            .map(|c| c.as_ref().len() + 1)
390            .sum::<usize>()
391            .saturating_sub(1);
392        let mut out = String::with_capacity(prefix.len() + table.len() + 2 + cols_capacity);
393        out.push_str(prefix);
394        out.push_str(table);
395        out.push_str("__");
396        write_sorted_columns(&mut out, columns);
397        out
398    }
399}
400
401/// Sort the column slice into a local scratchpad and write the columns into
402/// `out` joined by `'_'`. Replaces the previous `sort_columns_for_name(...).join("_")`
403/// pair which allocated a fresh `String` for the joined columns; here the
404/// columns go directly into the caller-supplied buffer.
405fn write_sorted_columns<T: AsRef<str>>(out: &mut String, columns: &[T]) {
406    let mut sorted: Vec<&str> = columns.iter().map(AsRef::as_ref).collect();
407    sorted.sort_unstable();
408    for (i, c) in sorted.iter().enumerate() {
409        if i > 0 {
410            out.push('_');
411        }
412        out.push_str(c);
413    }
414}
415
416/// Generate CHECK constraint name for `SQLite` enum column.
417/// Uses double underscore to separate table name from the rest.
418/// Format: chk_{table}__{column}
419pub fn build_check_constraint_name(table: &str, column: &str) -> String {
420    // Build in one exact-size allocation like the sibling constraint-name
421    // builders above, instead of routing through `format!`. Output is
422    // byte-identical: `chk_{table}__{column}` (`"chk_"` = 4 bytes, `"__"` = 2).
423    let mut out = String::with_capacity(4 + table.len() + 2 + column.len());
424    out.push_str("chk_");
425    out.push_str(table);
426    out.push_str("__");
427    out.push_str(column);
428    out
429}
430
431/// Generate enum type name with table prefix to avoid conflicts.
432/// Always includes table name to ensure uniqueness across tables.
433/// Format: {table}_{`enum_name`}
434///
435/// This prevents conflicts when multiple tables use the same enum name
436/// (e.g., "status" or "gender") with potentially different values.
437pub fn build_enum_type_name(table: &str, enum_name: &str) -> String {
438    // Build in one exact-size allocation like the sibling constraint-name
439    // builders above, instead of routing through `format!`. Output is
440    // byte-identical: `{table}_{enum_name}` (`'_'` = 1 byte).
441    let mut out = String::with_capacity(table.len() + 1 + enum_name.len());
442    out.push_str(table);
443    out.push('_');
444    out.push_str(enum_name);
445    out
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use proptest::prelude::*;
452    use rstest::rstest;
453
454    // ========================================================================
455    // Relation Naming Tests
456    // ========================================================================
457
458    #[test]
459    fn test_extract_relation_prefix_default_fk() {
460        // Default FK: column matches table name + ref_column suffix
461        assert_eq!(extract_relation_prefix("user_id", "user", "id"), "");
462        assert_eq!(extract_relation_prefix("org_id", "org", "id"), "");
463        assert_eq!(extract_relation_prefix("post_id", "post", "id"), "");
464    }
465
466    #[test]
467    fn test_extract_relation_prefix_different_ref_column() {
468        // Handle different ref_column suffixes (not just _id)
469        assert_eq!(extract_relation_prefix("user_idx", "user", "idx"), "");
470        assert_eq!(extract_relation_prefix("user_pk", "user", "pk"), "");
471        assert_eq!(extract_relation_prefix("user_key", "user", "key"), "");
472    }
473
474    #[test]
475    fn test_extract_relation_prefix_semantic_prefix() {
476        // Prefixed FK: has semantic prefix before table name
477        assert_eq!(
478            extract_relation_prefix("answered_by_user_id", "user", "id"),
479            "answered_by"
480        );
481        assert_eq!(
482            extract_relation_prefix("created_by_user_id", "user", "id"),
483            "created_by"
484        );
485        assert_eq!(
486            extract_relation_prefix("target_user_id", "user", "id"),
487            "target"
488        );
489        assert_eq!(
490            extract_relation_prefix("parent_org_id", "org", "id"),
491            "parent"
492        );
493    }
494
495    #[test]
496    fn test_extract_relation_prefix_role_fk() {
497        // Role FK: column doesn't end with table name
498        assert_eq!(extract_relation_prefix("author_id", "user", "id"), "author");
499        assert_eq!(extract_relation_prefix("owner_id", "user", "id"), "owner");
500        assert_eq!(
501            extract_relation_prefix("creator_id", "user", "id"),
502            "creator"
503        );
504    }
505
506    #[test]
507    fn test_extract_relation_prefix_no_suffix() {
508        // Edge case: no ref_column suffix
509        assert_eq!(extract_relation_prefix("user", "user", "id"), "");
510        assert_eq!(extract_relation_prefix("admin_user", "user", "id"), "admin");
511    }
512
513    #[test]
514    fn test_extract_relation_prefix_unicode_table_name() {
515        assert_eq!(
516            extract_relation_prefix("작성자_한국어테이블_id", "한국어테이블", "id"),
517            "작성자"
518        );
519        assert_eq!(extract_relation_prefix("📊_stats_id", "📊_stats", "id"), "");
520    }
521
522    #[test]
523    fn test_pluralize_unicode_name_ending_with_ascii_y() {
524        assert_eq!(pluralize("café_category"), "café_categories");
525    }
526
527    proptest! {
528        #[test]
529        fn extract_relation_prefix_does_not_panic_on_unicode(
530            table in proptest::collection::vec(any::<char>(), 0..30).prop_map(|v| v.into_iter().collect::<String>()),
531            prefix in proptest::collection::vec(any::<char>(), 0..30).prop_map(|v| v.into_iter().collect::<String>())
532        ) {
533            let fk_column = format!("{prefix}_{table}_id");
534            let _ = extract_relation_prefix(&fk_column, &table, "id");
535        }
536    }
537
538    #[test]
539    fn test_build_reverse_relation_field_name_single_fk() {
540        // Single FK - just use source table name
541        assert_eq!(
542            build_reverse_relation_field_name(
543                &["user_id".into()],
544                "user",
545                "inquiry",
546                "id",
547                false,
548                false
549            ),
550            "inquiries"
551        );
552        assert_eq!(
553            build_reverse_relation_field_name(
554                &["author_id".into()],
555                "user",
556                "comment",
557                "id",
558                false,
559                false
560            ),
561            "comments"
562        );
563    }
564
565    #[test]
566    fn test_build_reverse_relation_field_name_multiple_fks() {
567        // Multiple FKs - need disambiguation
568        assert_eq!(
569            build_reverse_relation_field_name(
570                &["user_id".into()],
571                "user",
572                "inquiry",
573                "id",
574                true,
575                false
576            ),
577            "inquiries"
578        );
579        assert_eq!(
580            build_reverse_relation_field_name(
581                &["answered_by_user_id".into()],
582                "user",
583                "inquiry",
584                "id",
585                true,
586                false
587            ),
588            "answered_by_inquiries"
589        );
590    }
591
592    #[test]
593    fn test_build_reverse_relation_field_name_one_to_one() {
594        assert_eq!(
595            build_reverse_relation_field_name(
596                &["user_id".into()],
597                "user",
598                "profile",
599                "id",
600                false,
601                true
602            ),
603            "profile"
604        );
605        assert_eq!(
606            build_reverse_relation_field_name(
607                &["backup_user_id".into()],
608                "user",
609                "settings",
610                "id",
611                true,
612                true
613            ),
614            "backup_settings"
615        );
616    }
617
618    #[test]
619    fn test_build_relation_enum_name() {
620        // Empty fk_columns - early return
621        assert_eq!(build_relation_enum_name(&[], "user", "id"), "");
622
623        // Default FK - empty enum name (not needed or use table name)
624        assert_eq!(
625            build_relation_enum_name(&["user_id".into()], "user", "id"),
626            ""
627        );
628
629        // Semantic prefix - PascalCase
630        assert_eq!(
631            build_relation_enum_name(&["answered_by_user_id".into()], "user", "id"),
632            "AnsweredBy"
633        );
634        assert_eq!(
635            build_relation_enum_name(&["target_user_id".into()], "user", "id"),
636            "Target"
637        );
638
639        // Role FK - PascalCase of role
640        assert_eq!(
641            build_relation_enum_name(&["author_id".into()], "user", "id"),
642            "Author"
643        );
644    }
645
646    #[test]
647    fn test_to_pascal_case() {
648        assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
649        assert_eq!(to_pascal_case("answered_by"), "AnsweredBy");
650        assert_eq!(to_pascal_case("user"), "User");
651        assert_eq!(to_pascal_case("hello-world"), "HelloWorld");
652        assert_eq!(to_pascal_case(""), "");
653    }
654
655    #[rstest]
656    #[case::lowercase("pending", "PENDING")]
657    #[case::snake_case("not_started", "NOT_STARTED")]
658    #[case::camel_case("inProgress", "IN_PROGRESS")]
659    #[case::kebab_case("order-status", "ORDER_STATUS")]
660    #[case::empty("", "")]
661    // Already-uppercase input survives: a position-based word-boundary rule
662    // would explode these into `E_R_R_O_R__L_E_V_E_L` / `H_T_T_P__500`.
663    #[case::already_screaming("ERROR_LEVEL", "ERROR_LEVEL")]
664    #[case::acronym_with_digits("HTTP_500", "HTTP_500")]
665    #[case::trailing_separator("status-", "STATUS")]
666    // Case conversion only: making this a valid identifier is
667    // `sanitize_identifier`'s job, since the rule differs per language.
668    #[case::leading_digit("1critical", "1CRITICAL")]
669    fn test_to_screaming_snake_case(#[case] input: &str, #[case] expected: &str) {
670        assert_eq!(to_screaming_snake_case(input), expected);
671    }
672
673    #[rstest]
674    #[case::already_valid("email", IdentifierStart::Underscore, "email")]
675    #[case::internal_digits("table_99_ok", IdentifierStart::Underscore, "table_99_ok")]
676    #[case::hyphen("user-id", IdentifierStart::Underscore, "user_id")]
677    #[case::space("user id", IdentifierStart::Underscore, "user_id")]
678    #[case::non_ascii("사용자", IdentifierStart::Underscore, "___")]
679    #[case::leading_digit_underscore("1st_place", IdentifierStart::Underscore, "_1st_place")]
680    #[case::leading_digit_letter("1st_place", IdentifierStart::Letter, "x1st_place")]
681    // The escape follows the case of the first letter it precedes.
682    #[case::leading_digit_screaming("1CRITICAL", IdentifierStart::Letter, "X1CRITICAL")]
683    // Prisma and Pydantic reject a leading `_`, so it is escaped too.
684    #[case::existing_underscore_letter("_private", IdentifierStart::Letter, "x_private")]
685    #[case::existing_underscore_ok("_private", IdentifierStart::Underscore, "_private")]
686    #[case::empty_underscore("", IdentifierStart::Underscore, "_")]
687    #[case::empty_letter("", IdentifierStart::Letter, "x")]
688    fn test_sanitize_identifier(
689        #[case] input: &str,
690        #[case] start: IdentifierStart,
691        #[case] expected: &str,
692    ) {
693        assert_eq!(sanitize_identifier(input, start), expected);
694    }
695
696    #[test]
697    fn test_pluralize() {
698        assert_eq!(pluralize("inquiry"), "inquiries");
699        assert_eq!(pluralize("category"), "categories");
700        assert_eq!(pluralize("comment"), "comments");
701        assert_eq!(pluralize("user"), "users");
702        assert_eq!(pluralize("status"), "status");
703        assert_eq!(pluralize("address"), "address");
704    }
705
706    // ========================================================================
707    // Constraint Naming Tests
708    // ========================================================================
709
710    /// The three builders monomorphized for `&[&str]` columns.
711    /// Column strings are `'static` so the generic builders (whose column
712    /// lifetime is fixed at instantiation) can coerce to a single fn pointer.
713    type BuildFn = fn(&str, &[&'static str], Option<&str>) -> String;
714    /// The three builders monomorphized for `&[String]` columns.
715    type BuildStringFn = fn(&str, &[String], Option<&str>) -> String;
716
717    #[rstest]
718    #[case::index_with_key(build_index_name, "users", &["email"][..], Some("email_idx"), "ix_users__email_idx")]
719    #[case::index_without_key(build_index_name, "users", &["email"][..], None, "ix_users__email")]
720    #[case::index_multiple_columns(build_index_name, "users", &["first_name", "last_name"][..], None, "ix_users__first_name_last_name")]
721    #[case::unique_with_key(build_unique_constraint_name, "users", &["email"][..], Some("email_unique"), "uq_users__email_unique")]
722    #[case::unique_without_key(build_unique_constraint_name, "users", &["email"][..], None, "uq_users__email")]
723    #[case::foreign_key_with_key(build_foreign_key_name, "posts", &["user_id"][..], Some("fk_user"), "fk_posts__fk_user")]
724    #[case::foreign_key_without_key(build_foreign_key_name, "posts", &["user_id"][..], None, "fk_posts__user_id")]
725    fn constraint_name_builders_render_expected(
726        #[case] build: BuildFn,
727        #[case] table: &str,
728        #[case] columns: &[&'static str],
729        #[case] key: Option<&str>,
730        #[case] expected: &str,
731    ) {
732        assert_eq!(build(table, columns, key), expected);
733    }
734
735    /// Column order must not affect the generated name (`&[&str]` instantiation).
736    #[rstest]
737    #[case::index(build_index_name, "users", &["last_name", "first_name"][..])]
738    #[case::unique(build_unique_constraint_name, "users", &["last_name", "first_name"][..])]
739    #[case::foreign_key(build_foreign_key_name, "posts", &["tenant_id", "user_id"][..])]
740    fn constraint_name_builders_sort_str_columns_for_deterministic_name(
741        #[case] build: BuildFn,
742        #[case] table: &str,
743        #[case] columns: &[&'static str],
744    ) {
745        let mut reversed = columns.to_vec();
746        reversed.reverse();
747        assert_eq!(build(table, columns, None), build(table, &reversed, None));
748    }
749
750    /// Column order must not affect the generated name (`&[String]` instantiation).
751    #[rstest]
752    #[case::index(build_index_name, "users", &["last_name", "first_name"][..])]
753    #[case::unique(build_unique_constraint_name, "order_items", &["product_id", "order_id"][..])]
754    #[case::foreign_key(build_foreign_key_name, "memberships", &["tenant_id", "account_id"][..])]
755    fn constraint_name_builders_sort_string_columns_for_deterministic_name(
756        #[case] build: BuildStringFn,
757        #[case] table: &str,
758        #[case] columns: &[&str],
759    ) {
760        let columns: Vec<String> = columns.iter().map(ToString::to_string).collect();
761        let mut reversed = columns.clone();
762        reversed.reverse();
763        assert_eq!(build(table, &columns, None), build(table, &reversed, None));
764    }
765
766    #[test]
767    fn test_build_check_constraint_name() {
768        assert_eq!(
769            build_check_constraint_name("users", "status"),
770            "chk_users__status"
771        );
772    }
773
774    #[test]
775    fn test_build_enum_type_name() {
776        assert_eq!(build_enum_type_name("users", "status"), "users_status");
777    }
778
779    #[test]
780    fn test_build_enum_type_name_with_existing_prefix() {
781        // Even if enum_name already has table prefix, we add it
782        // User should provide clean enum name (e.g., "status" not "users_status")
783        assert_eq!(
784            build_enum_type_name("users", "user_status"),
785            "users_user_status"
786        );
787    }
788
789    #[test]
790    fn test_build_enum_type_name_prevents_conflicts() {
791        // Different tables can have same enum name without conflict
792        assert_eq!(build_enum_type_name("users", "gender"), "users_gender");
793        assert_eq!(
794            build_enum_type_name("employees", "gender"),
795            "employees_gender"
796        );
797
798        assert_eq!(build_enum_type_name("orders", "status"), "orders_status");
799        assert_eq!(
800            build_enum_type_name("shipments", "status"),
801            "shipments_status"
802        );
803    }
804}