-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimplePocos.cs
528 lines (465 loc) · 22.7 KB
/
SimplePocos.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
using CodegenCS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using static CodegenCS.Symbols;
using static InterpolatedColorConsole.Symbols;
using System.CommandLine.Binding;
using System.CommandLine;
using CodegenCS.Utils;
using CodegenCS.Models.DbSchema;
using CodegenCS.Runtime;
/// <summary>
/// SimplePocos.cs: Given a Database Schema will Generate simple POCOs (just classes and properties, no relationships)
///
/// Usage: dotnet-codegencs template run SimplePocos.cs <DbSchema.json> <Namespace> [--SingleFile] [-t <true/false>] [-k <true/false>] [-db <true/false>] [-eq <true/false>]
/// e.g.: dotnet-codegencs template run SimplePocos.cs AdventureWorksSchema.json MyPOCOs -db false
///
/// Arguments:
/// <Namespace> Namespace of generated POCOs
///
/// Options:
/// --SingleFile If set all POCOs will be generated under a single filename
/// (default output file)
/// -t, --AddTableAttribute If true will add [Table] attributes to POCOs. [default: True]
/// -k, --AddKeyAttribute If true will add [Key] attributes to primary-key columns.
/// This is required by FastCRUD and Entity Framework [default: True]
/// -db, --AddDatabaseGeneratedAttribute If true will add [DatabaseGenerated] attributes to identity
/// and computed columns.
/// This is required by FastCRUD and Entity Framework [default: True]
/// -eq, --GenerateEqualsHashCode If true POCOs will have override Equals/GetHashCode and
/// equality/inequality operators (== and !=) [default: True]
/// </summary>
public class SimplePOCOGenerator : ICodegenMultifileTemplate<DatabaseSchema>
{
private ICodegenContext _generatorContext;
private ILogger _logger;
private bool _allTablesInSameSchema;
private bool _duplicatedTableNames;
private Dictionary<Table, Dictionary<string, string>> _tablePropertyNames { get; set; } = new Dictionary<Table, Dictionary<string, string>>();
private SimplePOCOGeneratorOptions _options;
public SimplePOCOGenerator(ILogger logger, SimplePOCOGeneratorOptions options)
{
_logger = logger;
_options = options;
}
public static void ConfigureCommand(Command command)
{
command.AddArgument(new Argument<string>("Namespace", "Namespace of generated POCOs") { Arity = ArgumentArity.ExactlyOne });
command.AddOption(new Option<bool>("-p:SingleFile") { Description = "If defined, all POCOs will be generated under a single filename (default output file)" });
command.AddOption(new Option<bool>("-p:AddTableAttribute", getDefaultValue: () => true) { Description = "If true will add [Table] attributes to POCOs." });
command.AddOption(new Option<bool>("-p:AddKeyAttribute", getDefaultValue: () => true) { Description = "If true will add [Key] attributes to primary-key columns.\nThis is required by FastCRUD and Entity Framework" });
command.AddOption(new Option<bool>("-p:AddDatabaseGeneratedAttribute", getDefaultValue: () => true) { Description = "If true will add [DatabaseGenerated] attributes to identity and computed columns.\nThis is required by FastCRUD and Entity Framework" });
command.AddOption(new Option<bool>("-p:GenerateEqualsHashCode", getDefaultValue: () => true) { Description = "If true POCOs will have override Equals/GetHashCode and equality/inequality operators (== and !=)" });
}
#region SimplePOCOGeneratorOptions
public class SimplePOCOGeneratorOptions : IAutoBindCommandLineArgs
{
/// <summary>
/// Namespace of generated POCOs
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// If set all POCOs will be generated under a single filename (default output file)
/// </summary>
public bool SingleFile { get; set; } = false;
/// <summary>
/// If true (default is true) will add [Table] attributes to POCOs.
/// </summary>
public bool AddTableAttribute { get; set; } = true;
/// <summary>
/// If true (default is true) will add [Key] attributes to primary-key columns.
/// This is required by FastCRUD and Entity Framework
/// </summary>
public bool AddKeyAttribute { get; set; } = true;
/// <summary>
/// If true (default is true) will add [DatabaseGenerated] attributes to identity and computed columns.
/// This is required by FastCRUD and Entity Framework
/// </summary>
public bool AddDatabaseGeneratedAttribute { get; set; } = true;
/// <summary>
/// If true (default is true) POCOs will have override Equals/GetHashCode and equality/inequality operators (== and !=)
/// </summary>
public bool GenerateEqualsHashCode { get; set; } = true;
}
#endregion /SimplePOCOGeneratorOptions
public void Render(ICodegenContext context, DatabaseSchema schema)
{
_generatorContext = context;
_allTablesInSameSchema = schema.Tables.Select(t => t.TableSchema).Distinct().Count() == 1;
_duplicatedTableNames = schema.Tables.Select(t => t.TableName).GroupBy(name => name).Where(g => g.Count() > 1).Any();
if (_duplicatedTableNames)
_logger.WriteLineAsync(ConsoleColor.Yellow, $"Warning: There are tables with same name (in different schemas?), class names will contain schema...");
GeneratePOCOs(schema);
}
/// <summary>
/// Generates POCOS
/// </summary>
public void GeneratePOCOs(DatabaseSchema schema)
{
var tablesAndViews = schema.Tables
.Where(t => ShouldProcessTable(t))
.OrderBy(t => GetClassNameForTable(t));
if (_options.SingleFile)
{
var singleFile = _generatorContext.DefaultOutputFile;
singleFile.WriteLine($$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by dotnet-codegencs tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace {{_options.Namespace}}
{
{{tablesAndViews.Render(table => GeneratePOCO(singleFile, table))}}
}
""");
}
else
{
foreach (var table in tablesAndViews)
{
var pocoFile = _generatorContext[GetFileNameForTable(table)];
GeneratePOCO(pocoFile, table);
}
}
}
private void GeneratePOCO(ICodegenOutputFile file, Table table)
{
if (!_options.SingleFile)
{
_logger.WriteLineAsync($"Generating POCO for {ConsoleColor.Yellow}'{table.TableName}'{PREVIOUS_COLOR}...");
file.WriteLine($$"""
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by dotnet-codegencs tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace {{_options.Namespace}}
{
{{() => GeneratePOCOClass(file, table)}}
}
""");
}
else
{
_logger.WriteLineAsync($"Generating POCO for {ConsoleColor.Yellow}{table.TableName} ('{file.RelativePath}'){PREVIOUS_COLOR}...");
file.WriteLine($$"""{{() => GeneratePOCOClass(file, table)}}""");
}
}
private void GeneratePOCOClass(ICodegenOutputFile file, Table table)
{
string entityClassName = GetClassNameForTable(table);
if (_options.AddTableAttribute)
{
// We'll decorate [Table("Name")] only if schema not default or if table name doesn't match entity name
if (table.TableSchema != "dbo") //TODO or table different than clas name?
file.WriteLine($"[Table(\"{table.TableName}\", Schema = \"{table.TableSchema}\")]");
else if (entityClassName.ToLower() != table.TableName.ToLower())
file.WriteLine($"[Table(\"{table.TableName}\")]");
}
List<string> baseClasses = new List<string>();
var columns = table.Columns
.Where(c => ShouldProcessColumn(table, c))
.OrderBy(c => c.IsPrimaryKeyMember ? 0 : 1)
.ThenBy(c => c.IsPrimaryKeyMember ? c.OrdinalPosition : 0) // respect PK order...
.ThenBy(c => GetPropertyNameForDatabaseColumn(table, c.ColumnName)); // but for other columns do alphabetically;
file.WithCBlock($"public partial class {entityClassName}{(baseClasses.Any() ? " : " + string.Join(", ", baseClasses) : "")}", () =>
{
file.WriteLine($$"""
#region Members
{{columns.Render(column => GenerateProperty(file, table, column))}}
#endregion Members
""");
if (_options.GenerateEqualsHashCode)
{
file.WriteLine($$"""
#region Equals/GetHashCode
{{GenerateEquals(table)}}
{{GenerateGetHashCode(table)}}
{{GenerateInequalityOperatorOverloads(table)}}
#endregion Equals/GetHashCode
""");
}
});
}
private void GenerateProperty(ICodegenOutputFile writer, Table table, Column column)
{
string propertyName = GetPropertyNameForDatabaseColumn(table, column.ColumnName);
string privateVariable = $"_{propertyName.Substring(0, 1).ToLower()}{propertyName.Substring(1)}";
if (column.IsPrimaryKeyMember && _options.AddKeyAttribute)
writer.WriteLine("[Key]");
if (column.IsIdentity && _options.AddDatabaseGeneratedAttribute)
writer.WriteLine("[DatabaseGenerated(DatabaseGeneratedOption.Identity)]");
else if (column.IsComputed && _options.AddDatabaseGeneratedAttribute)
writer.WriteLine("[DatabaseGenerated(DatabaseGeneratedOption.Computed)]");
// We'll decorate [Column("Name")] only if column name doesn't match property name
if (propertyName.ToLower() != column.ColumnName.ToLower())
writer.WriteLine($"[Column(\"{column.ColumnName}\")]");
writer.Write($"public {GetTypeDefinitionForDatabaseColumn(table, column) ?? ""} {propertyName} {{ get; set; }}");
}
private FormattableString GenerateEquals(Table table)
{
//TODO: GenerateIEquatable, which is a little faster for Generic collections - and our Equals(object other) can reuse this IEquatable<T>.Equals(T other)
string entityClassName = GetClassNameForTable(table);
var cols = table.Columns
.Where(c => ShouldProcessColumn(table, c))
.Where(c => !c.IsIdentity)
.OrderBy(c => GetPropertyNameForDatabaseColumn(table, c.ColumnName))
.Select(c => new { ColumnName = c.ColumnName, PropertyName = GetPropertyNameForDatabaseColumn(table, c.ColumnName) });
return $$"""
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
{{entityClassName}} other = obj as {{entityClassName}};
if (other == null) return false;
{{cols.Select(col => $$"""
if ({{col.PropertyName}} != other.{{col.PropertyName}})
return false;
""").Render(RenderEnumerableOptions.LineBreaksWithoutSpacer)}}
return true;
}
""";
}
private FormattableString GenerateGetHashCode(Table table)
{
var cols = table.Columns
.Where(c => ShouldProcessColumn(table, c))
.Where(c => !c.IsIdentity)
.OrderBy(c => GetPropertyNameForDatabaseColumn(table, c.ColumnName))
.Select(c => new { ColumnName = c.ColumnName, PropertyName = GetPropertyNameForDatabaseColumn(table, c.ColumnName), DefaultTypeValue = GetDefaultValue(GetTypeForDatabaseColumn(table, c)) });
//TODO: for dotnetcore we can use HashCode.Combine(field1, field2, field3)
return $$"""
public override int GetHashCode()
{
unchecked
{
int hash = 17;
{{cols.Select(col => $$"""hash = hash * 23 + ({{col.PropertyName}} == {{col.DefaultTypeValue}} ? 0 : {{col.PropertyName}}.GetHashCode());""")}}
return hash;
}
}
""";
}
private FormattableString GenerateInequalityOperatorOverloads(Table table)
{
string entityClassName = GetClassNameForTable(table);
return $$"""
public static bool operator ==({{entityClassName}} left, {{entityClassName}} right)
{
return Equals(left, right);
}
public static bool operator !=({{entityClassName}} left, {{entityClassName}} right)
{
return !Equals(left, right);
}
""";
}
private string GetFileNameForTable(Table table)
{
//return $"{table.TableName}.generated.cs";
// if all tables are under single schema or if it's default schema - just omit the schema:
if (_allTablesInSameSchema || table.TableSchema == "dbo")
return $"{table.TableName}.generated.cs";
else
return $"{table.TableSchema}.{table.TableName}.generated.cs";
}
private string GetClassNameForTable(Table table)
{
// if there are tables under multiple schemas and yet they have identical names - then each class should have unique name:
if (!_allTablesInSameSchema && _duplicatedTableNames)
return $"{table.TableSchema}_{table.TableName}";
else
return $"{table.TableName}";
}
private bool ShouldProcessTable(Table table)
{
if (table.TableType == "VIEW")
return false;
return true;
}
private bool ShouldProcessColumn(Table table, Column column)
{
string sqlDataType = column.SqlDataType;
switch (sqlDataType)
{
case "hierarchyid":
case "geography":
return false;
default:
break;
}
return true;
}
private static Dictionary<Type, string> _typeAlias = new Dictionary<Type, string>
{
{ typeof(bool), "bool" },
{ typeof(byte), "byte" },
{ typeof(char), "char" },
{ typeof(decimal), "decimal" },
{ typeof(double), "double" },
{ typeof(float), "float" },
{ typeof(int), "int" },
{ typeof(long), "long" },
{ typeof(object), "object" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(string), "string" },
{ typeof(uint), "uint" },
{ typeof(ulong), "ulong" },
// Yes, this is an odd one. Technically it's a type though.
{ typeof(void), "void" }
};
private Type GetTypeForDatabaseColumn(Table table, Column column)
{
System.Type type;
try
{
type = Type.GetType(column.ClrType);
}
catch (Exception ex)
{
return null; // ignore vendor specific types that DbSchema doesn't recognize
}
bool isNullable = column.IsNullable;
// Some developers use POCO instances with null Primary Key to represent a new (in-memory) object, so they prefer to set POCO PKs as Nullable
//if (column.IsPrimaryKeyMember)
// isNullable = true;
// reference types (basically only strings?) are nullable by default are nullable, no need to make it explicit
if (!type.IsValueType)
isNullable = false;
if (isNullable)
return typeof(Nullable<>).MakeGenericType(type);
return type;
}
private string GetTypeDefinitionForDatabaseColumn(Table table, Column column)
{
//if (column == null)
// return null; // IF/IIF symbols will evaluate both TRUE and FALSE statements, but this won't get rendered
Type type = GetTypeForDatabaseColumn(table, column);
if (type == null)
return "?!";
// unwrap nullable types
bool isNullable = false;
Type underlyingType = Nullable.GetUnderlyingType(type) ?? type;
if (underlyingType != type)
isNullable = true;
string typeName = underlyingType.Name;
// Let's use short type names (int instead of Int32, long instead of Int64, string instead of String, etc)
if (_typeAlias.TryGetValue(underlyingType, out string alias))
typeName = alias;
if (!isNullable)
return typeName;
return $"{typeName}?"; // some might prefer $"System.Nullable<{typeName}>"
}
private static string GetDefaultValue(Type type)
{
// all reference-types default to null
if (type == null || !type.IsValueType)
return "null";
// all nullables default to null
if (Nullable.GetUnderlyingType(type) != null)
return "null";
// Maybe we should replace by 0, DateTime.MinValue, Guid.Empty, etc?
string typeName = type.Name;
// Let's use short type names (int instead of Int32, long instead of Int64, string instead of String, etc)
if (_typeAlias.TryGetValue(type, out string alias))
typeName = alias;
return $"default({typeName})";
}
// From PetaPoco - https://github.com/CollaboratingPlatypus/PetaPoco/blob/development/T4Templates/PetaPoco.Core.ttinclude
private static Regex rxCleanUp = new Regex(@"[^\w\d_]", RegexOptions.Compiled);
private static string[] cs_keywords = { "abstract", "event", "new", "struct", "as", "explicit", "null",
"switch", "base", "extern", "object", "this", "bool", "false", "operator", "throw",
"break", "finally", "out", "true", "byte", "fixed", "override", "try", "case", "float",
"params", "typeof", "catch", "for", "private", "uint", "char", "foreach", "protected",
"ulong", "checked", "goto", "public", "unchecked", "class", "if", "readonly", "unsafe",
"const", "implicit", "ref", "ushort", "continue", "in", "return", "using", "decimal",
"int", "sbyte", "virtual", "default", "interface", "sealed", "volatile", "delegate",
"internal", "short", "void", "do", "is", "sizeof", "while", "double", "lock",
"stackalloc", "else", "long", "static", "enum", "namespace", "string" };
/// <summary>
/// Gets a unique identifier name for the column, which doesn't conflict with the POCO class itself or with previous identifiers for this POCO.
/// </summary>
/// <param name="table"></param>
/// <param name="column"></param>
/// <param name="previouslyUsedIdentifiers"></param>
/// <returns></returns>
string GetPropertyNameForDatabaseColumn(Table table, string columnName)
{
if (columnName == null)
return null;
if (_tablePropertyNames.ContainsKey(table) && _tablePropertyNames[table].ContainsKey(columnName))
return _tablePropertyNames[table][columnName];
string name = columnName;
// Replace forbidden characters
name = rxCleanUp.Replace(name, "_");
// Split multiple words
var parts = splitUpperCase.Split(name).Where(part => part != "_" && part != "-").ToList();
// we'll put first word into TitleCase except if it's a single-char in lowercase (like vNameOfTable) which we assume is a prefix (like v for views) and should be preserved as is
// if first world is a single-char in lowercase (like vNameOfTable) which we assume is a prefix (like v for views) and should be preserved as is
// Recapitalize (to TitleCase) all words
for (int i = 0; i < parts.Count; i++)
{
// if first world is a single-char in lowercase (like vNameOfTable), we assume it's a prefix (like v for views) and should be preserved as is
if (i == 0 && parts[i].Length == 1 && parts[i].ToLower() != parts[i])
continue;
switch (parts[i])
{
//case "ID": // don't convert "ID" for "Id"
// break;
default:
parts[i] = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(parts[i].ToLower());
break;
}
}
name = string.Join("", parts);
// can't start with digit
if (char.IsDigit(name[0]))
name = "_" + name;
// can't be a reserved keyword
if (cs_keywords.Contains(name))
name = "@" + name;
// check for name clashes
if (!_tablePropertyNames.ContainsKey(table))
_tablePropertyNames[table] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
int n = 0;
string attemptName = name;
while ((GetClassNameForTable(table) == attemptName || _tablePropertyNames[table].ContainsValue((attemptName))) && n < 100)
{
n++;
attemptName = name + n.ToString();
}
_tablePropertyNames[table].Add(columnName, attemptName);
return attemptName;
}
// Splits both camelCaseWords and also TitleCaseWords. Underscores and dashes are also splitted. Uppercase acronyms are also splitted.
// E.g. "BusinessEntityID" becomes ["Business","Entity","ID"]
// E.g. "Employee_SSN" becomes ["employee","_","SSN"]
private static Regex splitUpperCase = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z0-9]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z0-9])(?=[^A-Za-z0-9])", RegexOptions.IgnorePatternWhitespace);
}