This repository has been archived by the owner on Mar 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Data.cs
474 lines (374 loc) · 14.5 KB
/
Data.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
//#r "System.dll"
//#r "System.Data.dll"
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Dynamic;
using System.Threading.Tasks;
using System.Linq;
public class Startup
{
public async Task<object> Invoke(IDictionary<string, object> parameters)
{
JsParameterCollection pcol = new JsParameterCollection(parameters);
using (DbConnection connection = CreateConnection(pcol.ConnectionString, pcol.ConnectionType))
{
try
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
//If there is only one command then execute it on it's own.
//Otherwise run all commands as a single transaction.
if (pcol.Commands.Count == 1)
{
var com = pcol.Commands[0];
switch (com.type)
{
case JsQueryTypes.query:
return await ExecuteQuery(command, com);
case JsQueryTypes.scalar:
return await ExecuteScalar(command, com);
case JsQueryTypes.command:
return await ExecuteNonQuery(command, com);
case JsQueryTypes.procedure:
return await ExecuteProcedure(command, com);
case JsQueryTypes.procedure_scalar:
return await ExecuteProcedureScalar(command, com);
default:
throw new NotSupportedException("Unsupported type of database command. Only 'query', 'scalar', 'command' and 'procedure' are supported.");
}
}
else
{
return await ExecuteTransaction(connection, command, pcol.Commands);
}
}
}
finally
{
connection.Close();
}
}
}
private DbConnection CreateConnection(string connectionString, JsConnectionTypes type)
{
switch (type)
{
case JsConnectionTypes.oledb:
return new OleDbConnection(connectionString);
case JsConnectionTypes.odbc:
return new OdbcConnection(connectionString);
case JsConnectionTypes.sql:
return new SqlConnection(connectionString);
}
throw new NotImplementedException();
}
private async Task<object> ExecuteQuery(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.CommandText = jsCommand.query;
AddCommandParameters(dbCommand, jsCommand, prev);
using (DbDataReader reader = dbCommand.ExecuteReader())
{
List<object> results = new List<object>();
do
{
results.Add(await ParseReaderRow(reader));
}
while (await reader.NextResultAsync());
jsCommand.result = results;
}
UpdateCommandParameters(dbCommand, jsCommand);
return jsCommand;
}
private async Task<object> ExecuteScalar(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.CommandText = jsCommand.query;
AddCommandParameters(dbCommand, jsCommand, prev);
jsCommand.result = await dbCommand.ExecuteScalarAsync();
UpdateCommandParameters(dbCommand, jsCommand);
return jsCommand;
}
private async Task<object> ExecuteNonQuery(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.CommandText = jsCommand.query;
AddCommandParameters(dbCommand, jsCommand, prev);
jsCommand.result = await dbCommand.ExecuteNonQueryAsync();
UpdateCommandParameters(dbCommand, jsCommand);
return jsCommand;
}
private async Task<object> ExecuteProcedure(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.CommandText = jsCommand.query;
dbCommand.CommandType = CommandType.StoredProcedure;
AddCommandParameters(dbCommand, jsCommand, prev);
jsCommand.result = await dbCommand.ExecuteNonQueryAsync();
UpdateCommandParameters(dbCommand, jsCommand);
return jsCommand;
}
private async Task<object> ExecuteProcedureScalar(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.CommandText = jsCommand.query;
dbCommand.CommandType = CommandType.StoredProcedure;
AddCommandParameters(dbCommand, jsCommand, prev);
jsCommand.result = await dbCommand.ExecuteScalarAsync();
UpdateCommandParameters(dbCommand, jsCommand);
return jsCommand;
}
private async Task<object> ExecuteTransaction(DbConnection connection, DbCommand dbCommand, List<JsCommand> jsCommands)
{
DbTransaction transaction = null;
try
{
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
dbCommand.Transaction = transaction;
object prevResult = null;
foreach (JsCommand jsCommand in jsCommands)
{
switch (jsCommand.type)
{
case JsQueryTypes.command:
await ExecuteNonQuery(dbCommand, jsCommand, prevResult);
break;
case JsQueryTypes.query:
await ExecuteQuery(dbCommand, jsCommand, prevResult);
break;
case JsQueryTypes.scalar:
await ExecuteScalar(dbCommand, jsCommand, prevResult);
break;
case JsQueryTypes.procedure:
await ExecuteProcedure(dbCommand, jsCommand, prevResult);
break;
case JsQueryTypes.procedure_scalar:
await ExecuteProcedureScalar(dbCommand, jsCommand, prevResult);
break;
default:
throw new NotSupportedException("Unsupported type of database command. Only 'query', 'scalar', 'command' and 'procedure' are supported.");
}
prevResult = jsCommand.result;
}
transaction.Commit();
}
catch
{
try
{
transaction.Rollback();
}
catch
{
//Do nothing here; transaction is not active.
}
throw;
}
return jsCommands;
}
private async Task<List<object>> ParseReaderRow(DbDataReader reader)
{
List<object> rows = new List<object>();
IDataRecord row = reader;
while (await reader.ReadAsync())
{
var data = new ExpandoObject() as IDictionary<string, object>;
var result = new object[row.FieldCount];
row.GetValues(result);
for (int i = 0; i < row.FieldCount; i++)
{
Type type = row.GetFieldType(i);
if (result[i] is DBNull)
result[i] = null;
else if (type == typeof(byte[]) || type == typeof(char[]))
result[i] = Convert.ToBase64String((byte[])result[i]);
else if (type == typeof(Guid) || type == typeof(DateTime))
result[i] = result[i].ToString();
else if (type == typeof(IDataReader))
result[i] = "<IDataReader>";
data.Add(row.GetName(i), result[i]);
}
rows.Add(data);
}
return rows;
}
private void AddCommandParameters(DbCommand dbCommand, JsCommand jsCommand, object prev = null)
{
dbCommand.Parameters.Clear();
for (int i = 0; i < jsCommand.@params.Count; i++)
{
JsCommandParameter cp = jsCommand.@params[i];
DbParameter param = dbCommand.CreateParameter();
param.ParameterName = cp.name;
object paramVal = cp.value;
//Check if the parameter is a special $prev parameter.
//If so, then use the prev argument.
if (paramVal != null && paramVal.ToString().ToLower() == "$prev")
paramVal = prev;
if (paramVal == null)
param.Value = DBNull.Value;
else
param.Value = paramVal;
param.Direction = (ParameterDirection)cp.direction;
param.IsNullable = cp.isNullable;
if (cp.precision != null)
param.Precision = (byte)cp.precision;
if (cp.scale != null)
param.Scale = (byte)cp.scale;
if (cp.size != null)
param.Size = (byte)cp.size;
dbCommand.Parameters.Add(param);
}
}
private void UpdateCommandParameters(DbCommand dbCommand, JsCommand jsCommand)
{
foreach (DbParameter param in dbCommand.Parameters)
{
JsCommandParameter jparam = jsCommand.@params.FirstOrDefault(x => x.name == param.ParameterName);
if (jparam == null)
continue;
jparam.value = param.Value;
}
}
}
public enum JsQueryTypes
{
query,
scalar,
command,
procedure,
procedure_scalar
}
public enum JsConnectionTypes
{
oledb,
odbc,
sql
}
public class JsParameterCollection
{
private IDictionary<string, object> _Raw;
public string ConnectionString { get; private set; }
public JsConnectionTypes ConnectionType { get; private set; }
public List<JsCommand> Commands { get; private set; }
public JsParameterCollection(IDictionary<string, object> parameters)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
Commands = new List<JsCommand>();
_Raw = parameters;
ParseRawParameters();
}
private void ParseRawParameters()
{
//Extract the connection string.
ConnectionString = _Raw["constring"].ToString();
if (string.IsNullOrWhiteSpace(ConnectionString))
throw new ArgumentNullException("constring");
//Extract the connection type (optional)
object connectionType = null;
_Raw.TryGetValue("connection", out connectionType);
if (connectionType == null)
connectionType = "oledb";
ConnectionType = (JsConnectionTypes)Enum.Parse(typeof(JsConnectionTypes), connectionType.ToString().ToLower());
//Extract the commands array.
dynamic commands = null;
_Raw.TryGetValue("commands", out commands);
if (commands == null)
throw new ArgumentException("The commands field is required.");
for (int i = 0; i < commands.Length; i++)
{
dynamic com = commands[i];
if (!IsPropertyExist(com, "query"))
throw new ArgumentException("The query field is required on transaction object.");
JsCommand newCom = new JsCommand()
{
query = com.query
};
if (IsPropertyExist(com, "params"))
newCom.rawParameters = com.@params;
else
newCom.rawParameters = new object[] { };
if (IsPropertyExist(com, "type"))
newCom.type = (JsQueryTypes)Enum.Parse(typeof(JsQueryTypes), com.type.ToString().ToLower());
else
newCom.type = JsQueryTypes.command;
Commands.Add(newCom);
}
}
private bool IsPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
}
public class JsCommand
{
public string query { get; set; }
public JsQueryTypes type { get; set; }
public List<JsCommandParameter> @params { get; set; }
public object result { get; set; }
private object[] _rawParameters;
internal object[] rawParameters
{
get
{
return _rawParameters;
}
set
{
_rawParameters = value;
@params = new List<JsCommandParameter>();
//Go through each command parameter and build up the command parameter
//array. Work out wether to use named parameters (@myParam, @myOtherParam)
//or index named parameters (@p1, @p2 ect).
for (int i = 0; i < _rawParameters.Length; i++)
{
dynamic p = _rawParameters[i];
JsCommandParameter cp = new JsCommandParameter();
//Check if it is an expando object
//if it is then extract the name and value from it.
if (p is ExpandoObject)
{
if (IsPropertyExist(p, "name"))
cp.name = p.name.ToString();
else
cp.name = "p" + (i + 1).ToString();
if (IsPropertyExist(p, "value"))
cp.value = p.value;
else
cp.value = null;
try { cp.direction = (int)p.direction; } catch { cp.direction = (int)ParameterDirection.Input; }
try { cp.isNullable = (bool)p.isNullable; } catch { cp.isNullable = true; }
try { cp.precision = (byte)p.precision; } catch { }
try { cp.scale = (byte)p.scale; } catch { }
try { cp.size = (byte)p.size; } catch { }
}
else
{
cp.name = "p" + (i + 1).ToString();
cp.value = p;
}
@params.Add(cp);
}
}
}
private bool IsPropertyExist(dynamic obj, string name)
{
if (obj is ExpandoObject)
return ((IDictionary<string, object>)obj).ContainsKey(name);
return obj.GetType().GetProperty(name) != null;
}
}
public class JsCommandParameter
{
public string name { get; set; }
public object value { get; set; }
public int direction { get; set; }
public bool isNullable { get; set; }
public byte? precision { get; set; }
public byte? scale { get; set; }
public byte? size { get; set; }
}