Skip to main content

schema_sql_generator/common/
constraint_naming.rs

1/// Java-compatible `String.hashCode()`: a 32-bit, base-31 polynomial hash over UTF-16 code
2/// units. All identifiers this is used for are ASCII, so iterating `char`s is equivalent.
3pub fn java_string_hash(s: &str) -> u32 {
4    s.chars()
5        .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32)) as u32
6}
7
8/// Postgres's maximum identifier length, in bytes.
9const MAX_IDENTIFIER_BYTES: usize = 63;
10
11/// Lower-cases `s` and truncates it to at most `max_len` characters.
12pub fn truncate_lower(s: &str, max_len: usize) -> String {
13    s.to_lowercase().chars().take(max_len).collect()
14}
15
16/// Builds a `{prefix}{table[0..9]}_{column[0..9]}_{HASH}` constraint name, matching the
17/// legacy Java codegen tool's naming scheme for hash-suffixed constraints (check constraints,
18/// default constraints). The hash is computed over the full (non-truncated) lowercase
19/// `"{table}_{column}"` string and formatted as uppercase hex, unpadded (matching Java's
20/// `Integer.toHexString(hash).toUpperCase()` - not zero-padded to a fixed width).
21pub fn hashed_constraint_name(prefix: &str, table_name: &str, column_name: &str) -> String {
22    let table_lower = table_name.to_lowercase();
23    let column_lower = column_name.to_lowercase();
24    let hash = java_string_hash(&format!("{}_{}", table_lower, column_lower));
25    let mut table_part = truncate_lower(&table_lower, 9);
26    let mut column_part = truncate_lower(&column_lower, 9);
27    let hash_part = format!("{:X}", hash);
28
29    // Postgres limits identifiers to 63 bytes, and a multi-byte name can exceed that within the
30    // 9-character cut; trim whole characters until it fits. ASCII names are never trimmed.
31    let fixed = prefix.len() + 2 + hash_part.len();
32    while fixed + table_part.len() + column_part.len() > MAX_IDENTIFIER_BYTES {
33        let longer = if table_part.len() >= column_part.len() {
34            &mut table_part
35        } else {
36            &mut column_part
37        };
38        if longer.pop().is_none() {
39            break;
40        }
41    }
42
43    format!("{}{}_{}_{}", prefix, table_part, column_part, hash_part)
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn java_string_hash_matches_known_values() {
52        // Verified by reproducing Java's String.hashCode() against every check/default
53        // constraint name in the legacy tool's SQL Server reference output.
54        assert_eq!(java_string_hash("earning_type_id"), 0x97E3620B);
55        assert_eq!(java_string_hash("user_id"), 0xF73AEE0F);
56        assert_eq!(
57            java_string_hash("tip_pool_contributor_template_contribution_basis"),
58            0x326125D1
59        );
60    }
61
62    #[test]
63    fn hashed_constraint_name_matches_legacy_format() {
64        assert_eq!(
65            hashed_constraint_name("df_", "earning_type", "id"),
66            "df_earning_t_id_97E3620B"
67        );
68        assert_eq!(
69            hashed_constraint_name("ck_", "tip_pool_contributor_template", "contribution_basis"),
70            "ck_tip_pool__contribut_326125D1"
71        );
72    }
73
74    #[test]
75    fn hashed_constraint_name_does_not_zero_pad_the_hash() {
76        // The legacy Java tool formats the hash with Integer.toHexString(...).toUpperCase(),
77        // which drops leading zero nibbles rather than zero-padding to a fixed width.
78        assert_eq!(
79            java_string_hash("tip_sub_pool_template_hours_mode"),
80            0x0DCD6758
81        );
82        assert_eq!(
83            hashed_constraint_name("ck_", "tip_sub_pool_template", "hours_mode"),
84            "ck_tip_sub_p_hours_mod_DCD6758"
85        );
86    }
87
88    #[test]
89    fn hashed_constraint_name_stays_within_postgres_byte_limit() {
90        let name = hashed_constraint_name("ck_", &"表".repeat(20), &"列".repeat(20));
91
92        assert!(name.len() <= 63, "{name} is {} bytes", name.len());
93    }
94}