-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbHelper.cs
330 lines (273 loc) · 9.73 KB
/
DbHelper.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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
namespace DbHelperNet
{
public class DbHelper : IDisposable
{
private string _connectionString;
public string connectionString
{
get
{
if (string.IsNullOrEmpty(_connectionString))
{
_connectionString = "Host=localhost;Username=postgres;Password=postgres;Database=db";
}
return _connectionString;
}
}
public IEnumerable<IDictionary<string, object>> Read(string sql, params object[] parms)
{
var _toReturn = new List<IDictionary<string, object>>();
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var dic = Enumerable.Range(0, reader.FieldCount)
.ToDictionary(reader.GetName, reader.GetValue);
_toReturn.Add(dic);
}
}
}
}
return _toReturn;
}
public IEnumerable<dynamic> ReadDynamic(string sql, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var reader = command.ExecuteReader())
{
var fieldNames = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
foreach (IDataRecord row in reader)
{
var expando = new ExpandoObject() as IDictionary<string, object>;
foreach (var fieldName in fieldNames)
{
expando[fieldName] = row[fieldName];
}
yield return expando;
}
}
}
}
}
public IEnumerable<IDictionary<string, object>> Read(string sql)
{
return Read(sql, null);
}
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> mapper, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return mapper(reader);
}
}
}
}
}
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> mapper)
{
return Read(sql, mapper, null);
}
public object Scalar(string sql, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
return command.ExecuteScalar();
}
}
}
public void Insert(string sql, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
command.ExecuteNonQuery();
}
}
}
public int Update(string sql, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
return command.ExecuteNonQuery();
}
}
}
public int Delete(string sql, params object[] parms)
{
return Update(sql, parms);
}
public int Delete(string sql)
{
return Update(sql, null);
}
private DbConnection CreateConnection()
{
var connection = new NpgsqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
private DbCommand CreateCommand(string sql, DbConnection conn, params object[] parms)
{
var command = conn.CreateCommand();
command.CommandText = sql;
command.AddParameters(parms);
return command;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: descartar estado gerenciado (objetos gerenciados).
// Fechar a connection
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
private bool disposedValue = false; // Para detectar chamadas redundantes
}
internal static class DbExtentions
{
public static void AddParameters(this DbCommand command, object[] parms)
{
if (parms != null && parms.Length > 0)
{
for (int i = 0; i < parms.Length; i += 2)
{
string name = parms[i].ToString();
if (parms[i + 1] is string && (string)parms[i + 1] == "")
parms[i + 1] = null;
object value = parms[i + 1] ?? DBNull.Value;
var dbParameter = command.CreateParameter();
dbParameter.ParameterName = name;
dbParameter.Value = value;
command.Parameters.Add(dbParameter);
}
}
}
}
public static class TypeExtentions
{
public static int AsId(this object item, int defaultId = -1)
{
if (item == null)
return defaultId;
int result;
if (!int.TryParse(item.ToString(), out result))
return defaultId;
return result;
}
public static int AsInt(this object item, int defaultInt = default(int))
{
if (item == null)
return defaultInt;
int result;
if (!int.TryParse(item.ToString(), out result))
return defaultInt;
return result;
}
public static double AsDouble(this object item, double defaultDouble = default(double))
{
if (item == null)
return defaultDouble;
double result;
if (!double.TryParse(item.ToString(), out result))
return defaultDouble;
return result;
}
public static string AsString(this object item, string defaultString = default(string))
{
if (item == null || item.Equals(DBNull.Value))
return defaultString;
return item.ToString().Trim();
}
public static DateTime AsDateTime(this object item, DateTime defaultDateTime = default(DateTime))
{
if (item == null || string.IsNullOrEmpty(item.ToString()))
return defaultDateTime;
DateTime result;
if (!DateTime.TryParse(item.ToString(), out result))
return defaultDateTime;
return result;
}
public static bool AsBool(this object item, bool defaultBool = default(bool))
{
if (item == null)
return defaultBool;
return new List<string>() { "yes", "y", "true" }.Contains(item.ToString().ToLower());
}
public static byte[] AsByteArray(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
return Convert.FromBase64String(s);
}
public static string AsBase64String(this object item)
{
if (item == null)
return null;
return Convert.ToBase64String((byte[])item);
}
public static Guid AsGuid(this object item)
{
try
{
return new Guid(item.ToString());
}
catch
{
return Guid.Empty;
}
}
public static byte[] AsByteArray(this object item)
{
if ((item == null) || (item is DBNull))
return null;
return (byte[])item;
}
public static string OrderBy(this string sql, string sortExpression)
{
if (string.IsNullOrEmpty(sortExpression))
return sql;
return sql + " ORDER BY " + sortExpression;
}
public static string CommaSeparate<T, U>(this IEnumerable<T> source, Func<T, U> func)
{
return string.Join(",", source.Select(s => func(s).ToString()).ToArray());
}
}
}