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