sanitizedKey method

String sanitizedKey(
  1. List<String> endings
)

Generates a sanitized key for the foreign key relationship, used for generating field names in model classes.

It takes the first local column name of the foreign key, removes any specified endings (like "_id", "Id", "uuid"), converts it to camelCase, and then:

  • If the resulting name (lowercase) matches the foreign table name (lowercase), it returns the pluralized version of that name. Example: author_id in books table referencing authors table -> authors.
  • Otherwise, it appends the capitalized camelCase foreign table name to ensure uniqueness. Example: primary_author_id in books table referencing authors table -> primaryAuthorAuthors.

This helps create intuitive field names for relationships. For instance, a Book model might have an author field (if FK is author_id) or coAuthorAuthors (if FK is co_author_id pointing to authors table).

Implementation

String sanitizedKey(List<String> endings) {
  String baseName = originalColumns.first;

  // Remove any matching ending from the column name
  for (final ending in endings) {
    if (baseName.toLowerCase().endsWith(ending.toLowerCase())) {
      baseName = baseName.substring(0, baseName.length - ending.length);
      break; // Stop after the first match
    }
  }

  // Convert the base name to camelCase
  baseName = StringUtils.toCamelCase(baseName);

  // If the base name matches the foreign table name, return the pluralized table name
  if (baseName.toLowerCase() == originalForeignTableName.toLowerCase()) {
    return StringUtils.pluralize(baseName);
  }

  // Combine the base name with the foreign table name to ensure uniqueness
  return '$baseName${StringUtils.capitalize(StringUtils.toCamelCase(originalForeignTableName))}';
}