Skip to content

Commit

Permalink
Database SnakeCaseNaming fixes
Browse files Browse the repository at this point in the history
Fixes formatting of owned entity type property names. These are normally named "FooBar_Baz" by EF Core, but the snake case thing was turning them into "foo_bar__baz". The double underscore is now fixed.

We don't *yet* have any EF Core owned entity in use, but I am planning to add one. I don't know if downstreams are using any so this should still be marked as a breaking change.

Also fixed it creating and dropping a Compiled Regex instance for every name, the regex is now cached (and pregenerated).
  • Loading branch information
PJB3005 authored and MilonPL committed Nov 29, 2024
1 parent 6ca5436 commit a896533
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions Content.Server.Database/SnakeCaseNaming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public ConventionSet ModifyConventions(ConventionSet conventionSet)
}
}

public class SnakeCaseConvention :
public partial class SnakeCaseConvention :
IEntityTypeAddedConvention,
IEntityTypeAnnotationChangedConvention,
IPropertyAddedConvention,
Expand All @@ -99,22 +99,27 @@ public SnakeCaseConvention() {}

public static string RewriteName(string name)
{
var regex = new Regex("[A-Z]+", RegexOptions.Compiled);
return regex.Replace(
name,
(Match match) => {
if (match.Index == 0 && (match.Value == "FK" || match.Value == "PK" || match.Value == "IX")) {
return match.Value;
return UpperCaseLocator()
.Replace(
name,
(Match match) => {
if (match.Index == 0 && (match.Value == "FK" || match.Value == "PK" || match.Value == "IX")) {
return match.Value;
}
if (match.Value == "HWI")
return (match.Index == 0 ? "" : "_") + "hwi";
if (match.Index == 0)
return match.Value.ToLower();
if (match.Length > 1)
return $"_{match.Value[..^1].ToLower()}_{match.Value[^1..^0].ToLower()}";

// Do not add a _ if there is already one before this. This happens with owned entities.
if (name[match.Index - 1] == '_')
return match.Value.ToLower();

return "_" + match.Value.ToLower();
}
if (match.Value == "HWI")
return (match.Index == 0 ? "" : "_") + "hwi";
if (match.Index == 0)
return match.Value.ToLower();
if (match.Length > 1)
return $"_{match.Value[..^1].ToLower()}_{match.Value[^1..^0].ToLower()}";
return "_" + match.Value.ToLower();
}
);
);
}

public virtual void ProcessEntityTypeAdded(
Expand Down Expand Up @@ -332,5 +337,8 @@ private static void RewriteColumnName(IConventionPropertyBuilder propertyBuilder
}
}
}

[GeneratedRegex("[A-Z]+", RegexOptions.Compiled)]
private static partial Regex UpperCaseLocator();
}
}

0 comments on commit a896533

Please sign in to comment.