-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDBContext.cs
465 lines (405 loc) · 23.8 KB
/
DBContext.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
// ReSharper disable RedundantArgumentDefaultValue
namespace Easy.Storage.Common
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Easy.Common;
using Easy.Common.Extensions;
using Easy.Storage.Common.Extensions;
using Easy.Storage.Common.Filter;
/// <summary>
/// Represents the context for retrieving records of the given <typeparamref name="T"/>
/// type from the storage.
/// </summary>
// ReSharper disable once InconsistentNaming
public sealed class DBContext<T> : IDBContext<T>
{
/// <summary>
/// Creates an instance of the <see cref="DBContext{T}"/>.
/// </summary>
internal DBContext(IDbConnection dbConnection, Dialect dialect, string tableName = "")
{
Connection = Ensure.NotNull(dbConnection, nameof(dbConnection));
Table = Table.MakeOrGet<T>(dialect, tableName);
}
/// <summary>
/// Gets the underlying connection.
/// </summary>
public IDbConnection Connection { get; }
/// <summary>
/// Gets the abstraction used for working with the model.
/// </summary>
public Table Table { get; }
/// <summary>
/// Gets a <see cref="Query{T}"/> instance for building queries.
/// </summary>
public Query<T> Query => Query<T>.For(Table);
/// <summary>
/// Gets the records represented by the <typeparamref name="T"/> from the storage.
/// <remarks>This method returns a buffered result.</remarks>
/// </summary>
public async Task<IList<T>> Get(IDbTransaction transaction = null)
=> (await Connection.QueryAsync<T>(Table.Select, transaction: transaction, buffered: true)
.ConfigureAwait(false)).SpeculativeToList();
/// <summary>
/// Gets the records represented by the <typeparamref name="T"/> from the storage.
/// <remarks>This method returns a non-buffered result.</remarks>
/// </summary>
public Task<IEnumerable<T>> GetLazy(IDbTransaction transaction = null)
=> Connection.QueryAsync<T>(Table.Select, transaction: transaction, buffered: false);
/// <summary>
/// Gets the records represented by the <typeparamref name="T"/> from the storage.
/// <remarks>This method returns a buffered result.</remarks>
/// </summary>
/// <param name="selector">The selector used to identify the column by which the query should be filtered.</param>
/// <param name="value">The value associated to the column specified by the <paramref name="selector"/> by which the query should be filtered.</param>
/// <param name="transaction">The transaction</param>
public async Task<IList<T>> GetWhere<TProperty>(
Expression<Func<T, TProperty>> selector, TProperty value, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var filter = Query.Filter.And(selector, Operator.Is, value);
var sql = filter.GetSQL();
var parameters = filter.Parameters.ToDynamicParameters();
return (await Connection.QueryAsync<T>(sql, parameters, transaction, buffered: true)
.ConfigureAwait(false)).SpeculativeToList();
}
/// <summary>
/// Gets the records represented by the <typeparamref name="T"/> from the storage.
/// <remarks>This method returns a buffered result.</remarks>
/// </summary>
/// <param name="selector">The selector used to identify the column by which the query should be filtered.</param>
/// <param name="transaction">The transaction</param>
/// <param name="values">The values associated to the column specified by the <paramref name="selector"/> by which the query should be filtered.</param>
public async Task<IList<T>> GetWhere<TProperty>(
Expression<Func<T, TProperty>> selector, IDbTransaction transaction = null, params TProperty[] values)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(values, nameof(values));
var filter = Query.Filter.AndIn(selector, values);
var sql = filter.GetSQL();
var parameters = filter.Parameters.ToDynamicParameters();
return (await Connection.QueryAsync<T>(sql, parameters, transaction, buffered: true)
.ConfigureAwait(false)).SpeculativeToList();
}
/// <summary>
/// Gets the records represented by the <typeparamref name="T"/> based on the given <paramref name="filter"/>.
/// <remarks>This method returns a buffered result.</remarks>
/// </summary>
/// <param name="transaction">The transaction</param>
/// <param name="filter">The filter to limit the records returned</param>
public async Task<IList<T>> GetWhere(Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(filter, nameof(filter));
var sql = filter.GetSQL();
var parameters = filter.Parameters.ToDynamicParameters();
return (await Connection.QueryAsync<T>(sql, parameters, transaction, buffered: true)
.ConfigureAwait(false)).SpeculativeToList();
}
/// <summary>
/// Inserts the given <paramref name="item"/> to the storage.
/// </summary>
/// <param name="item">The item to be inserted.</param>
/// <param name="transaction">The transaction</param>
/// <returns>The inserted id of the <paramref name="item"/>.</returns>
public async Task<object> Insert(T item, IDbTransaction transaction = null)
{
var insertSql = Table.HasIdentityColumn ? Table.InsertIdentity : Table.InsertAll;
return (await Connection.QueryAsync<dynamic>(insertSql, item, transaction, buffered: true)
.ConfigureAwait(false)).First().Id;
}
/// <summary>
/// Inserts the given <paramref name="items"/> to the storage.
/// </summary>
/// <param name="items">The items to be inserted.</param>
/// <param name="transaction">The transaction</param>
/// <returns>The number of inserted records.</returns>
public Task<int> Insert(IEnumerable<T> items, IDbTransaction transaction = null)
{
Ensure.NotNull(items, nameof(items));
var insertSql = Table.HasIdentityColumn ? Table.InsertIdentity : Table.InsertAll;
return Connection.ExecuteAsync(insertSql, items, transaction);
}
/// <summary>
/// Inserts every specified columns in the given <paramref name="item"/> as the record.
/// </summary>
/// <param name="item">The item to be inserted.</param>
/// <param name="transaction">The transaction</param>
/// <returns>The inserted id of the <paramref name="item"/>.</returns>
public async Task<object> InsertPartial(object item, IDbTransaction transaction = null)
{
Ensure.NotNull(item, nameof(item));
var sql = Table.Dialect.GetPartialInsertQuery<T>(Table, item);
return (await Connection.QueryAsync<dynamic>(sql, item, transaction, buffered: true)
.ConfigureAwait(false)).First().Id;
}
/// <summary>
/// Inserts every specified columns of every item in the given <paramref name="items"/> as the record.
/// </summary>
/// <param name="items">The items to be inserted.</param>
/// <param name="transaction">The transaction</param>
/// <returns>Number of inserted rows</returns>
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public async Task<int> InsertPartial(IEnumerable<object> items, IDbTransaction transaction = null)
{
Ensure.NotNull(items, nameof(items));
string sql = null;
var counter = 0;
foreach (var item in items)
{
if (sql is null)
{
sql = Table.Dialect.GetPartialInsertQuery<T>(Table, item);
}
counter += await Connection.ExecuteAsync(sql, item, transaction);
}
return counter;
}
/// <summary>
/// Updates every column in the given <paramref name="item"/> (except for the id column) for the record.
/// <remarks>The id of the <paramref name="item"/> is used to identify the record to be updated.</remarks>.
/// </summary>
/// <returns>Number of rows affected</returns>
public Task<int> Update(T item, IDbTransaction transaction = null)
=> Connection.ExecuteAsync(Table.UpdateIdentity, item, transaction);
/// <summary>
/// Updates every column for each of the items in the given <paramref name="items"/> (except for the id column) for the record.
/// <remarks>The id of each item in the <paramref name="items"/> is used to identify the record to be updated.</remarks>.
/// </summary>
/// <returns>Number of rows affected</returns>
public Task<int> Update(IEnumerable<T> items, IDbTransaction transaction = null)
{
Ensure.NotNull(items, nameof(items));
return Connection.ExecuteAsync(Table.UpdateIdentity, items, transaction);
}
/// <summary>
/// Updates every column in the given <paramref name="item"/> (including the id column) for the record.
/// <remarks>The <paramref name="filter"/> is used to identify the record(s) to be updated.</remarks>.
/// </summary>
/// <returns>Number of rows affected</returns>
public Task<int> UpdateWhere(T item, Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(filter, nameof(filter));
var sql = filter.GetSQL(Table.UpdateAll);
var parameters = filter.Parameters.ToDynamicParameters(item);
return Connection.ExecuteAsync(sql, parameters, transaction);
}
/// <summary>
/// Updates every specified columns in the given <paramref name="item"/> for the record.
/// <remarks>The <paramref name="filter"/> is used to identify the record(s) to be updated.</remarks>.
/// </summary>
/// <returns>Number of rows affected</returns>
public Task<int> UpdatePartialWhere(
object item, Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(item, nameof(item));
Ensure.NotNull(filter, nameof(filter));
var sql = Table.Dialect.GetPartialUpdateQuery(Table, item, filter);
var parameters = filter.Parameters.ToDynamicParameters();
parameters.AddDynamicParams(item);
return Connection.ExecuteAsync(sql, parameters, transaction);
}
/// <summary>
/// Deletes a record based on the value of the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the query should be filtered.</param>
/// <param name="value">The value associated to the column specified by the <paramref name="selector"/> by which the query should be filtered.</param>
/// <param name="transaction">The transaction</param>
/// <returns>Number of rows affected</returns>
public Task<int> DeleteWhere<TProperty>(
Expression<Func<T, TProperty>> selector, TProperty value, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var filter = Query.Filter.And(selector, Operator.Is, value);
var sql = filter.GetSQL(Table.Delete);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteAsync(sql, parameters, transaction);
}
/// <summary>
/// Deletes a record based on the value of the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the query should be filtered.</param>
/// <param name="transaction">The transaction</param>
/// <param name="values">The values associated to the column specified by the <paramref name="selector"/> by which the query should be filtered.</param>
/// <returns>Number of rows affected</returns>
public Task<int> DeleteWhere<TProperty>(
Expression<Func<T, TProperty>> selector, IDbTransaction transaction = null, params TProperty[] values)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(values, nameof(values));
var filter = Query.Filter.AndIn(selector, values);
var sql = filter.GetSQL(Table.Delete);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteAsync(sql, parameters, transaction);
}
/// <summary>
/// Deletes a record based on the given <paramref name="filter"/>.
/// </summary>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="transaction">The transaction</param>
/// <returns>Number of rows affected</returns>
public Task<int> DeleteWhere(Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(filter, nameof(filter));
var sql = filter.GetSQL(Table.Delete);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteAsync(sql, parameters, transaction);
}
/// <summary>
/// Deletes all the records.
/// </summary>
public Task<int> DeleteAll(IDbTransaction transaction = null)
=> Connection.ExecuteAsync(Table.Delete, transaction: transaction);
/// <summary>
/// Returns the count of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>COUNT</c> should be calculated.</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<ulong> Count<TProperty>(Expression<Func<T, TProperty>> selector, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT COUNT ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name}";
return Connection.ExecuteScalarAsync<ulong>(query, transaction: transaction);
}
/// <summary>
/// Returns the count of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>COUNT</c> should be calculated.</param>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<ulong> Count<TProperty>(Expression<Func<T, TProperty>> selector, Filter<T> filter, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(filter, nameof(filter));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT COUNT ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name} WHERE 1=1";
var sql = filter.GetSQL(query);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteScalarAsync<ulong>(sql, parameters, transaction);
}
/// <summary>
/// Returns the sum of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>SUM</c> should be calculated.</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<long> Sum<TProperty>(Expression<Func<T, TProperty>> selector, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT SUM ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name}";
return Connection.ExecuteScalarAsync<long>(query, transaction: transaction);
}
/// <summary>
/// Returns the sum of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>SUM</c> should be calculated.</param>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<long> Sum<TProperty>(Expression<Func<T, TProperty>> selector, Filter<T> filter, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(filter, nameof(filter));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT SUM ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name} WHERE 1=1";
var sql = filter.GetSQL(query);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteScalarAsync<long>(sql, parameters, transaction);
}
/// <summary>
/// Returns the average of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>AVG</c> should be calculated.</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<decimal> Avg<TProperty>(Expression<Func<T, TProperty>> selector, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT AVG ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name}";
return Connection.ExecuteScalarAsync<decimal>(query, transaction: transaction);
}
/// <summary>
/// Returns the average of records based on the given <paramref name="selector"/>.
/// </summary>
/// <param name="selector">The selector used to identify the column by which the <c>AVG</c> should be calculated.</param>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="distinct">The flag indicating whether unique values should be considered only or not.</param>
/// <param name="transaction">The transaction</param>
public Task<decimal> Avg<TProperty>(Expression<Func<T, TProperty>> selector, Filter<T> filter, bool distinct = false, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(filter, nameof(filter));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT AVG ({(distinct ? "DISTINCT" : string.Empty)} {column}) FROM {Table.Name} WHERE 1=1";
var sql = filter.GetSQL(query);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteScalarAsync<decimal>(sql, parameters, transaction);
}
/// <summary>
/// Returns the minimum value defined by the given <paramref name="selector"/>.
/// <param name="selector">The selector used to identify the column by which the <c>MIN</c> should be calculated.</param>
/// <param name="transaction">The transaction</param>
/// </summary>
public Task<TProperty> Min<TProperty>(Expression<Func<T, TProperty>> selector, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT MIN ({column}) FROM {Table.Name}";
return Connection.ExecuteScalarAsync<TProperty>(query, transaction: transaction);
}
/// <summary>
/// Returns the minimum value defined by the given <paramref name="selector"/>.
/// <param name="selector">The selector used to identify the column by which the <c>MIN</c> should be calculated.</param>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="transaction">The transaction</param>
/// </summary>
public Task<TProperty> Min<TProperty>(Expression<Func<T, TProperty>> selector, Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(filter, nameof(filter));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT MIN ({column}) FROM {Table.Name} WHERE 1=1";
var sql = filter.GetSQL(query);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteScalarAsync<TProperty>(sql, parameters, transaction);
}
/// <summary>
/// Returns the maximum value defined by the given <paramref name="selector"/>.
/// <param name="selector">The selector used to identify the column by which the <c>MAX</c> should be calculated.</param>
/// <param name="transaction">The transaction</param>
/// </summary>
public Task<TProperty> Max<TProperty>(Expression<Func<T, TProperty>> selector, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT MAX ({column}) FROM {Table.Name}";
return Connection.ExecuteScalarAsync<TProperty>(query, transaction: transaction);
}
/// <summary>
/// Returns the maximum value defined by the given <paramref name="selector"/>.
/// <param name="selector">The selector used to identify the column by which the <c>MAX</c> should be calculated.</param>
/// <param name="filter">The filter to limit the records returned</param>
/// <param name="transaction">The transaction</param>
/// </summary>
public Task<TProperty> Max<TProperty>(Expression<Func<T, TProperty>> selector, Filter<T> filter, IDbTransaction transaction = null)
{
Ensure.NotNull(selector, nameof(selector));
Ensure.NotNull(filter, nameof(filter));
var column = Table.PropertyNamesToColumns[selector.GetPropertyName()];
var query = $"SELECT MAX ({column}) FROM {Table.Name} WHERE 1=1";
var sql = filter.GetSQL(query);
var parameters = filter.Parameters.ToDynamicParameters();
return Connection.ExecuteScalarAsync<TProperty>(sql, parameters, transaction);
}
}
}