forked from ErikEJ/EFCorePowerTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseEngineerScaffolder.cs
450 lines (400 loc) · 18.5 KB
/
ReverseEngineerScaffolder.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Scaffolding;
using Microsoft.EntityFrameworkCore.Scaffolding.Internal;
using RevEng.Common;
using RevEng.Core.Abstractions;
using RevEng.Core.Abstractions.Metadata;
using RevEng.Core.Abstractions.Model;
using RevEng.Core.Functions;
using RevEng.Core.Procedures;
namespace RevEng.Core
{
public class ReverseEngineerScaffolder : IReverseEngineerScaffolder
{
private readonly IDatabaseModelFactory databaseModelFactory;
private readonly IScaffoldingModelFactory factory;
private readonly ICSharpHelper code;
private readonly IFunctionScaffolder functionScaffolder;
private readonly IFunctionModelFactory functionModelFactory;
private readonly IProcedureScaffolder procedureScaffolder;
private readonly IProcedureModelFactory procedureModelFactory;
public ReverseEngineerScaffolder(
IDatabaseModelFactory databaseModelFactory,
IScaffoldingModelFactory scaffoldingModelFactory,
IFunctionScaffolder functionScaffolder,
IFunctionModelFactory functionModelFactory,
IProcedureScaffolder procedureScaffolder,
IProcedureModelFactory procedureModelFactory,
IModelCodeGeneratorSelector modelCodeGeneratorSelector,
ICSharpHelper cSharpHelper)
{
this.databaseModelFactory = databaseModelFactory;
factory = scaffoldingModelFactory;
code = cSharpHelper;
this.functionScaffolder = functionScaffolder;
this.functionModelFactory = functionModelFactory;
this.procedureScaffolder = procedureScaffolder;
this.procedureModelFactory = procedureModelFactory;
ModelCodeGeneratorSelector = modelCodeGeneratorSelector;
}
private IModelCodeGeneratorSelector ModelCodeGeneratorSelector { get; }
public SavedModelFiles GenerateDbContext(
ReverseEngineerCommandOptions options,
List<string> schemas,
string outputContextDir,
string modelNamespace,
string contextNamespace,
string projectPath,
string outputPath)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
SavedModelFiles filePaths;
var modelOptions = new ModelReverseEngineerOptions
{
UseDatabaseNames = options.UseDatabaseNames,
#if CORE60
NoPluralize = !options.UseInflector,
#endif
};
var codeOptions = new ModelCodeGenerationOptions
{
UseDataAnnotations = !options.UseFluentApiOnly,
Language = "C#",
ContextName = code.Identifier(options.ContextClassName),
ContextDir = outputContextDir,
RootNamespace = null,
ContextNamespace = contextNamespace,
ModelNamespace = modelNamespace,
SuppressConnectionStringWarning = false,
ConnectionString = options.ConnectionString,
#if CORE60
SuppressOnConfiguring = !options.IncludeConnectionString,
#endif
#if CORE60
UseNullableReferenceTypes = options.UseNullableReferences,
#endif
#if CORE70
ProjectDir = options.UseT4 ? projectPath : null,
#endif
};
var dbOptions = new DatabaseModelFactoryOptions(options.Tables.Where(t => t.ObjectType.HasColumns()).Select(m => m.Name), schemas);
var scaffoldedModel = ScaffoldModel(
options.Dacpac ?? options.ConnectionString,
dbOptions,
modelOptions,
codeOptions,
options.UseBoolPropertiesWithoutDefaultSql,
options.SelectedToBeGenerated == 1, // DbContext only
options.SelectedToBeGenerated == 2, // Entities only
options.UseSchemaFolders);
filePaths = Save(
scaffoldedModel,
Path.GetFullPath(Path.Combine(options.ProjectPath, outputPath ?? string.Empty)));
return filePaths;
}
public SavedModelFiles GenerateFunctions(
ReverseEngineerCommandOptions options,
ref List<string> errors,
string outputContextDir,
string modelNamespace,
string contextNamespace,
bool supportsFunctions)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var functionModelScaffolder = functionScaffolder;
if (functionModelScaffolder != null
&& supportsFunctions
&& (options.Tables.Any(t => t.ObjectType == ObjectType.ScalarFunction)
|| !options.Tables.Any()))
{
var modelFactoryOptions = new ModuleModelFactoryOptions
{
FullModel = true,
Modules = options.Tables.Where(t => t.ObjectType == ObjectType.ScalarFunction).Select(m => m.Name),
};
var functionModel = functionModelFactory.Create(options.Dacpac ?? options.ConnectionString, modelFactoryOptions);
ApplyRenamers(functionModel.Routines, options.CustomReplacers);
var functionOptions = new ModuleScaffolderOptions
{
ContextDir = outputContextDir,
ContextName = options.ContextClassName,
ContextNamespace = contextNamespace,
ModelNamespace = modelNamespace,
NullableReferences = options.UseNullableReferences,
UseAsyncCalls = options.UseAsyncCalls,
};
var functionScaffoldedModel = functionModelScaffolder.ScaffoldModel(functionModel, functionOptions, ref errors);
if (functionScaffoldedModel != null)
{
return functionModelScaffolder.Save(
functionScaffoldedModel,
Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputPath ?? string.Empty)),
contextNamespace,
options.UseAsyncCalls);
}
}
return null;
}
public SavedModelFiles GenerateStoredProcedures(
ReverseEngineerCommandOptions options,
ref List<string> errors,
string outputContextDir,
string modelNamespace,
string contextNamespace,
bool supportsProcedures)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var procedureModelScaffolder = procedureModelFactory;
if (procedureModelScaffolder != null
&& supportsProcedures
&& (options.Tables.Any(t => t.ObjectType == ObjectType.Procedure)
|| !options.Tables.Any()))
{
var procedureModelFactoryOptions = new ModuleModelFactoryOptions
{
DiscoverMultipleResultSets = options.UseMultipleSprocResultSets,
UseLegacyResultSetDiscovery = options.UseLegacyResultSetDiscovery && !options.UseMultipleSprocResultSets,
UseDateOnlyTimeOnly = options.UseDateOnlyTimeOnly,
FullModel = true,
Modules = options.Tables.Where(t => t.ObjectType == ObjectType.Procedure).Select(m => m.Name),
ModulesUsingLegacyDiscovery = options.Tables
.Where(t => t.ObjectType == ObjectType.Procedure && t.UseLegacyResultSetDiscovery)
.Select(m => m.Name),
MappedModules = options.Tables
.Where(t => t.ObjectType == ObjectType.Procedure && !string.IsNullOrEmpty(t.MappedType))
.Select(m => new { m.Name, m.MappedType })
.ToDictionary(m => m.Name, m => m.MappedType),
};
var procedureModel = procedureModelFactory.Create(options.Dacpac ?? options.ConnectionString, procedureModelFactoryOptions);
ApplyRenamers(procedureModel.Routines, options.CustomReplacers);
var procedureOptions = new ModuleScaffolderOptions
{
ContextDir = outputContextDir,
ContextName = options.ContextClassName,
ContextNamespace = contextNamespace,
ModelNamespace = modelNamespace,
NullableReferences = options.UseNullableReferences,
UseSchemaFolders = options.UseSchemaFolders,
UseAsyncCalls = options.UseAsyncCalls,
};
var procedureScaffoldedModel = procedureScaffolder.ScaffoldModel(procedureModel, procedureOptions, ref errors);
if (procedureScaffoldedModel != null)
{
return procedureScaffolder.Save(
procedureScaffoldedModel,
Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputPath ?? string.Empty)),
contextNamespace,
options.UseAsyncCalls);
}
}
return null;
}
private static SavedModelFiles Save(
ScaffoldedModel scaffoldedModel,
string outputDir)
{
Directory.CreateDirectory(outputDir);
var contextPath = string.Empty;
if (scaffoldedModel.ContextFile != null)
{
contextPath = Path.GetFullPath(Path.Combine(outputDir, scaffoldedModel.ContextFile!.Path));
Directory.CreateDirectory(Path.GetDirectoryName(contextPath)!);
File.WriteAllText(contextPath, scaffoldedModel.ContextFile.Code, Encoding.UTF8);
}
var additionalFiles = new List<string>();
foreach (var entityTypeFile in scaffoldedModel.AdditionalFiles)
{
var additionalFilePath = Path.Combine(outputDir, entityTypeFile.Path);
if (additionalFilePath != null)
{
var path = Path.GetDirectoryName(additionalFilePath);
if (path != null)
{
Directory.CreateDirectory(path);
File.WriteAllText(additionalFilePath, entityTypeFile.Code, Encoding.UTF8);
additionalFiles.Add(additionalFilePath);
}
}
}
return new SavedModelFiles(contextPath, additionalFiles);
}
private static void ApplyRenamers(IEnumerable<SqlObjectBase> sqlObjects, List<Schema> renamers)
{
if (renamers == null || !renamers.Any())
{
return;
}
foreach (var sqlObject in sqlObjects)
{
var schema = renamers
.FirstOrDefault(x => x.SchemaName == sqlObject.Schema);
if (schema != null)
{
if (schema.Tables != null && schema.Tables.Any(t => t.Name == sqlObject.Name))
{
sqlObject.NewName = schema.Tables.SingleOrDefault(t => t.Name == sqlObject.Name)?.NewName;
}
else if (!string.IsNullOrEmpty(schema.TableRegexPattern) && schema.TablePatternReplaceWith != null)
{
sqlObject.NewName = RegexNameReplace(schema.TableRegexPattern, sqlObject.Name, schema.TablePatternReplaceWith);
}
}
}
}
private static string RegexNameReplace(string pattern, string originalName, string replacement, int timeout = 100)
{
string newName = string.Empty;
try
{
newName = Regex.Replace(originalName, pattern, replacement, RegexOptions.None, TimeSpan.FromMilliseconds(timeout));
}
catch (RegexMatchTimeoutException)
{
Console.WriteLine($"Regex pattern {pattern} time out when trying to match {originalName}, name won't be replaced");
}
return newName;
}
private static void AppendSchemaFoldersAndNamespace(IModel databaseModel, ScaffoldedModel scaffoldedModel, bool useSchemaFolders, IEnumerable<string> schemas)
{
// Tables and views only
if (!useSchemaFolders)
{
return;
}
scaffoldedModel.ContextFile.Code = AppendSchemaNamespace(string.Empty, scaffoldedModel.ContextFile.Code, schemas);
foreach (var entityType in scaffoldedModel.AdditionalFiles)
{
var entityTypeName = Path.GetFileNameWithoutExtension(entityType.Path);
var entityTypeExtension = Path.GetExtension(entityType.Path);
var entityMatch = databaseModel.GetEntityTypes().FirstOrDefault(x => x.Name == entityTypeName);
var entityTypeSchema = entityMatch?.GetSchema();
#if CORE60
if (entityMatch?.GetViewName() != null)
{
entityTypeSchema = entityMatch?.GetViewSchema();
}
#endif
if (!string.IsNullOrEmpty(entityTypeSchema))
{
entityType.Path = Path.Combine(entityTypeSchema, entityTypeName + entityTypeExtension);
entityType.Code = AppendSchemaNamespace(entityTypeSchema, entityType.Code, schemas);
}
}
}
private static string AppendSchemaNamespace(string entityTypeSchema, string code, IEnumerable<string> schemas)
{
var nameSpaceSuffix = "Ns";
var entityTypeSchemaWithSuffix = entityTypeSchema + nameSpaceSuffix;
var namespaceKeyWord = "namespace ";
var usingKeyWord = "using ";
var codeLines = code.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);
var originalNameSpaceLine = codeLines.Where(l => l.StartsWith(namespaceKeyWord)).Single();
var newNameSpaceLine = originalNameSpaceLine;
var cSharp10NameSpaceStyle = newNameSpaceLine.EndsWith(";");
if (cSharp10NameSpaceStyle) { newNameSpaceLine = newNameSpaceLine.Substring(0, newNameSpaceLine.Length - 1); }
var originalLastUsing = codeLines.Where(l => l.StartsWith(usingKeyWord)).Last();
var regexStartsWithNameSpace = new Regex(Regex.Escape(namespaceKeyWord));
var newUsings = new StringBuilder(originalLastUsing);
newUsings.AppendLine();
foreach (var schema in schemas.Where(s => s != entityTypeSchemaWithSuffix))
{
var newUsing = regexStartsWithNameSpace.Replace(newNameSpaceLine, usingKeyWord, 1);
newUsings.Append(newUsing);
newUsings.Append('.');
newUsings.Append(schema);
newUsings.Append(nameSpaceSuffix);
newUsings.AppendLine(";");
}
newNameSpaceLine = newNameSpaceLine + $".{entityTypeSchemaWithSuffix}";
if (cSharp10NameSpaceStyle) { newNameSpaceLine += ";"; }
var sb = new StringBuilder();
foreach (var codeLine in codeLines)
{
if (codeLine.Equals(originalNameSpaceLine) && !string.IsNullOrEmpty(entityTypeSchema))
{
sb.AppendLine(newNameSpaceLine);
}
else if (codeLine.Equals(originalLastUsing))
{
sb.AppendLine(newUsings.ToString());
}
else
{
sb.AppendLine(codeLine);
}
}
return sb.ToString();
}
private ScaffoldedModel ScaffoldModel(
string connectionString,
DatabaseModelFactoryOptions databaseOptions,
ModelReverseEngineerOptions modelOptions,
ModelCodeGenerationOptions codeOptions,
bool removeNullableBoolDefaults,
bool dbContextOnly,
bool entitiesOnly,
bool useSchemaFolders)
{
var databaseModel = databaseModelFactory.Create(connectionString, databaseOptions);
if (removeNullableBoolDefaults)
{
foreach (var column in databaseModel.Tables
.SelectMany(table => table.Columns
.Where(column => ((column.StoreType == "bit" || column.StoreType == "boolean")
&& !column.IsNullable
&& !string.IsNullOrEmpty(column.DefaultValueSql))
||
// Oracle
(column.StoreType == "NUMBER(1)" && !column.IsNullable
&& !string.IsNullOrEmpty(column.DefaultValueSql)
&& (column.DefaultValueSql?.Trim() == "1" || column.DefaultValueSql?.Trim() == "0")))))
{
column.DefaultValueSql = null;
}
}
#if CORE60
var model = factory.Create(databaseModel, modelOptions);
#else
var model = factory.Create(databaseModel, modelOptions.UseDatabaseNames);
#endif
if (model == null)
{
throw new InvalidOperationException($"No model from provider {factory.GetType().ShortDisplayName()}");
}
#if CORE70
var codeGenerator = ModelCodeGeneratorSelector.Select(codeOptions);
#else
var codeGenerator = ModelCodeGeneratorSelector.Select(codeOptions.Language);
#endif
var codeModel = codeGenerator.GenerateModel(model, codeOptions);
if (entitiesOnly)
{
codeModel.ContextFile = null!;
}
if (dbContextOnly)
{
codeModel.AdditionalFiles.Clear();
}
AppendSchemaFoldersAndNamespace(model, codeModel, useSchemaFolders, databaseModel.Tables.Select(t => t.Schema).Distinct());
return codeModel;
}
}
}