1
0

SnakeCaseNaming.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.EntityFrameworkCore.Infrastructure;
  7. using Microsoft.EntityFrameworkCore.Metadata;
  8. using Microsoft.EntityFrameworkCore.Metadata.Builders;
  9. using Microsoft.EntityFrameworkCore.Metadata.Conventions;
  10. using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
  11. using Microsoft.Extensions.DependencyInjection;
  12. namespace Content.Server.Database
  13. {
  14. public class SnakeCaseExtension : IDbContextOptionsExtension
  15. {
  16. public DbContextOptionsExtensionInfo Info { get; }
  17. public SnakeCaseExtension() {
  18. Info = new ExtensionInfo(this);
  19. }
  20. public void ApplyServices(IServiceCollection services)
  21. {
  22. services.AddSnakeCase();
  23. }
  24. public void Validate(IDbContextOptions options) {}
  25. private sealed class ExtensionInfo : DbContextOptionsExtensionInfo
  26. {
  27. public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) {}
  28. public override bool IsDatabaseProvider => false;
  29. public override string LogFragment => "Snake Case Extension";
  30. public override int GetServiceProviderHashCode()
  31. {
  32. return 0;
  33. }
  34. public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other)
  35. {
  36. return other is ExtensionInfo;
  37. }
  38. public override void PopulateDebugInfo(IDictionary<string, string> debugInfo)
  39. {
  40. }
  41. }
  42. }
  43. public static class SnakeCaseServiceCollectionExtensions
  44. {
  45. public static IServiceCollection AddSnakeCase(
  46. this IServiceCollection serviceCollection)
  47. {
  48. new EntityFrameworkServicesBuilder(serviceCollection)
  49. .TryAdd<IConventionSetPlugin, SnakeCaseConventionSetPlugin>();
  50. return serviceCollection;
  51. }
  52. }
  53. public class SnakeCaseConventionSetPlugin : IConventionSetPlugin
  54. {
  55. public ConventionSet ModifyConventions(ConventionSet conventionSet)
  56. {
  57. var convention = new SnakeCaseConvention();
  58. conventionSet.EntityTypeAddedConventions.Add(convention);
  59. conventionSet.EntityTypeAnnotationChangedConventions.Add(convention);
  60. conventionSet.PropertyAddedConventions.Add(convention);
  61. conventionSet.ForeignKeyOwnershipChangedConventions.Add(convention);
  62. conventionSet.KeyAddedConventions.Add(convention);
  63. conventionSet.ForeignKeyAddedConventions.Add(convention);
  64. conventionSet.EntityTypeBaseTypeChangedConventions.Add(convention);
  65. conventionSet.ModelFinalizingConventions.Add(convention);
  66. return conventionSet;
  67. }
  68. }
  69. public partial class SnakeCaseConvention :
  70. IEntityTypeAddedConvention,
  71. IEntityTypeAnnotationChangedConvention,
  72. IPropertyAddedConvention,
  73. IForeignKeyOwnershipChangedConvention,
  74. IKeyAddedConvention,
  75. IForeignKeyAddedConvention,
  76. IEntityTypeBaseTypeChangedConvention,
  77. IModelFinalizingConvention
  78. {
  79. private static readonly StoreObjectType[] _storeObjectTypes
  80. = { StoreObjectType.Table, StoreObjectType.View, StoreObjectType.Function, StoreObjectType.SqlQuery };
  81. public SnakeCaseConvention() {}
  82. public static string RewriteName(string name)
  83. {
  84. return UpperCaseLocator()
  85. .Replace(
  86. name,
  87. (Match match) => {
  88. if (match.Index == 0 && (match.Value == "FK" || match.Value == "PK" || match.Value == "IX")) {
  89. return match.Value;
  90. }
  91. if (match.Value == "HWI")
  92. return (match.Index == 0 ? "" : "_") + "hwi";
  93. if (match.Index == 0)
  94. return match.Value.ToLower();
  95. if (match.Length > 1)
  96. return $"_{match.Value[..^1].ToLower()}_{match.Value[^1..^0].ToLower()}";
  97. // Do not add a _ if there is already one before this. This happens with owned entities.
  98. if (name[match.Index - 1] == '_')
  99. return match.Value.ToLower();
  100. return "_" + match.Value.ToLower();
  101. }
  102. );
  103. }
  104. public virtual void ProcessEntityTypeAdded(
  105. IConventionEntityTypeBuilder entityTypeBuilder,
  106. IConventionContext<IConventionEntityTypeBuilder> context)
  107. {
  108. var entityType = entityTypeBuilder.Metadata;
  109. if (entityType.ClrType == typeof(Microsoft.EntityFrameworkCore.Migrations.HistoryRow))
  110. return;
  111. if (entityType.BaseType is null)
  112. {
  113. entityTypeBuilder.ToTable(RewriteName(entityType.GetTableName()!), entityType.GetSchema());
  114. if (entityType.GetViewNameConfigurationSource() == ConfigurationSource.Convention)
  115. {
  116. entityTypeBuilder.ToView(RewriteName(entityType.GetViewName()!), entityType.GetViewSchema());
  117. }
  118. }
  119. }
  120. public void ProcessEntityTypeBaseTypeChanged(
  121. IConventionEntityTypeBuilder entityTypeBuilder,
  122. IConventionEntityType? newBaseType,
  123. IConventionEntityType? oldBaseType,
  124. IConventionContext<IConventionEntityType> context)
  125. {
  126. var entityType = entityTypeBuilder.Metadata;
  127. if (newBaseType is null)
  128. {
  129. entityTypeBuilder.ToTable(RewriteName(entityType.GetTableName()!), entityType.GetSchema());
  130. }
  131. else
  132. {
  133. entityTypeBuilder.HasNoAnnotation(RelationalAnnotationNames.TableName);
  134. entityTypeBuilder.HasNoAnnotation(RelationalAnnotationNames.Schema);
  135. }
  136. }
  137. public virtual void ProcessPropertyAdded(
  138. IConventionPropertyBuilder propertyBuilder,
  139. IConventionContext<IConventionPropertyBuilder> context)
  140. {
  141. RewriteColumnName(propertyBuilder);
  142. }
  143. public void ProcessForeignKeyOwnershipChanged(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext<bool?> context)
  144. {
  145. var foreignKey = relationshipBuilder.Metadata;
  146. var ownedEntityType = foreignKey.DeclaringEntityType;
  147. if (foreignKey.IsOwnership && ownedEntityType.GetTableNameConfigurationSource() != ConfigurationSource.Explicit)
  148. {
  149. ownedEntityType.Builder.HasNoAnnotation(RelationalAnnotationNames.TableName);
  150. ownedEntityType.Builder.HasNoAnnotation(RelationalAnnotationNames.Schema);
  151. ownedEntityType.FindPrimaryKey()?.Builder.HasNoAnnotation(RelationalAnnotationNames.Name);
  152. foreach (var property in ownedEntityType.GetProperties())
  153. {
  154. RewriteColumnName(property.Builder);
  155. }
  156. }
  157. }
  158. public void ProcessEntityTypeAnnotationChanged(
  159. IConventionEntityTypeBuilder entityTypeBuilder,
  160. string name,
  161. IConventionAnnotation? annotation,
  162. IConventionAnnotation? oldAnnotation,
  163. IConventionContext<IConventionAnnotation> context)
  164. {
  165. var entityType = entityTypeBuilder.Metadata;
  166. if (entityType.ClrType == typeof(Microsoft.EntityFrameworkCore.Migrations.HistoryRow))
  167. return;
  168. if (name != RelationalAnnotationNames.TableName
  169. || StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) is not StoreObjectIdentifier tableIdentifier)
  170. {
  171. return;
  172. }
  173. if (entityType.FindPrimaryKey() is { } primaryKey)
  174. {
  175. if (entityType.FindRowInternalForeignKeys(tableIdentifier).FirstOrDefault() is null
  176. && (entityType.BaseType is null || entityType.GetTableName() == entityType.BaseType.GetTableName()))
  177. {
  178. primaryKey.Builder.HasName(RewriteName(primaryKey.GetDefaultName()!));
  179. }
  180. else
  181. {
  182. primaryKey.Builder.HasNoAnnotation(RelationalAnnotationNames.Name);
  183. }
  184. }
  185. foreach (var foreignKey in entityType.GetForeignKeys())
  186. {
  187. foreignKey.Builder.HasConstraintName(RewriteName(foreignKey.GetDefaultName()!));
  188. }
  189. foreach (var index in entityType.GetIndexes())
  190. {
  191. index.Builder.HasDatabaseName(RewriteName(index.GetDefaultDatabaseName()!));
  192. }
  193. if (annotation?.Value is not null
  194. && entityType.FindOwnership() is { } ownership
  195. && (string)annotation.Value != ownership.PrincipalEntityType.GetTableName())
  196. {
  197. foreach (var property in entityType.GetProperties()
  198. .Except(entityType.FindPrimaryKey()!.Properties)
  199. .Where(p => p.Builder.CanSetColumnName(null)))
  200. {
  201. RewriteColumnName(property.Builder);
  202. }
  203. if (entityType.FindPrimaryKey() is { } key)
  204. {
  205. key.Builder.HasName(RewriteName(key.GetDefaultName()!));
  206. }
  207. }
  208. }
  209. public void ProcessForeignKeyAdded(
  210. IConventionForeignKeyBuilder relationshipBuilder,
  211. IConventionContext<IConventionForeignKeyBuilder> context)
  212. {
  213. relationshipBuilder.HasConstraintName(RewriteName(relationshipBuilder.Metadata.GetDefaultName()!));
  214. }
  215. public void ProcessKeyAdded(IConventionKeyBuilder keyBuilder, IConventionContext<IConventionKeyBuilder> context)
  216. {
  217. var entityType = keyBuilder.Metadata.DeclaringEntityType;
  218. if (entityType.ClrType == typeof(Microsoft.EntityFrameworkCore.Migrations.HistoryRow))
  219. return;
  220. if (entityType.FindOwnership() is null)
  221. {
  222. keyBuilder.HasName(RewriteName(keyBuilder.Metadata.GetDefaultName()!));
  223. }
  224. }
  225. public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> context)
  226. {
  227. foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
  228. {
  229. if (entityType.ClrType == typeof(Microsoft.EntityFrameworkCore.Migrations.HistoryRow))
  230. continue;
  231. foreach (var property in entityType.GetProperties())
  232. {
  233. var columnName = property.GetColumnName();
  234. if (columnName.StartsWith(entityType.ShortName() + '_', StringComparison.Ordinal))
  235. {
  236. property.Builder.HasColumnName(
  237. RewriteName(entityType.ShortName()) + columnName[entityType.ShortName().Length..]);
  238. }
  239. foreach (var storeObjectType in _storeObjectTypes)
  240. {
  241. var identifier = StoreObjectIdentifier.Create(entityType, storeObjectType);
  242. if (identifier is null)
  243. continue;
  244. if (property.GetColumnNameConfigurationSource(identifier.Value) == ConfigurationSource.Convention)
  245. {
  246. columnName = property.GetColumnName(identifier.Value)!;
  247. if (columnName.StartsWith(entityType.ShortName() + '_', StringComparison.Ordinal))
  248. {
  249. property.Builder.HasColumnName(
  250. RewriteName(entityType.ShortName())
  251. + columnName[entityType.ShortName().Length..]);
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. private static void RewriteColumnName(IConventionPropertyBuilder propertyBuilder)
  259. {
  260. var property = propertyBuilder.Metadata;
  261. var entityType = (IConventionEntityType)property.DeclaringType;
  262. if (entityType.ClrType == typeof(Microsoft.EntityFrameworkCore.Migrations.HistoryRow))
  263. return;
  264. property.Builder.HasNoAnnotation(RelationalAnnotationNames.ColumnName);
  265. var baseColumnName = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) is { } tableIdentifier
  266. ? property.GetDefaultColumnName(tableIdentifier)
  267. : property.GetDefaultColumnName();
  268. if (baseColumnName == "Id")
  269. baseColumnName = entityType.GetTableName() + baseColumnName;
  270. propertyBuilder.HasColumnName(RewriteName(baseColumnName!));
  271. foreach (var storeObjectType in _storeObjectTypes)
  272. {
  273. var identifier = StoreObjectIdentifier.Create(entityType, storeObjectType);
  274. if (identifier is null)
  275. continue;
  276. if (property.GetColumnNameConfigurationSource(identifier.Value) == ConfigurationSource.Convention)
  277. {
  278. var name = property.GetColumnName(identifier.Value);
  279. if (name == "Id")
  280. name = entityType.GetTableName() + name;
  281. propertyBuilder.HasColumnName(
  282. RewriteName(name!), identifier.Value);
  283. }
  284. }
  285. }
  286. [GeneratedRegex("[A-Z]+", RegexOptions.Compiled)]
  287. private static partial Regex UpperCaseLocator();
  288. }
  289. }