forked from DapperLib/Dapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabase.cs
478 lines (421 loc) · 23 KB
/
Database.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text;
using System.Data.Common;
using System.Reflection.Emit;
namespace Dapper
{
/// <summary>
/// Represents a database, assumes all the tables have an Id column named Id
/// </summary>
/// <typeparam name="TDatabase">The type of database this represents.</typeparam>
public abstract partial class Database<TDatabase> : IDisposable where TDatabase : Database<TDatabase>, new()
{
/// <summary>
/// A database table of type <typeparamref name="T"/> and primary key of type <typeparamref name="TId"/>.
/// </summary>
/// <typeparam name="T">The type of object in this table.</typeparam>
/// <typeparam name="TId">The type of the primary key for this table.</typeparam>
public partial class Table<T, TId>
{
internal Database<TDatabase> database;
internal string tableName;
internal string likelyTableName;
/// <summary>
/// Creates a table in the specified database with a given name.
/// </summary>
/// <param name="database">The database this table belongs in.</param>
/// <param name="likelyTableName">The name for this table.</param>
public Table(Database<TDatabase> database, string likelyTableName)
{
this.database = database;
this.likelyTableName = likelyTableName;
}
/// <summary>
/// The name for this table.
/// </summary>
public string TableName
{
get
{
tableName = tableName ?? database.DetermineTableName<T>(likelyTableName);
return tableName;
}
}
/// <summary>
/// Insert a row into the db
/// </summary>
/// <param name="data">Either DynamicParameters or an anonymous type or concrete type</param>
/// <returns></returns>
public virtual int? Insert(dynamic data)
{
var o = (object)data;
List<string> paramNames = GetParamNames(o);
paramNames.Remove("Id");
string cols = string.Join(",", paramNames);
string colsParams = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + colsParams + ") select cast(scope_identity() as int)";
return database.Query<int?>(sql, o).Single();
}
/// <summary>
/// Update a record in the database.
/// </summary>
/// <param name="id">The primary key of the row to update.</param>
/// <param name="data">The new object data.</param>
/// <returns>The number of rows affected.</returns>
public int Update(TId id, dynamic data)
{
List<string> paramNames = GetParamNames((object)data);
var builder = new StringBuilder();
builder.Append("update ").Append(TableName).Append(" set ");
builder.AppendLine(string.Join(",", paramNames.Where(n => n != "Id").Select(p => p + "= @" + p)));
builder.Append("where Id = @Id");
DynamicParameters parameters = new DynamicParameters(data);
parameters.Add("Id", id);
return database.Execute(builder.ToString(), parameters);
}
/// <summary>
/// Delete a record for the DB
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool Delete(TId id)
{
return database.Execute("delete from " + TableName + " where Id = @id", new { id }) > 0;
}
/// <summary>
/// Gets a record with a particular Id from the DB
/// </summary>
/// <param name="id">The primary key of the table to fetch.</param>
/// <returns>The record with the specified Id.</returns>
public T Get(TId id)
{
return database.QueryFirstOrDefault<T>("select * from " + TableName + " where Id = @id", new { id });
}
/// <summary>
/// Gets the first row from this table (order determined by the database provider).
/// </summary>
/// <returns>Data from the first table row.</returns>
public virtual T First()
{
return database.QueryFirstOrDefault<T>("select top 1 * from " + TableName);
}
/// <summary>
/// Gets the all rows from this table.
/// </summary>
/// <returns>Data from all table rows.</returns>
public IEnumerable<T> All()
{
return database.Query<T>("select * from " + TableName);
}
private static readonly ConcurrentDictionary<Type, List<string>> paramNameCache = new ConcurrentDictionary<Type, List<string>>();
internal static List<string> GetParamNames(object o)
{
if (o is DynamicParameters parameters)
{
return parameters.ParameterNames.ToList();
}
if (!paramNameCache.TryGetValue(o.GetType(), out List<string> paramNames))
{
paramNames = new List<string>();
foreach (var prop in o.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.GetGetMethod(false) != null))
{
var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true);
var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute;
if (attr == null || (!attr.Value))
{
paramNames.Add(prop.Name);
}
}
paramNameCache[o.GetType()] = paramNames;
}
return paramNames;
}
}
/// <summary>
/// A database table of type <typeparamref name="T"/> and primary key of type <see cref="int"/>.
/// </summary>
/// <typeparam name="T">The type of object in this table.</typeparam>
public class Table<T> : Table<T, int>
{
/// <summary>
/// Creates a table in the specified database with a given name.
/// </summary>
/// <param name="database">The database this table belongs in.</param>
/// <param name="likelyTableName">The name for this table.</param>
public Table(Database<TDatabase> database, string likelyTableName)
: base(database, likelyTableName)
{
}
}
private DbConnection _connection;
private int _commandTimeout;
private DbTransaction _transaction;
/// <summary>
/// Initializes the database.
/// </summary>
/// <param name="connection">The connection to use.</param>
/// <param name="commandTimeout">The timeout to use (in seconds).</param>
/// <returns></returns>
public static TDatabase Init(DbConnection connection, int commandTimeout)
{
TDatabase db = new TDatabase();
db.InitDatabase(connection, commandTimeout);
return db;
}
internal static Action<TDatabase> tableConstructor;
internal void InitDatabase(DbConnection connection, int commandTimeout)
{
_connection = connection;
_commandTimeout = commandTimeout;
tableConstructor = tableConstructor ?? CreateTableConstructorForTable();
tableConstructor(this as TDatabase);
}
internal virtual Action<TDatabase> CreateTableConstructorForTable()
{
return CreateTableConstructor(typeof(Table<>), typeof(Table<,>));
}
/// <summary>
/// Begins a transaction in this database.
/// </summary>
/// <param name="isolation">The isolation level to use.</param>
public void BeginTransaction(IsolationLevel isolation = IsolationLevel.ReadCommitted)
{
_transaction = _connection.BeginTransaction(isolation);
}
/// <summary>
/// Commits the current transaction in this database.
/// </summary>
public void CommitTransaction()
{
_transaction.Commit();
_transaction = null;
}
/// <summary>
/// Rolls back the current transaction in this database.
/// </summary>
public void RollbackTransaction()
{
_transaction.Rollback();
_transaction = null;
}
/// <summary>
/// Gets a table creation function for the specified type.
/// </summary>
/// <param name="tableType">The object type to create a table for.</param>
/// <returns>The function to create the <paramref name="tableType"/> table.</returns>
protected Action<TDatabase> CreateTableConstructor(Type tableType)
{
return CreateTableConstructor(new[] { tableType });
}
/// <summary>
/// Gets a table creation function for the specified types.
/// </summary>
/// <param name="tableTypes">The object types to create a table for.</param>
/// <returns>The function to create the <paramref name="tableTypes"/> tables.</returns>
protected Action<TDatabase> CreateTableConstructor(params Type[] tableTypes)
{
var dm = new DynamicMethod("ConstructInstances", null, new[] { typeof(TDatabase) }, true);
var il = dm.GetILGenerator();
var setters = GetType().GetProperties()
.Where(p => p.PropertyType.IsGenericType() && tableTypes.Contains(p.PropertyType.GetGenericTypeDefinition()))
.Select(p => Tuple.Create(
p.GetSetMethod(true),
p.PropertyType.GetConstructor(new[] { typeof(TDatabase), typeof(string) }),
p.Name,
p.DeclaringType
));
foreach (var setter in setters)
{
il.Emit(OpCodes.Ldarg_0);
// [db]
il.Emit(OpCodes.Ldstr, setter.Item3);
// [db, likelyname]
il.Emit(OpCodes.Newobj, setter.Item2);
// [table]
var table = il.DeclareLocal(setter.Item2.DeclaringType);
il.Emit(OpCodes.Stloc, table);
// []
il.Emit(OpCodes.Ldarg_0);
// [db]
il.Emit(OpCodes.Castclass, setter.Item4);
// [db cast to container]
il.Emit(OpCodes.Ldloc, table);
// [db cast to container, table]
il.Emit(OpCodes.Callvirt, setter.Item1);
// []
}
il.Emit(OpCodes.Ret);
return (Action<TDatabase>)dm.CreateDelegate(typeof(Action<TDatabase>));
}
private static readonly ConcurrentDictionary<Type, string> tableNameMap = new ConcurrentDictionary<Type, string>();
private string DetermineTableName<T>(string likelyTableName)
{
if (!tableNameMap.TryGetValue(typeof(T), out string name))
{
name = likelyTableName;
if (!TableExists(name))
{
name = "[" + typeof(T).Name + "]";
}
tableNameMap[typeof(T)] = name;
}
return name;
}
private bool TableExists(string name)
{
string schemaName = null;
name = name.Replace("[", "");
name = name.Replace("]", "");
if (name.Contains("."))
{
var parts = name.Split('.');
if (parts.Length == 2)
{
schemaName = parts[0];
name = parts[1];
}
}
var builder = new StringBuilder("select 1 from INFORMATION_SCHEMA.TABLES where ");
if (!string.IsNullOrEmpty(schemaName)) builder.Append("TABLE_SCHEMA = @schemaName AND ");
builder.Append("TABLE_NAME = @name");
return _connection.Query(builder.ToString(), new { schemaName, name }, _transaction).Count() == 1;
}
/// <summary>
/// Executes SQL against the current database.
/// </summary>
/// <param name="sql">The SQL to execute.</param>
/// <param name="param">The parameters to use.</param>
/// <returns>The number of rows affected.</returns>
public int Execute(string sql, dynamic param = null) =>
_connection.Execute(sql, param as object, _transaction, _commandTimeout);
/// <summary>
/// Queries the current database.
/// </summary>
/// <typeparam name="T">The type to return.</typeparam>
/// <param name="sql">The SQL to execute.</param>
/// <param name="param">The parameters to use.</param>
/// <param name="buffered">Whether to buffer the results.</param>
/// <returns>An enumerable of <typeparamref name="T"/> for the rows fetched.</returns>
public IEnumerable<T> Query<T>(string sql, dynamic param = null, bool buffered = true) =>
_connection.Query<T>(sql, param as object, _transaction, buffered, _commandTimeout);
/// <summary>
/// Queries the current database for a single record.
/// </summary>
/// <typeparam name="T">The type to return.</typeparam>
/// <param name="sql">The SQL to execute.</param>
/// <param name="param">The parameters to use.</param>
/// <returns>An enumerable of <typeparamref name="T"/> for the rows fetched.</returns>
public T QueryFirstOrDefault<T>(string sql, dynamic param = null) =>
_connection.QueryFirstOrDefault<T>(sql, param as object, _transaction, _commandTimeout);
/// <summary>
/// Perform a multi-mapping query with 2 input types.
/// This returns a single type, combined from the raw types via <paramref name="map"/>.
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset.</typeparam>
/// <typeparam name="TSecond">The second type in the recordset.</typeparam>
/// <typeparam name="TReturn">The combined type to return.</typeparam>
/// <param name="sql">The SQL to execute for this query.</param>
/// <param name="map">The function to map row types to the return type.</param>
/// <param name="param">The parameters to use for this query.</param>
/// <param name="transaction">The transaction to use for this query.</param>
/// <param name="buffered">Whether to buffer the results in memory.</param>
/// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout.</param>
/// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns>
public IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) =>
_connection.Query(sql, map, param as object, transaction, buffered, splitOn, commandTimeout);
/// <summary>
/// Perform a multi-mapping query with 3 input types.
/// This returns a single type, combined from the raw types via <paramref name="map"/>.
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset.</typeparam>
/// <typeparam name="TSecond">The second type in the recordset.</typeparam>
/// <typeparam name="TThird">The third type in the recordset.</typeparam>
/// <typeparam name="TReturn">The combined type to return.</typeparam>
/// <param name="sql">The SQL to execute for this query.</param>
/// <param name="map">The function to map row types to the return type.</param>
/// <param name="param">The parameters to use for this query.</param>
/// <param name="transaction">The transaction to use for this query.</param>
/// <param name="buffered">Whether to buffer the results in memory.</param>
/// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout.</param>
/// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns>
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) =>
_connection.Query(sql, map, param as object, transaction, buffered, splitOn, commandTimeout);
/// <summary>
/// Perform a multi-mapping query with 4 input types.
/// This returns a single type, combined from the raw types via <paramref name="map"/>.
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset.</typeparam>
/// <typeparam name="TSecond">The second type in the recordset.</typeparam>
/// <typeparam name="TThird">The third type in the recordset.</typeparam>
/// <typeparam name="TFourth">The fourth type in the recordset.</typeparam>
/// <typeparam name="TReturn">The combined type to return.</typeparam>
/// <param name="sql">The SQL to execute for this query.</param>
/// <param name="map">The function to map row types to the return type.</param>
/// <param name="param">The parameters to use for this query.</param>
/// <param name="transaction">The transaction to use for this query.</param>
/// <param name="buffered">Whether to buffer the results in memory.</param>
/// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout.</param>
/// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns>
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) =>
_connection.Query(sql, map, param as object, transaction, buffered, splitOn, commandTimeout);
/// <summary>
/// Perform a multi-mapping query with 5 input types.
/// This returns a single type, combined from the raw types via <paramref name="map"/>.
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset.</typeparam>
/// <typeparam name="TSecond">The second type in the recordset.</typeparam>
/// <typeparam name="TThird">The third type in the recordset.</typeparam>
/// <typeparam name="TFourth">The fourth type in the recordset.</typeparam>
/// <typeparam name="TFifth">The fifth type in the recordset.</typeparam>
/// <typeparam name="TReturn">The combined type to return.</typeparam>
/// <param name="sql">The SQL to execute for this query.</param>
/// <param name="map">The function to map row types to the return type.</param>
/// <param name="param">The parameters to use for this query.</param>
/// <param name="transaction">The transaction to use for this query.</param>
/// <param name="buffered">Whether to buffer the results in memory.</param>
/// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout.</param>
/// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns>
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) =>
_connection.Query(sql, map, param as object, transaction, buffered, splitOn, commandTimeout);
/// <summary>
/// Return a sequence of dynamic objects with properties matching the columns
/// </summary>
/// <param name="sql">The SQL to execute.</param>
/// <param name="param">The parameters to use.</param>
/// <param name="buffered">Whether the results should be buffered in memory.</param>
/// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object></remarks>
public IEnumerable<dynamic> Query(string sql, dynamic param = null, bool buffered = true) =>
_connection.Query(sql, param as object, _transaction, buffered);
/// <summary>
/// Execute a command that returns multiple result sets, and access each in turn.
/// </summary>
/// <param name="sql">The SQL to execute for this query.</param>
/// <param name="param">The parameters to use for this query.</param>
/// <param name="transaction">The transaction to use for this query.</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout.</param>
/// <param name="commandType">Is it a stored proc or a batch?</param>
public SqlMapper.GridReader QueryMultiple(string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
SqlMapper.QueryMultiple(_connection, sql, param, transaction, commandTimeout, commandType);
/// <summary>
/// Disposes the current database, rolling back current transactions.
/// </summary>
public void Dispose()
{
if (_connection.State != ConnectionState.Closed)
{
_transaction?.Rollback();
_connection.Close();
_connection = null;
}
}
}
}