-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathTableMapping.cs
473 lines (437 loc) · 19.5 KB
/
TableMapping.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Ceen.Database
{
/// <summary>
/// The auto-generate action
/// </summary>
public enum AutoGenerateAction
{
/// <summary>No auto generation</summary>
None,
/// <summary>Database creates a unique ID</summary>
DatabaseAutoID,
/// <summary>Database assigns a "created" timestamp</summary>
DatabaseCreateTimestamp,
/// <summary>Database assigns a "change" timestamp</summary>
DatabaseChangeTimestamp,
/// <summary>Client creates a unique ID</summary>
ClientGenerateGuid,
/// <summary>Client assigns a "created" timestamp</summary>
ClientCreateTimestamp,
/// <summary>client assigns a "change" timestamp</summary>
ClientChangeTimestamp
}
/// <summary>
/// Represents the mapping for a table
/// </summary>
public class TableMapping
{
/// <summary>
/// The name of the table in SQL format
/// </summary>
public readonly string Name;
/// <summary>
/// The name of the table in quotes for SQL
/// </summary>
public readonly string QuotedTableName;
/// <summary>
/// The type being mapped
/// </summary>
public readonly Type Type;
/// <summary>
/// The database dialect
/// </summary>
public readonly IDatabaseDialect Dialect;
/// <summary>
/// A value indicating if the primary key is generated by the database
/// </summary>
public readonly bool IsPrimaryKeyAutogenerated;
/// <summary>
/// A value indicating if the change timestamp is generated by the database
/// </summary>
public readonly bool HasDatabaseGeneratedChangeTimestamp;
/// <summary>
/// A value indicating if the create timestamp is generated by the database
/// </summary>
public readonly bool HasDatabaseGeneratedCreateTimestamp;
/// <summary>
/// All the columns, where the key is the property name
/// </summary>
public readonly Dictionary<string, ColumnMapping> AllColumnsByMemberName;
/// <summary>
/// All the columns, where the key is the sql column name
/// </summary>
public readonly Dictionary<string, ColumnMapping> AllColumnsBySqlName;
/// <summary>
/// All the columns, where the value is generated by the client
/// </summary>
public readonly HashSet<ColumnMapping> ClientGenerated;
/// <summary>
/// All the columns, where the value is generated by the database
/// </summary>
public readonly HashSet<ColumnMapping> DatabaseGenerated;
/// <summary>
/// All the columns for the table
/// </summary>
public readonly ColumnMapping[] AllColumns;
/// <summary>
/// The columns that should be used when inserting a row
/// </summary>
public readonly ColumnMapping[] InsertColumns;
/// <summary>
/// The columns that should be used when updating a row
/// </summary>
public readonly ColumnMapping[] UpdateColumns;
/// <summary>
/// All columns that are not the primary key
/// </summary>
public readonly ColumnMapping[] ColumnsWithoutPrimaryKey;
/// <summary>
/// All columns that are primary keys
/// </summary>
public readonly ColumnMapping[] PrimaryKeys;
/// <summary>
/// The unique mappings
/// </summary>
public readonly UniqueMapping[] Uniques;
/// <summary>
/// The rules for validating table items prior to insert or update
/// </summary>
public readonly ValidationBaseAttribute[] ValidationRules;
/// <summary>
/// All the columns with validation rule(s) attached
/// </summary>
public readonly ColumnMapping[] AllColumnsWithValidationRules;
/// <summary>
/// Flag used to bypass validation code if it does not do anything
/// </summary>
public readonly bool HasValidationRules;
/// <summary>
/// Initializes a new instance of the <see cref="T:Ceen.Database.TableMapping"/> class.
/// </summary>
/// <param name="dialect">The database dialect.</param>
/// <param name="type">The type to mape.</param>
/// <param name="nameoverride">An optional name override for the table name</param>
/// <param name="ignorefields">An optional flag that removes all fields from the map</param>
public TableMapping(IDatabaseDialect dialect, Type type, string nameoverride = null, bool ignoreFields = false)
{
Dialect = dialect ?? throw new ArgumentNullException(nameof(dialect));
Type = type;
Name = nameoverride ?? dialect.GetName(type);
QuotedTableName = dialect.QuoteName(Name);
AllColumns = type
.GetProperties()
.Where(x => !x.GetCustomAttributes<IgnoreAttribute>(true).Any())
.Select(x => new ColumnMapping(dialect, x))
.Concat(
type
.GetFields()
.Where(x => !x.GetCustomAttributes<IgnoreAttribute>(true).Any() && !ignoreFields)
.Select(x => new ColumnMapping(dialect, x))
)
.ToArray();
var dbcreated = new[] { AutoGenerateAction.DatabaseAutoID, AutoGenerateAction.DatabaseChangeTimestamp, AutoGenerateAction.DatabaseCreateTimestamp };
InsertColumns = AllColumns.Where(x => !dbcreated.Contains(x.AutoGenerateAction)).ToArray();
ColumnsWithoutPrimaryKey = AllColumns.Where(x => !x.IsPrimaryKey).ToArray();
UpdateColumns = ColumnsWithoutPrimaryKey.Where(x => !dbcreated.Contains(x.AutoGenerateAction)).ToArray();
PrimaryKeys = AllColumns.Where(x => x.IsPrimaryKey).ToArray();
AllColumnsBySqlName = AllColumns.ToDictionary(x => x.ColumnName, x => x);
AllColumnsByMemberName = AllColumns.ToDictionary(x => x.Member.Name, x => x);
// Build the unique maps
var uniques = AllColumns
.Select(x => new Tuple<ColumnMapping, string[]>(x, x.Member.GetCustomAttributes<UniqueAttribute>().Select(y => y.Group).ToArray()))
.Where(x => x.Item2 != null && x.Item2.Length > 0);
var solos = uniques.Where(x => x.Item2.Contains(null));
var groups = uniques
.SelectMany(x =>
x.Item2
.Where(y => y != null)
.Select(y => new KeyValuePair<string, ColumnMapping>(y, x.Item1))
)
.GroupBy(x => x.Key);
Uniques =
solos
.Select(x => new UniqueMapping(null, new ColumnMapping[] { x.Item1 }))
.Concat(
groups.Select(x => new UniqueMapping(x.Key, x.Select(y => y.Value).ToArray()))
).ToArray();
ClientGenerated = new HashSet<ColumnMapping>(AllColumns
.Where(x =>
x.AutoGenerateAction == AutoGenerateAction.ClientGenerateGuid
|| x.AutoGenerateAction == AutoGenerateAction.ClientChangeTimestamp
|| x.AutoGenerateAction == AutoGenerateAction.ClientCreateTimestamp
)
);
DatabaseGenerated = new HashSet<ColumnMapping>(AllColumns
.Where(x =>
x.AutoGenerateAction == AutoGenerateAction.DatabaseAutoID
|| x.AutoGenerateAction == AutoGenerateAction.DatabaseChangeTimestamp
|| x.AutoGenerateAction == AutoGenerateAction.DatabaseCreateTimestamp
)
);
IsPrimaryKeyAutogenerated = PrimaryKeys.Any(x => x.AutoGenerateAction == AutoGenerateAction.DatabaseAutoID);
HasDatabaseGeneratedCreateTimestamp = ColumnsWithoutPrimaryKey.Any(x => x.AutoGenerateAction == AutoGenerateAction.DatabaseCreateTimestamp);
HasDatabaseGeneratedChangeTimestamp = ColumnsWithoutPrimaryKey.Any(x => x.AutoGenerateAction == AutoGenerateAction.DatabaseChangeTimestamp);
ValidationRules = type.GetCustomAttributes<ValidationBaseAttribute>(true).ToArray();
AllColumnsWithValidationRules = AllColumns.Where(x => x.ValidationRules.Length > 0).ToArray();
HasValidationRules = ValidationRules.Length + AllColumnsWithValidationRules.Length > 0;
}
/// <summary>
/// Returns the column name in quotes
/// </summary>
/// <param name="propertyname">The name of the property to get the column name for</param>
/// <returns>The quoted column name</returns>
public string QuotedColumnName(string propertyname)
{
return Dialect.QuoteName(AllColumnsByMemberName[propertyname].ColumnName);
}
/// <summary>
/// Calls all validation methods on the item
/// </summary>
/// <param name="item">The item to validate, must be of the target type or a dictionary</param>
public void Validate(object item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
// Do not waste time testing empty validation rules
if (!HasValidationRules)
return;
if (item is Dictionary<string, object> dict)
{
// First validate the overall object
foreach (var v in ValidationRules)
v.Validate(item);
foreach (var c in dict)
{
if (!AllColumnsByMemberName.TryGetValue(c.Key, out var cl))
throw new ArgumentException($"No column named {c.Key} in {Type}");
foreach (var r in cl.ValidationRules)
{
try
{
r.Validate(c.Value);
}
catch (Exception ex)
{
// Add more context to the validation error
if (ex is ValidationException vex)
throw new ValidationException(Type, cl.Member, r, vex.Message, ex);
throw;
}
}
}
}
else if (item.GetType() == Type)
{
foreach (var v in ValidationRules)
v.Validate(item);
foreach (var cl in AllColumnsWithValidationRules)
{
var v = cl.GetValue(item);
foreach (var r in cl.ValidationRules)
{
try
{
r.Validate(v);
}
catch (Exception ex)
{
// Add more context to the validation error
if (ex is ValidationException vex)
throw new ValidationException(Type, cl.Member, r, vex.Message, ex);
throw;
}
}
}
}
else
{
throw new ArgumentException($"Item had type {item.GetType()} but it be either {Type} or a Dictionary<string, object>");
}
}
}
/// <summary>
/// The mapping of a column
/// </summary>
public class ColumnMapping
{
/// <summary>
/// Value indicating if the column is a primary key
/// </summary>
public readonly bool IsPrimaryKey;
/// <summary>
/// Value indicating if the column is auto-generated
/// </summary>
public readonly AutoGenerateAction AutoGenerateAction;
/// <summary>
/// The name of the column in SQL format
/// </summary>
public readonly string ColumnName;
/// <summary>
/// The name of the column, quoted for SQL
/// </summary>
public readonly string QuotedColumnName;
/// <summary>
/// The name of the member item
/// </summary>
public string MemberName => Member.Name;
/// <summary>
/// The type of the member
/// </summary>
/// <returns></returns>
public readonly Type MemberType;
/// <summary>
/// The property being mapped
/// </summary>
public readonly MemberInfo Member;
/// <summary>
/// The mapped type of the column
/// </summary>
public readonly string SqlType;
/// <summary>
/// The rules for validating values prior to insert or update
/// </summary>
public readonly ValidationBaseAttribute[] ValidationRules;
/// <summary>
/// Initializes a new instance of the <see cref="T:Ceen.Database.ColumnMapping"/> class.
/// </summary>
/// <param name="dialect">The database dialect.</param>
/// <param name="field">The field to map.</param>
public ColumnMapping(IDatabaseDialect dialect, FieldInfo field)
: this(dialect, field, field?.FieldType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Ceen.Database.ColumnMapping"/> class.
/// </summary>
/// <param name="dialect">The database dialect.</param>
/// <param name="property">The property to map.</param>
public ColumnMapping(IDatabaseDialect dialect, PropertyInfo property)
: this(dialect, property, property?.PropertyType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Ceen.Database.ColumnMapping"/> class.
/// </summary>
/// <param name="dialect">The database dialect.</param>
/// <param name="member">The member to map.</param>
/// <param name="memberType">The member type</param>
private ColumnMapping(IDatabaseDialect dialect, MemberInfo member, Type memberType)
{
Member = member ?? throw new ArgumentNullException(nameof(member));
MemberType = memberType;
ColumnName = dialect.GetName(member);
QuotedColumnName = dialect.QuoteName(ColumnName);
IsPrimaryKey = member.GetCustomAttributes<PrimaryKeyAttribute>(true).Any();
var sqlType = dialect.GetSqlColumnType(member);
SqlType = sqlType.Item1;
AutoGenerateAction = sqlType.Item2;
ValidationRules = member.GetCustomAttributes<ValidationBaseAttribute>(true).ToArray();
}
/// <summary>
/// Helper method to get the value from an instance
/// </summary>
/// <param name="instance">The instance to get the value from</param>
/// <returns>The value obtained from the instance</returns>
public object GetValue(object instance)
{
if (Member is PropertyInfo pi)
return pi.GetValue(instance);
else if (Member is FieldInfo fi)
return fi.GetValue(instance);
else
throw new ArgumentException($"Unexpected member type: {Member.GetType()}");
}
/// <summary>
/// Helper method to set the value on an instance
/// </summary>
/// <param name="instance">The instance to se the value on</param>
/// <param name="value">The value to se</param>
public void SetValue(object instance, object value)
{
if (Member is PropertyInfo pi)
pi.SetValue(instance, value);
else if (Member is FieldInfo fi)
fi.SetValue(instance, value);
else
throw new ArgumentException($"Unexpected member type: {Member.GetType()}");
}
/// <summary>
/// Sets the property value from the database value
/// </summary>
/// <param name="instance">The instance to set the value for</param>
/// <param name="value">The value to set</param>
public void SetValueFromDb(object instance, object value)
{
if (MemberType.IsEnum)
value = TryParseEnum(MemberType, value, true) ?? value;
SetValue(instance, Convert.ChangeType(value, MemberType));
}
/// <summary>
/// Helper method for parsing a stored enum, either as an integer or a string
/// </summary>
/// <param name="type">The enum type</param>
/// <param name="value">The value to attemp to parse</param>
/// <param name="ignoreCase">Case insensitive match</param>
/// <returns></returns>
private static object TryParseEnum(Type type, object value, bool ignoreCase)
{
if (value is string valstring)
{
if (Enum.GetNames(type).Contains(valstring, ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal))
return Enum.Parse(type, valstring, ignoreCase);
if (type.GetEnumUnderlyingType() == typeof(int))
{
if (int.TryParse(valstring, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var v))
value = v;
}
}
if (value is int valint)
{
var vals = Enum.GetValues(type);
var ix = Array.IndexOf(Enum.GetValues(type), valint);
if (ix >= 0)
return vals.GetValue(ix);
}
return null;
}
/// <summary>
/// Returns the value in a format suitable for inserting into the database
/// </summary>
/// <param name="instance">The instance to get the value for</param>
public object GetValueForDb(object instance)
{
var v = GetValue(instance);
if (MemberType.IsEnum)
return (v ?? string.Empty).ToString();
return v;
}
}
/// <summary>
/// Unique column mapping
/// </summary>
public class UniqueMapping
{
/// <summary>
/// The optional name of the group
/// </summary>
public readonly string Group;
/// <summary>
/// The columns in the mapping
/// </summary>
public readonly ColumnMapping[] Columns;
/// <summary>
/// Initializes a new instance of the <see cref="T:Ceen.Database.UniqueMapping"/> class.
/// </summary>
/// <param name="group">The group name, if any.</param>
/// <param name="columns">The columns in the mapping.</param>
public UniqueMapping(string group, ColumnMapping[] columns)
{
Group = group;
Columns = columns ?? throw new ArgumentNullException(nameof(columns));
}
}
}