pub fn extract_relation_prefix(fk_column: &str, current_table: &str, ref_column: &str) -> String {
let ref_suffix = format!("_{ref_column}");
let without_ref = if let Some(stripped) = fk_column.strip_suffix(&ref_suffix) {
stripped
} else {
fk_column
};
let current_lower = current_table.to_lowercase();
let without_ref_lower = without_ref.to_lowercase();
if without_ref_lower == current_lower {
return String::new();
}
let table_suffix = format!("_{current_lower}");
if without_ref_lower.ends_with(&table_suffix) {
let prefix_chars = without_ref_lower.chars().count() - table_suffix.chars().count();
return without_ref.chars().take(prefix_chars).collect();
}
without_ref.to_string()
}
pub fn build_reverse_relation_field_name(
fk_columns: &[String],
current_table: &str,
source_table: &str,
ref_column: &str,
has_multiple_fks: bool,
is_one_to_one: bool,
) -> String {
let base_name = if is_one_to_one {
source_table.to_string()
} else {
pluralize(source_table)
};
if !has_multiple_fks || fk_columns.is_empty() {
return base_name;
}
let prefix = extract_relation_prefix(&fk_columns[0], current_table, ref_column);
if prefix.is_empty() {
base_name
} else {
format!("{prefix}_{base_name}")
}
}
pub fn build_relation_enum_name(
fk_columns: &[String],
current_table: &str,
ref_column: &str,
) -> String {
if fk_columns.is_empty() {
return String::new();
}
let prefix = extract_relation_prefix(&fk_columns[0], current_table, ref_column);
if prefix.is_empty() {
String::new()
} else {
to_pascal_case(&prefix)
}
}
pub fn to_pascal_case(s: &str) -> String {
let mut result = String::new();
let mut capitalize = true;
for c in s.chars() {
let is_separator = c == '_' || c == '-';
if is_separator {
capitalize = true;
continue;
}
let ch = if capitalize {
c.to_ascii_uppercase()
} else {
c
};
capitalize = false;
result.push(ch);
}
result
}
pub fn pluralize(name: &str) -> String {
if name.ends_with('s') || name.ends_with("es") {
name.to_string()
} else if name.ends_with('y')
&& !name.ends_with("ay")
&& !name.ends_with("ey")
&& !name.ends_with("oy")
&& !name.ends_with("uy")
{
format!("{}ies", name.strip_suffix('y').unwrap_or(name))
} else {
format!("{name}s")
}
}
pub fn build_index_name<T: AsRef<str>>(table: &str, columns: &[T], key: Option<&str>) -> String {
match key {
Some(k) => format!("ix_{table}__{k}"),
None => format!("ix_{}__{}", table, sort_columns_for_name(columns).join("_")),
}
}
pub fn build_unique_constraint_name<T: AsRef<str>>(
table: &str,
columns: &[T],
key: Option<&str>,
) -> String {
match key {
Some(k) => format!("uq_{table}__{k}"),
None => format!("uq_{}__{}", table, sort_columns_for_name(columns).join("_")),
}
}
pub fn build_foreign_key_name<T: AsRef<str>>(
table: &str,
columns: &[T],
key: Option<&str>,
) -> String {
match key {
Some(k) => format!("fk_{table}__{k}"),
None => format!("fk_{}__{}", table, sort_columns_for_name(columns).join("_")),
}
}
fn sort_columns_for_name<T: AsRef<str>>(columns: &[T]) -> Vec<&str> {
let mut sorted: Vec<&str> = columns.iter().map(AsRef::as_ref).collect();
sorted.sort_unstable();
sorted
}
pub fn build_check_constraint_name(table: &str, column: &str) -> String {
format!("chk_{table}__{column}")
}
pub fn build_enum_type_name(table: &str, enum_name: &str) -> String {
format!("{table}_{enum_name}")
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn test_extract_relation_prefix_default_fk() {
assert_eq!(extract_relation_prefix("user_id", "user", "id"), "");
assert_eq!(extract_relation_prefix("org_id", "org", "id"), "");
assert_eq!(extract_relation_prefix("post_id", "post", "id"), "");
}
#[test]
fn test_extract_relation_prefix_different_ref_column() {
assert_eq!(extract_relation_prefix("user_idx", "user", "idx"), "");
assert_eq!(extract_relation_prefix("user_pk", "user", "pk"), "");
assert_eq!(extract_relation_prefix("user_key", "user", "key"), "");
}
#[test]
fn test_extract_relation_prefix_semantic_prefix() {
assert_eq!(
extract_relation_prefix("answered_by_user_id", "user", "id"),
"answered_by"
);
assert_eq!(
extract_relation_prefix("created_by_user_id", "user", "id"),
"created_by"
);
assert_eq!(
extract_relation_prefix("target_user_id", "user", "id"),
"target"
);
assert_eq!(
extract_relation_prefix("parent_org_id", "org", "id"),
"parent"
);
}
#[test]
fn test_extract_relation_prefix_role_fk() {
assert_eq!(extract_relation_prefix("author_id", "user", "id"), "author");
assert_eq!(extract_relation_prefix("owner_id", "user", "id"), "owner");
assert_eq!(
extract_relation_prefix("creator_id", "user", "id"),
"creator"
);
}
#[test]
fn test_extract_relation_prefix_no_suffix() {
assert_eq!(extract_relation_prefix("user", "user", "id"), "");
assert_eq!(extract_relation_prefix("admin_user", "user", "id"), "admin");
}
#[test]
fn test_extract_relation_prefix_unicode_table_name() {
assert_eq!(
extract_relation_prefix("작성자_한국어테이블_id", "한국어테이블", "id"),
"작성자"
);
assert_eq!(extract_relation_prefix("📊_stats_id", "📊_stats", "id"), "");
}
#[test]
fn test_pluralize_unicode_name_ending_with_ascii_y() {
assert_eq!(pluralize("café_category"), "café_categories");
}
proptest! {
#[test]
fn extract_relation_prefix_does_not_panic_on_unicode(
table in proptest::collection::vec(any::<char>(), 0..30).prop_map(|v| v.into_iter().collect::<String>()),
prefix in proptest::collection::vec(any::<char>(), 0..30).prop_map(|v| v.into_iter().collect::<String>())
) {
let fk_column = format!("{prefix}_{table}_id");
let _ = extract_relation_prefix(&fk_column, &table, "id");
}
}
#[test]
fn test_build_reverse_relation_field_name_single_fk() {
assert_eq!(
build_reverse_relation_field_name(
&["user_id".into()],
"user",
"inquiry",
"id",
false,
false
),
"inquiries"
);
assert_eq!(
build_reverse_relation_field_name(
&["author_id".into()],
"user",
"comment",
"id",
false,
false
),
"comments"
);
}
#[test]
fn test_build_reverse_relation_field_name_multiple_fks() {
assert_eq!(
build_reverse_relation_field_name(
&["user_id".into()],
"user",
"inquiry",
"id",
true,
false
),
"inquiries"
);
assert_eq!(
build_reverse_relation_field_name(
&["answered_by_user_id".into()],
"user",
"inquiry",
"id",
true,
false
),
"answered_by_inquiries"
);
}
#[test]
fn test_build_reverse_relation_field_name_one_to_one() {
assert_eq!(
build_reverse_relation_field_name(
&["user_id".into()],
"user",
"profile",
"id",
false,
true
),
"profile"
);
assert_eq!(
build_reverse_relation_field_name(
&["backup_user_id".into()],
"user",
"settings",
"id",
true,
true
),
"backup_settings"
);
}
#[test]
fn test_build_relation_enum_name() {
assert_eq!(build_relation_enum_name(&[], "user", "id"), "");
assert_eq!(
build_relation_enum_name(&["user_id".into()], "user", "id"),
""
);
assert_eq!(
build_relation_enum_name(&["answered_by_user_id".into()], "user", "id"),
"AnsweredBy"
);
assert_eq!(
build_relation_enum_name(&["target_user_id".into()], "user", "id"),
"Target"
);
assert_eq!(
build_relation_enum_name(&["author_id".into()], "user", "id"),
"Author"
);
}
#[test]
fn test_to_pascal_case() {
assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
assert_eq!(to_pascal_case("answered_by"), "AnsweredBy");
assert_eq!(to_pascal_case("user"), "User");
assert_eq!(to_pascal_case("hello-world"), "HelloWorld");
assert_eq!(to_pascal_case(""), "");
}
#[test]
fn test_pluralize() {
assert_eq!(pluralize("inquiry"), "inquiries");
assert_eq!(pluralize("category"), "categories");
assert_eq!(pluralize("comment"), "comments");
assert_eq!(pluralize("user"), "users");
assert_eq!(pluralize("status"), "status");
assert_eq!(pluralize("address"), "address");
}
#[test]
fn test_build_index_name_with_key() {
assert_eq!(
build_index_name("users", &["email"], Some("email_idx")),
"ix_users__email_idx"
);
}
#[test]
fn test_build_index_name_without_key() {
assert_eq!(
build_index_name("users", &["email"], None),
"ix_users__email"
);
}
#[test]
fn test_build_index_name_multiple_columns() {
assert_eq!(
build_index_name("users", &["first_name", "last_name"], None),
"ix_users__first_name_last_name"
);
}
#[test]
fn test_build_index_name_multiple_columns_is_deterministic() {
assert_eq!(
build_index_name("users", &["last_name", "first_name"], None),
build_index_name("users", &["first_name", "last_name"], None)
);
}
#[test]
fn test_build_index_name_sorts_columns_for_deterministic_name() {
let columns = vec!["last_name".to_string(), "first_name".to_string()];
let reversed = vec!["first_name".to_string(), "last_name".to_string()];
assert_eq!(
build_index_name("users", &columns, None),
build_index_name("users", &reversed, None)
);
}
#[test]
fn test_build_unique_constraint_name_with_key() {
assert_eq!(
build_unique_constraint_name("users", &["email"], Some("email_unique")),
"uq_users__email_unique"
);
}
#[test]
fn test_build_unique_constraint_name_without_key() {
assert_eq!(
build_unique_constraint_name("users", &["email"], None),
"uq_users__email"
);
}
#[test]
fn test_build_unique_constraint_name_multiple_columns_is_deterministic() {
assert_eq!(
build_unique_constraint_name("users", &["last_name", "first_name"], None),
build_unique_constraint_name("users", &["first_name", "last_name"], None)
);
}
#[test]
fn test_build_unique_constraint_name_sorts_columns_for_deterministic_name() {
let columns = vec!["product_id".to_string(), "order_id".to_string()];
let reversed = vec!["order_id".to_string(), "product_id".to_string()];
assert_eq!(
build_unique_constraint_name("order_items", &columns, None),
build_unique_constraint_name("order_items", &reversed, None)
);
}
#[test]
fn test_build_foreign_key_name_with_key() {
assert_eq!(
build_foreign_key_name("posts", &["user_id"], Some("fk_user")),
"fk_posts__fk_user"
);
}
#[test]
fn test_build_foreign_key_name_without_key() {
assert_eq!(
build_foreign_key_name("posts", &["user_id"], None),
"fk_posts__user_id"
);
}
#[test]
fn test_build_foreign_key_name_multiple_columns_is_deterministic() {
assert_eq!(
build_foreign_key_name("posts", &["tenant_id", "user_id"], None),
build_foreign_key_name("posts", &["user_id", "tenant_id"], None)
);
}
#[test]
fn test_build_foreign_key_name_sorts_columns_for_deterministic_name() {
let columns = vec!["tenant_id".to_string(), "account_id".to_string()];
let reversed = vec!["account_id".to_string(), "tenant_id".to_string()];
assert_eq!(
build_foreign_key_name("memberships", &columns, None),
build_foreign_key_name("memberships", &reversed, None)
);
}
#[test]
fn test_build_check_constraint_name() {
assert_eq!(
build_check_constraint_name("users", "status"),
"chk_users__status"
);
}
#[test]
fn test_build_enum_type_name() {
assert_eq!(build_enum_type_name("users", "status"), "users_status");
}
#[test]
fn test_build_enum_type_name_with_existing_prefix() {
assert_eq!(
build_enum_type_name("users", "user_status"),
"users_user_status"
);
}
#[test]
fn test_build_enum_type_name_prevents_conflicts() {
assert_eq!(build_enum_type_name("users", "gender"), "users_gender");
assert_eq!(
build_enum_type_name("employees", "gender"),
"employees_gender"
);
assert_eq!(build_enum_type_name("orders", "status"), "orders_status");
assert_eq!(
build_enum_type_name("shipments", "status"),
"shipments_status"
);
}
}