-
Notifications
You must be signed in to change notification settings - Fork 18
/
Database.cs
executable file
·294 lines (258 loc) · 9.38 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
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace DapperLite
{
public delegate void DapperLiteException(Exception e);
/// <summary>
/// A container for a database. Assumes all tables have an Id column named Id.
/// </summary>
/// <typeparam name="TId">The .NET equivalent type of the Id column (typically int or Guid).</typeparam>
public abstract class Database<TId>
{
private readonly IDbConnection m_connection;
private Dictionary<string, string> m_tableNameMap;
private readonly DapperLiteException m_exceptionHandler;
protected readonly bool m_throwExceptions;
protected Database(IDbConnection connection)
{
if (connection == null) throw new ArgumentException("Connection cannot be null");
m_connection = connection;
m_throwExceptions = true;
}
/// <summary>
/// Provides advanced configuration for the behaviour of the class when Exceptions are encountered.
/// </summary>
/// <param name="connection"></param>
/// <param name="exceptionHandler">Deletegate which will receive any caught Exception objects.</param>
/// <param name="throwExceptions">Indicate whether a caught exception should be re-thrown.</param>
protected Database(IDbConnection connection, DapperLiteException exceptionHandler, bool throwExceptions)
{
if (connection == null) throw new ArgumentException("Connection cannot be null");
m_connection = connection;
m_exceptionHandler = exceptionHandler;
m_throwExceptions = throwExceptions;
}
/// <summary>
/// This method must be called to initialize the table name map, used to map type names to table names.
/// </summary>
public void Init()
{
m_tableNameMap = GetTableNameMap();
}
/// <summary>
/// Wrapper method for the delegate so we don't throw an exception if the delegate is null.
/// </summary>
protected void ExceptionHandler(Exception e)
{
if (m_exceptionHandler != null) m_exceptionHandler(e);
}
protected IDbConnection GetConnection()
{
if (m_connection.State != ConnectionState.Open)
{
m_connection.Open();
}
return m_connection;
}
private static string Pluralize(string s)
{
char lastchar = s[s.Length - 1];
if (lastchar == 'y')
{
return s.Remove(s.Length - 1, 1) + "ies";
}
if (lastchar == 's')
{
return s;
}
return s + "s";
}
/// <summary>
/// This abstract method must be implemented by deriving types as
/// the implementation is specific to the SQL vendor (and possibly version).
/// </summary>
protected abstract Dictionary<string, string> GetTableNameMap();
/// <summary>
/// First checks if there is an exact match between type name and table name.
/// Then checks if there is a match between the pluralized type name and table name.
/// </summary>
private string GetTableName(MemberInfo type)
{
string tableName;
string typeName = type.Name;
// First see if the type name exactly matches a table name.
if (m_tableNameMap.TryGetValue(typeName, out tableName))
{
return tableName;
}
// Then check if when the type name is pluralized, it matches a table name.
if (m_tableNameMap.TryGetValue(Pluralize(typeName), out tableName))
{
return tableName;
}
throw new Exception(string.Format("Cannot match the type name {0} to any table", typeName));
}
protected string GetTableName(object obj)
{
return GetTableName(obj.GetType());
}
/// <summary>
/// A wrapper that uses the internally cached connection.
/// </summary>
public int Execute(string sql, object param, IDbTransaction transaction)
{
try
{
return GetConnection().Execute(sql, param, transaction);
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return -1;
}
/// <summary>
/// A wrapper that uses the internally cached connection.
/// </summary>
public int Execute(string sql)
{
return Execute(sql, null, null);
}
/// <summary>
/// A wrapper that uses the internally cached connection.
/// </summary>
public IEnumerable<T> Query<T>(string sql, object param)
{
try
{
return GetConnection().Query<T>(sql, param);
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return new List<T>();
}
/// <summary>
/// A wrapper that uses the internally cached connection.
/// </summary>
public IEnumerable<T> Query<T>(string sql)
{
return Query<T>(sql, null);
}
/// <summary>
/// Gets a single instance of a type by specifying the row Id.
/// </summary>
/// <returns>A specific instance of the specified type, or the default value for the type.</returns>
public T Get<T>(TId id)
{
try
{
string tableName = GetTableName(typeof(T));
return GetConnection().Query<T>("SELECT * FROM " + tableName + " WHERE Id = @id", new { id }).FirstOrDefault();
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return default(T);
}
/// <summary>
/// Gets a single instance of a type. Filters by a single column.
/// </summary>
/// <param name="columnName">Used to generate a WHERE clause.</param>
/// <param name="data">Input parameter for the WHERE clause.</param>
/// <returns>A specific instance of the specified type, or the default value for the type.</returns>
public T Get<T>(string columnName, object data)
{
try
{
return All<T>(columnName, data).FirstOrDefault();
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return default(T);
}
/// <summary>
/// Gets all records in the table matching the supplied type after applying the supplied filter
/// in a WHERE clause.
/// </summary>
/// <param name="columnName">Used to generate a WHERE clause.</param>
/// <param name="data">Input parameter for the WHERE clause.</param>
/// <returns>All records in the table matching the supplied type.</returns>
public IEnumerable<T> All<T>(string columnName, object data)
{
try
{
string tableName = GetTableName(typeof(T));
string sql = String.Format("SELECT * FROM {0} WHERE {1} = @param", tableName, columnName);
return GetConnection().Query<T>(sql, new { param = data });
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return new List<T>();
}
/// <summary>
/// Gets all records in the table matching the supplied type.
/// </summary>
/// <returns>All records in the table matching the supplied type.</returns>
public IEnumerable<T> All<T>()
{
try
{
string tableName = GetTableName(typeof(T));
return GetConnection().Query<T>("SELECT * FROM " + tableName);
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
return new List<T>();
}
/// <summary>
/// Inserts the supplied object into the database. Infers table name from type name.
/// </summary>
public virtual void Insert(object obj)
{
try
{
string tableName = GetTableName(obj);
GetConnection().Insert(null, tableName, obj);
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
}
/// <summary>
/// Updates the supplied object. Infers table name from type name.
/// </summary>
public virtual void Update(object obj)
{
try
{
string tableName = GetTableName(obj);
GetConnection().Update(null, tableName, obj);
}
catch (Exception e)
{
ExceptionHandler(e);
if (m_throwExceptions) throw;
}
}
}
}