Repository navigation
Expand file tree
/
Copy pathSqlDataProvider.cs
More file actions
450 lines (398 loc) · 15.5 KB
/
Copy pathSqlDataProvider.cs
File metadata and controls
450 lines (398 loc) · 15.5 KB
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.Linq;
using Audit.Core;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data.Common;
namespace Audit.SqlServer.Providers
{
/// <summary>
/// SQL Server data access
/// </summary>
/// <remarks>
/// Settings:
/// - ConnectionString: Database connection string
/// - DbConnection: Alternatively to ConnectionString, you can pass a DbConnection object
/// - TableName: Table name (default is 'Event')
/// - JsonColumnName: Column name where the JSON will be stored (default is 'Data')
/// - IdColumnName: Column name with the primary key (default is 'EventId')
/// - LastUpdatedDateColumnName: datetime column to update when replacing events (NULL to ignore)
/// - Schema: The Schema Name to use
/// - CustomColumns: A collection of custom columns to be added when saving the audit event
/// </remarks>
public class SqlDataProvider : AuditDataProvider
{
/// <summary>
/// The Database connection string to use.
/// </summary>
public Setting<string> ConnectionString { get; set; }
/// <summary>
/// The Db Connection to use. Alternative to ConnectionString.
/// </summary>
public Setting<DbConnection> DbConnection { get; set; }
/// <summary>
/// The Db Context instance to use. Alternative to ConnectionString and DbConnection.
/// When a DbContext instance is provided with this setting, the DbContext will not be disposed by the library.
/// </summary>
public Setting<DbContext> DbContext { get; set; }
/// <summary>
/// The SQL events Table Name
/// </summary>
public Setting<string> TableName { get; set; } = "Event";
/// <summary>
/// The Column Name that stores the JSON
/// </summary>
public Setting<string> JsonColumnName { get; set; }
/// <summary>
/// The Column Name that stores the Last Updated Date (NULL to ignore)
/// </summary>
public Setting<string> LastUpdatedDateColumnName { get; set; }
/// <summary>
/// The Column Name that is the primary ley
/// </summary>
public Setting<string> IdColumnName { get; set; }
/// <summary>
/// The Schema Name to use (NULL to ignore)
/// </summary>
public Setting<string> Schema { get; set; }
/// <summary>
/// A collection of custom columns to be added when saving the audit event
/// </summary>
public List<CustomColumn> CustomColumns { get; set; } = new List<CustomColumn>();
/// <summary>
/// The DbContext options builder, to provide custom database options for the Default Audit DbContext. This setting is ignored if a DbContext instance is provided.
/// </summary>
[CLSCompliant(false)]
public Setting<DbContextOptions> DbContextOptions { get; set; }
public SqlDataProvider()
{
}
[CLSCompliant(false)]
public SqlDataProvider(Action<Configuration.ISqlServerProviderConfigurator> config)
{
var sqlConfig = new Configuration.SqlServerProviderConfigurator();
if (config != null)
{
config.Invoke(sqlConfig);
ConnectionString = sqlConfig._connectionString;
DbConnection = sqlConfig._dbConnection;
DbContext = sqlConfig._dbContext;
IdColumnName = sqlConfig._idColumnName;
JsonColumnName = sqlConfig._jsonColumnName;
LastUpdatedDateColumnName = sqlConfig._lastUpdatedColumnName;
Schema = sqlConfig._schema;
TableName = sqlConfig._tableName;
CustomColumns = sqlConfig._customColumns;
DbContextOptions = sqlConfig._dbContextOptions;
}
}
public override object InsertEvent(AuditEvent auditEvent)
{
object[] parameters = GetParametersForInsert(auditEvent);
var ctx = CreateContext(auditEvent, out var isLocal);
var cmdText = GetInsertCommandText(auditEvent);
try
{
#if NET7_0_OR_GREATER
var result = ctx.Database.SqlQueryRaw<string>(cmdText, parameters);
var id = result.ToList().FirstOrDefault();
#else
var result = ctx.Set<AuditEventValueModel>().FromSqlRaw(cmdText, parameters);
var id = result.ToList().FirstOrDefault()?.Value;
#endif
return id;
}
finally
{
if (isLocal && ctx != null)
{
ctx.Dispose();
}
}
}
public override async Task<object> InsertEventAsync(AuditEvent auditEvent, CancellationToken cancellationToken = default)
{
var parameters = GetParametersForInsert(auditEvent);
var ctx = CreateContext(auditEvent, out var isLocal);
var cmdText = GetInsertCommandText(auditEvent);
try
{
#if NET7_0_OR_GREATER
var result = ctx.Database.SqlQueryRaw<string>(cmdText, parameters);
var id = (await result.ToListAsync(cancellationToken)).FirstOrDefault();
#else
var result = ctx.Set<AuditEventValueModel>().FromSqlRaw(cmdText, parameters);
var id = (await result.ToListAsync(cancellationToken)).FirstOrDefault()?.Value;
#endif
return id;
}
finally
{
if (isLocal && ctx != null)
{
await ctx.DisposeAsync();
}
}
}
public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
{
var parameters = GetParametersForReplace(eventId, auditEvent);
var ctx = CreateContext(auditEvent, out var isLocal);
var cmdText = GetReplaceCommandText(auditEvent);
try
{
ctx.Database.ExecuteSqlRaw(cmdText, parameters);
}
finally
{
if (isLocal && ctx != null)
{
ctx.Dispose();
}
}
}
public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent, CancellationToken cancellationToken = default)
{
var parameters = GetParametersForReplace(eventId, auditEvent);
var ctx = CreateContext(auditEvent, out var isLocal);
var cmdText = GetReplaceCommandText(auditEvent);
try
{
await ctx.Database.ExecuteSqlRawAsync(cmdText, parameters, cancellationToken);
}
finally
{
if (isLocal && ctx != null)
{
await ctx.DisposeAsync();
}
}
}
public override T GetEvent<T>(object eventId)
{
if (JsonColumnName.GetDefault() == null)
{
return null;
}
var ctx = CreateContext(null, out var isLocal);
var cmdText = GetSelectCommandText(null);
try
{
#if NET7_0_OR_GREATER
var result = ctx.Database.SqlQueryRaw<string>(cmdText, new SqlParameter("@eventId", eventId));
var json = result.FirstOrDefault();
#else
var result = ctx.Set<AuditEventValueModel>().FromSqlRaw(cmdText, new SqlParameter("@eventId", eventId));
var json = result.FirstOrDefault()?.Value;
#endif
if (json != null)
{
return AuditEvent.FromJson<T>(json);
}
return null;
}
finally
{
if (isLocal && ctx != null)
{
ctx.Dispose();
}
}
}
public override async Task<T> GetEventAsync<T>(object eventId, CancellationToken cancellationToken = default)
{
if (JsonColumnName.GetDefault() == null)
{
return null;
}
var ctx = CreateContext(null, out var isLocal);
var cmdText = GetSelectCommandText(null);
try
{
#if NET7_0_OR_GREATER
var result = ctx.Database.SqlQueryRaw<string>(cmdText, new SqlParameter("@eventId", eventId));
var json = await result.FirstOrDefaultAsync(cancellationToken);
#else
var result = ctx.Set<AuditEventValueModel>().FromSqlRaw(cmdText, new SqlParameter("@eventId", eventId));
var json = (await result.FirstOrDefaultAsync(cancellationToken))?.Value;
#endif
if (json != null)
{
return AuditEvent.FromJson<T>(json);
}
return null;
}
finally
{
if (isLocal && ctx != null)
{
await ctx.DisposeAsync();
}
}
}
protected internal string GetFullTableName(AuditEvent auditEvent)
{
var schema = Schema.GetValue(auditEvent);
var table = TableName.GetValue(auditEvent);
return schema != null ? $"[{schema}].[{table}]" : $"[{table}]";
}
protected string GetInsertCommandText(AuditEvent auditEvent)
{
return string.Format("INSERT INTO {0} ({1}) OUTPUT CONVERT(NVARCHAR(MAX), INSERTED.[{2}]) AS [Value] VALUES ({3})",
GetFullTableName(auditEvent),
GetColumnsForInsert(auditEvent),
IdColumnName.GetValue(auditEvent),
GetValuesForInsert(auditEvent));
}
private string GetColumnsForInsert(AuditEvent auditEvent)
{
var columns = new List<string>();
var jsonColumnName = JsonColumnName.GetValue(auditEvent);
if (jsonColumnName != null)
{
columns.Add(jsonColumnName);
}
if (CustomColumns != null)
{
foreach (var column in CustomColumns)
{
if (column.Guard == null || column.Guard.Invoke(auditEvent))
{
columns.Add(column.Name);
}
}
}
return string.Join(", ", columns.Select(c => $"[{c}]"));
}
private string GetValuesForInsert(AuditEvent auditEvent)
{
var values = new List<string>();
if (JsonColumnName.GetValue(auditEvent) != null)
{
values.Add("@json");
}
if (CustomColumns != null)
{
int i = 0;
foreach (var column in CustomColumns)
{
if (column.Guard == null || column.Guard.Invoke(auditEvent))
{
values.Add($"@c{i}");
i++;
}
}
}
return string.Join(", ", values);
}
protected SqlParameter[] GetParametersForInsert(AuditEvent auditEvent)
{
var parameters = new List<SqlParameter>();
if (JsonColumnName.GetValue(auditEvent) != null)
{
parameters.Add(new SqlParameter("@json", auditEvent.ToJson()));
}
if (CustomColumns != null)
{
int i = 0;
foreach (var column in CustomColumns)
{
if (column.Guard == null || column.Guard.Invoke(auditEvent))
{
parameters.Add(new SqlParameter($"@c{i}", column.Value.Invoke(auditEvent) ?? DBNull.Value));
i++;
}
}
}
return parameters.ToArray();
}
protected SqlParameter[] GetParametersForReplace(object eventId, AuditEvent auditEvent)
{
var parameters = new List<SqlParameter>();
if (JsonColumnName.GetValue(auditEvent) != null)
{
parameters.Add(new SqlParameter("@json", auditEvent.ToJson()));
}
parameters.Add(new SqlParameter("@eventId", eventId));
if (CustomColumns != null)
{
int i = 0;
foreach (var column in CustomColumns)
{
if (column.Guard == null || column.Guard.Invoke(auditEvent))
{
parameters.Add(new SqlParameter($"@c{i}", column.Value.Invoke(auditEvent) ?? DBNull.Value));
i++;
}
}
}
return parameters.ToArray();
}
protected string GetReplaceCommandText(AuditEvent auditEvent)
{
var cmdText = string.Format("UPDATE {0} SET {1} WHERE [{2}] = @eventId",
GetFullTableName(auditEvent),
GetSetForUpdate(auditEvent),
IdColumnName.GetValue(auditEvent));
return cmdText;
}
private string GetSetForUpdate(AuditEvent auditEvent)
{
var jsonColumnName = JsonColumnName.GetValue(auditEvent);
var ludColumn = LastUpdatedDateColumnName.GetValue(auditEvent);
var sets = new List<string>();
if (jsonColumnName != null)
{
sets.Add($"[{jsonColumnName}] = @json");
}
if (ludColumn != null)
{
sets.Add($"[{ludColumn}] = GETUTCDATE()");
}
if (CustomColumns != null)
{
int i = 0;
foreach (var column in CustomColumns)
{
if (column.Guard == null || column.Guard.Invoke(auditEvent))
{
sets.Add($"[{column.Name}] = @c{i}");
i++;
}
}
}
return string.Join(", ", sets);
}
protected string GetSelectCommandText(AuditEvent auditEvent)
{
var cmdText = string.Format("SELECT [{0}] As [Value] FROM {1} WHERE [{2}] = @eventId",
JsonColumnName.GetValue(auditEvent),
GetFullTableName(auditEvent),
IdColumnName.GetValue(auditEvent));
return cmdText;
}
protected virtual DbContext CreateContext(AuditEvent auditEvent, out bool isLocal)
{
// Use the DbContext if provided
var dbContext = DbContext.GetValue(auditEvent);
if (dbContext != null)
{
isLocal = false;
return dbContext;
}
isLocal = true;
// Use the connection string or the db connection
var ctxOptions = DbContextOptions.GetValue(auditEvent);
var dbConnection = DbConnection.GetValue(auditEvent);
if (dbConnection != null)
{
return ctxOptions != null ? new DefaultAuditDbContext(dbConnection, ctxOptions) : new DefaultAuditDbContext(dbConnection);
}
var connectionString = ConnectionString.GetValue(auditEvent);
return ctxOptions != null ? new DefaultAuditDbContext(connectionString, ctxOptions) : new DefaultAuditDbContext(connectionString);
}
}
}