-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathSqlServerAnnotationCodeGenerator.cs
467 lines (396 loc) · 24 KB
/
SqlServerAnnotationCodeGenerator.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.SqlServer.Design.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlServerAnnotationCodeGenerator : AnnotationCodeGenerator
{
#region MethodInfos
private static readonly MethodInfo ModelUseIdentityColumnsMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.UseIdentityColumns), new[] { typeof(ModelBuilder), typeof(long), typeof(int) })!;
private static readonly MethodInfo ModelUseHiLoMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.UseHiLo), new[] { typeof(ModelBuilder), typeof(string), typeof(string) })!;
private static readonly MethodInfo ModelUseKeySequencesMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.UseKeySequences), new[] { typeof(ModelBuilder), typeof(string), typeof(string) })!;
private static readonly MethodInfo ModelHasDatabaseMaxSizeMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.HasDatabaseMaxSize), new[] { typeof(ModelBuilder), typeof(string) })!;
private static readonly MethodInfo ModelHasServiceTierSqlMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.HasServiceTierSql), new[] { typeof(ModelBuilder), typeof(string) })!;
private static readonly MethodInfo ModelHasPerformanceLevelSqlMethodInfo
= typeof(SqlServerModelBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerModelBuilderExtensions.HasPerformanceLevelSql), new[] { typeof(ModelBuilder), typeof(string) })!;
private static readonly MethodInfo ModelHasAnnotationMethodInfo
= typeof(ModelBuilder).GetRuntimeMethod(
nameof(ModelBuilder.HasAnnotation), new[] { typeof(string), typeof(object) })!;
private static readonly MethodInfo EntityTypeToTableMethodInfo
= typeof(RelationalEntityTypeBuilderExtensions).GetRuntimeMethod(
nameof(RelationalEntityTypeBuilderExtensions.ToTable), new[] { typeof(EntityTypeBuilder), typeof(string) })!;
private static readonly MethodInfo EntityTypeIsMemoryOptimizedMethodInfo
= typeof(SqlServerEntityTypeBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerEntityTypeBuilderExtensions.IsMemoryOptimized), new[] { typeof(EntityTypeBuilder), typeof(bool) })!;
private static readonly MethodInfo PropertyIsSparseMethodInfo
= typeof(SqlServerPropertyBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerPropertyBuilderExtensions.IsSparse), new[] { typeof(PropertyBuilder), typeof(bool) })!;
private static readonly MethodInfo PropertyUseIdentityColumnsMethodInfo
= typeof(SqlServerPropertyBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerPropertyBuilderExtensions.UseIdentityColumn), new[] { typeof(PropertyBuilder), typeof(long), typeof(int) })!;
private static readonly MethodInfo PropertyUseHiLoMethodInfo
= typeof(SqlServerPropertyBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerPropertyBuilderExtensions.UseHiLo), new[] { typeof(PropertyBuilder), typeof(string), typeof(string) })!;
private static readonly MethodInfo PropertyUseSequenceMethodInfo
= typeof(SqlServerPropertyBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerPropertyBuilderExtensions.UseSequence), new[] { typeof(PropertyBuilder), typeof(string), typeof(string) })!;
private static readonly MethodInfo IndexIsClusteredMethodInfo
= typeof(SqlServerIndexBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerIndexBuilderExtensions.IsClustered), new[] { typeof(IndexBuilder), typeof(bool) })!;
private static readonly MethodInfo IndexIncludePropertiesMethodInfo
= typeof(SqlServerIndexBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerIndexBuilderExtensions.IncludeProperties), new[] { typeof(IndexBuilder), typeof(string[]) })!;
private static readonly MethodInfo IndexHasFillFactorMethodInfo
= typeof(SqlServerIndexBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerIndexBuilderExtensions.HasFillFactor), new[] { typeof(IndexBuilder), typeof(int) })!;
private static readonly MethodInfo KeyIsClusteredMethodInfo
= typeof(SqlServerKeyBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerKeyBuilderExtensions.IsClustered), new[] { typeof(KeyBuilder), typeof(bool) })!;
private static readonly MethodInfo TableIsTemporalMethodInfo
= typeof(SqlServerTableBuilderExtensions).GetRuntimeMethod(
nameof(SqlServerTableBuilderExtensions.IsTemporal), new[] { typeof(TableBuilder), typeof(bool) })!;
private static readonly MethodInfo TemporalTableUseHistoryTableMethodInfo1
= typeof(TemporalTableBuilder).GetRuntimeMethod(
nameof(TemporalTableBuilder.UseHistoryTable), new[] { typeof(string), typeof(string) })!;
private static readonly MethodInfo TemporalTableUseHistoryTableMethodInfo2
= typeof(TemporalTableBuilder).GetRuntimeMethod(
nameof(TemporalTableBuilder.UseHistoryTable), new[] { typeof(string) })!;
private static readonly MethodInfo TemporalTableHasPeriodStartMethodInfo
= typeof(TemporalTableBuilder).GetRuntimeMethod(
nameof(TemporalTableBuilder.HasPeriodStart), new[] { typeof(string) })!;
private static readonly MethodInfo TemporalTableHasPeriodEndMethodInfo
= typeof(TemporalTableBuilder).GetRuntimeMethod(
nameof(TemporalTableBuilder.HasPeriodEnd), new[] { typeof(string) })!;
private static readonly MethodInfo TemporalPropertyHasColumnNameMethodInfo
= typeof(TemporalPeriodPropertyBuilder).GetRuntimeMethod(
nameof(TemporalPeriodPropertyBuilder.HasColumnName), new[] { typeof(string) })!;
#endregion MethodInfos
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlServerAnnotationCodeGenerator(AnnotationCodeGeneratorDependencies dependencies)
: base(dependencies)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override IReadOnlyList<MethodCallCodeFragment> GenerateFluentApiCalls(
IModel model,
IDictionary<string, IAnnotation> annotations)
{
var fragments = new List<MethodCallCodeFragment>(base.GenerateFluentApiCalls(model, annotations));
if (GenerateValueGenerationStrategy(annotations, model, onModel: true) is MethodCallCodeFragment valueGenerationStrategy)
{
fragments.Add(valueGenerationStrategy);
}
GenerateSimpleFluentApiCall(
annotations,
SqlServerAnnotationNames.MaxDatabaseSize, ModelHasDatabaseMaxSizeMethodInfo,
fragments);
GenerateSimpleFluentApiCall(
annotations,
SqlServerAnnotationNames.ServiceTierSql, ModelHasServiceTierSqlMethodInfo,
fragments);
GenerateSimpleFluentApiCall(
annotations,
SqlServerAnnotationNames.PerformanceLevelSql, ModelHasPerformanceLevelSqlMethodInfo,
fragments);
return fragments;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override IReadOnlyList<MethodCallCodeFragment> GenerateFluentApiCalls(
IProperty property,
IDictionary<string, IAnnotation> annotations)
{
var fragments = new List<MethodCallCodeFragment>(base.GenerateFluentApiCalls(property, annotations));
if (GenerateValueGenerationStrategy(annotations, property.DeclaringType.Model, onModel: false) is MethodCallCodeFragment
valueGenerationStrategy)
{
fragments.Add(valueGenerationStrategy);
}
if (GetAndRemove<bool?>(annotations, SqlServerAnnotationNames.Sparse) is bool isSparse)
{
fragments.Add(
isSparse
? new MethodCallCodeFragment(PropertyIsSparseMethodInfo)
: new MethodCallCodeFragment(PropertyIsSparseMethodInfo, false));
}
return fragments;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override IReadOnlyList<MethodCallCodeFragment> GenerateFluentApiCalls(
IEntityType entityType,
IDictionary<string, IAnnotation> annotations)
{
var fragments = new List<MethodCallCodeFragment>(base.GenerateFluentApiCalls(entityType, annotations));
if (GetAndRemove<bool?>(annotations, SqlServerAnnotationNames.MemoryOptimized) is bool isMemoryOptimized)
{
fragments.Add(
isMemoryOptimized
? new MethodCallCodeFragment(EntityTypeIsMemoryOptimizedMethodInfo)
: new MethodCallCodeFragment(EntityTypeIsMemoryOptimizedMethodInfo, false));
}
if (annotations.TryGetValue(SqlServerAnnotationNames.IsTemporal, out var isTemporalAnnotation)
&& isTemporalAnnotation.Value as bool? == true)
{
var historyTableName = annotations.ContainsKey(SqlServerAnnotationNames.TemporalHistoryTableName)
? annotations[SqlServerAnnotationNames.TemporalHistoryTableName].Value as string
: null;
var historyTableSchema = annotations.ContainsKey(SqlServerAnnotationNames.TemporalHistoryTableSchema)
? annotations[SqlServerAnnotationNames.TemporalHistoryTableSchema].Value as string
: null;
// for the RevEng path, we avoid adding period properties to the entity
// because we don't want code for them to be generated - they need to be in shadow state
// so if we don't find property on the entity, we know it's this scenario
// and in that case period column name is actually the same as the period property name annotation
// since in RevEng scenario there can't be custom column mapping
// see #26007
var periodStartPropertyName = entityType.GetPeriodStartPropertyName();
var periodStartProperty = entityType.FindProperty(periodStartPropertyName!);
var periodStartColumnName = periodStartProperty != null
? periodStartProperty[RelationalAnnotationNames.ColumnName] as string
: periodStartPropertyName;
var periodEndPropertyName = entityType.GetPeriodEndPropertyName();
var periodEndProperty = entityType.FindProperty(periodEndPropertyName!);
var periodEndColumnName = periodEndProperty != null
? periodEndProperty[RelationalAnnotationNames.ColumnName] as string
: periodEndPropertyName;
// ttb => ttb.UseHistoryTable("HistoryTable", "schema")
var temporalTableBuilderCalls = new List<MethodCallCodeFragment>();
if (historyTableName != null)
{
temporalTableBuilderCalls.Add(
historyTableSchema != null
? new MethodCallCodeFragment(TemporalTableUseHistoryTableMethodInfo1, historyTableName, historyTableSchema)
: new MethodCallCodeFragment(TemporalTableUseHistoryTableMethodInfo2, historyTableName));
}
// ttb => ttb.HasPeriodStart("Start").HasColumnName("ColumnStart")
temporalTableBuilderCalls.Add(
periodStartColumnName != null
? new MethodCallCodeFragment(TemporalTableHasPeriodStartMethodInfo, periodStartPropertyName)
.Chain(new MethodCallCodeFragment(TemporalPropertyHasColumnNameMethodInfo, periodStartColumnName))
: new MethodCallCodeFragment(TemporalTableHasPeriodStartMethodInfo, periodStartPropertyName));
// ttb => ttb.HasPeriodEnd("End").HasColumnName("ColumnEnd")
temporalTableBuilderCalls.Add(
periodEndColumnName != null
? new MethodCallCodeFragment(TemporalTableHasPeriodEndMethodInfo, periodEndPropertyName)
.Chain(new MethodCallCodeFragment(TemporalPropertyHasColumnNameMethodInfo, periodEndColumnName))
: new MethodCallCodeFragment(TemporalTableHasPeriodEndMethodInfo, periodEndPropertyName));
// ToTable(tb => tb.IsTemporal(ttb => { ... }))
var toTemporalTableCall = new MethodCallCodeFragment(
EntityTypeToTableMethodInfo,
new NestedClosureCodeFragment(
"tb",
new MethodCallCodeFragment(
TableIsTemporalMethodInfo,
new NestedClosureCodeFragment(
"ttb",
temporalTableBuilderCalls))));
fragments.Add(toTemporalTableCall);
annotations.Remove(SqlServerAnnotationNames.IsTemporal);
annotations.Remove(SqlServerAnnotationNames.TemporalHistoryTableName);
annotations.Remove(SqlServerAnnotationNames.TemporalHistoryTableSchema);
annotations.Remove(SqlServerAnnotationNames.TemporalPeriodStartPropertyName);
annotations.Remove(SqlServerAnnotationNames.TemporalPeriodEndPropertyName);
}
return fragments;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override bool IsHandledByConvention(IModel model, IAnnotation annotation)
{
if (annotation.Name == RelationalAnnotationNames.DefaultSchema)
{
return (string?)annotation.Value == "dbo";
}
return annotation.Name == SqlServerAnnotationNames.ValueGenerationStrategy
&& (SqlServerValueGenerationStrategy)annotation.Value! == SqlServerValueGenerationStrategy.IdentityColumn;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override bool IsHandledByConvention(IProperty property, IAnnotation annotation)
{
if (annotation.Name == SqlServerAnnotationNames.ValueGenerationStrategy)
{
return (SqlServerValueGenerationStrategy)annotation.Value! == property.DeclaringType.Model.GetValueGenerationStrategy();
}
return base.IsHandledByConvention(property, annotation);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override MethodCallCodeFragment? GenerateFluentApi(IKey key, IAnnotation annotation)
=> annotation.Name == SqlServerAnnotationNames.Clustered
? (bool)annotation.Value! == false
? new MethodCallCodeFragment(KeyIsClusteredMethodInfo, false)
: new MethodCallCodeFragment(KeyIsClusteredMethodInfo)
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override MethodCallCodeFragment? GenerateFluentApi(IIndex index, IAnnotation annotation)
=> annotation.Name switch
{
SqlServerAnnotationNames.Clustered => (bool)annotation.Value! == false
? new MethodCallCodeFragment(IndexIsClusteredMethodInfo, false)
: new MethodCallCodeFragment(IndexIsClusteredMethodInfo),
SqlServerAnnotationNames.Include => new MethodCallCodeFragment(IndexIncludePropertiesMethodInfo, annotation.Value),
SqlServerAnnotationNames.FillFactor => new MethodCallCodeFragment(IndexHasFillFactorMethodInfo, annotation.Value),
_ => null
};
private static MethodCallCodeFragment? GenerateValueGenerationStrategy(
IDictionary<string, IAnnotation> annotations,
IModel model,
bool onModel)
{
SqlServerValueGenerationStrategy strategy;
if (annotations.TryGetValue(SqlServerAnnotationNames.ValueGenerationStrategy, out var strategyAnnotation)
&& strategyAnnotation.Value != null)
{
annotations.Remove(SqlServerAnnotationNames.ValueGenerationStrategy);
strategy = (SqlServerValueGenerationStrategy)strategyAnnotation.Value;
}
else
{
return null;
}
switch (strategy)
{
case SqlServerValueGenerationStrategy.IdentityColumn:
// Support pre-6.0 IdentitySeed annotations, which contained an int rather than a long
if (annotations.TryGetValue(SqlServerAnnotationNames.IdentitySeed, out var seedAnnotation)
&& seedAnnotation.Value != null)
{
annotations.Remove(SqlServerAnnotationNames.IdentitySeed);
}
else
{
seedAnnotation = model.FindAnnotation(SqlServerAnnotationNames.IdentitySeed);
}
var seed = seedAnnotation is null
? 1L
: seedAnnotation.Value is int intValue
? intValue
: (long?)seedAnnotation.Value ?? 1L;
var increment = GetAndRemove<int?>(annotations, SqlServerAnnotationNames.IdentityIncrement)
?? model.FindAnnotation(SqlServerAnnotationNames.IdentityIncrement)?.Value as int?
?? 1;
return new MethodCallCodeFragment(
onModel ? ModelUseIdentityColumnsMethodInfo : PropertyUseIdentityColumnsMethodInfo,
(seed, increment) switch
{
(1L, 1) => Array.Empty<object>(),
(_, 1) => new object[] { seed },
_ => new object[] { seed, increment }
});
case SqlServerValueGenerationStrategy.SequenceHiLo:
{
var name = GetAndRemove<string>(annotations, SqlServerAnnotationNames.HiLoSequenceName);
var schema = GetAndRemove<string>(annotations, SqlServerAnnotationNames.HiLoSequenceSchema);
return new MethodCallCodeFragment(
onModel ? ModelUseHiLoMethodInfo : PropertyUseHiLoMethodInfo,
(name, schema) switch
{
(null, null) => Array.Empty<object>(),
(_, null) => new object[] { name },
_ => new object[] { name!, schema }
});
}
case SqlServerValueGenerationStrategy.Sequence:
{
var nameOrSuffix = GetAndRemove<string>(
annotations,
onModel ? SqlServerAnnotationNames.SequenceNameSuffix : SqlServerAnnotationNames.SequenceName);
var schema = GetAndRemove<string>(annotations, SqlServerAnnotationNames.SequenceSchema);
return new MethodCallCodeFragment(
onModel ? ModelUseKeySequencesMethodInfo : PropertyUseSequenceMethodInfo,
(name: nameOrSuffix, schema) switch
{
(null, null) => Array.Empty<object>(),
(_, null) => new object[] { nameOrSuffix },
_ => new object[] { nameOrSuffix!, schema }
});
}
case SqlServerValueGenerationStrategy.None:
return new MethodCallCodeFragment(
ModelHasAnnotationMethodInfo,
SqlServerAnnotationNames.ValueGenerationStrategy,
SqlServerValueGenerationStrategy.None);
default:
throw new ArgumentOutOfRangeException();
}
}
private static T? GetAndRemove<T>(IDictionary<string, IAnnotation> annotations, string annotationName)
{
if (annotations.TryGetValue(annotationName, out var annotation)
&& annotation.Value != null)
{
annotations.Remove(annotationName);
return (T)annotation.Value;
}
return default;
}
private static void GenerateSimpleFluentApiCall(
IDictionary<string, IAnnotation> annotations,
string annotationName,
MethodInfo methodInfo,
List<MethodCallCodeFragment> methodCallCodeFragments)
{
if (annotations.TryGetValue(annotationName, out var annotation))
{
annotations.Remove(annotationName);
if (annotation.Value is object annotationValue)
{
methodCallCodeFragments.Add(
new MethodCallCodeFragment(methodInfo, annotationValue));
}
}
}
}