Repository navigation
Expand file tree
/
Copy pathMyDatabase.cs
More file actions
2098 lines (1794 loc) · 82.7 KB
/
Copy pathMyDatabase.cs
File metadata and controls
2098 lines (1794 loc) · 82.7 KB
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* NPoco 3.0 - A Tiny ORMish thing for your POCO's.
* Copyright 2011-2015. All Rights Reserved.
*
* Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0
*
* Originally created by Brad Robinson (@toptensoftware)
*
* Special thanks to Rob Conery (@robconery) for original inspiration (ie:Massive) and for
* use of Subsonic's T4 templates, Rob Sullivan (@DataChomp) for hard core DBA advice
* and Adam Schroder (@schotime) for lots of suggestions, improvements and Oracle support
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using NPoco.Expressions;
using NPoco.Linq;
using System.Text.RegularExpressions;
#if !DNXCORE50
using System.Configuration;
#endif
namespace NPoco
{
public partial class MyDatabase : IDatabase
{
public const bool DefaultEnableAutoSelect = true;
public MyDatabase()
{
}
static MyDatabase()
{
regexList = new List<Regex> {
new Regex(@"insert[ ]+into[ ]+[\[|`|""]*([_0-9a-zA-Z]+)[\]|`|""]*", RegexOptions.IgnoreCase),
new Regex(@"delete[ ]+from[ ]+[\[|`|""]*([_0-9a-zA-Z]+)[\]|`|""]*", RegexOptions.IgnoreCase),
new Regex(@"update[ ]+[\[|`|""]*([_0-9a-zA-Z]+)[\]|`|""]*", RegexOptions.IgnoreCase),
new Regex(@"select[ ]+.+[ ]+from[ ]+[\[|`|""]*([_0-9a-zA-Z]+)[\]|`|""]*", RegexOptions.IgnoreCase)
};
}
private void ReInit(string connectionString, string providerName, IsolationLevel? isolationLevel, bool enableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = false;
_connectionString = connectionString;
_factory = DbProviderFactories.GetFactory(providerName);
var dbTypeName = (_factory == null ? _sharedConnection.GetType() : _factory.GetType()).Name;
_dbType = DatabaseType.Resolve(dbTypeName, providerName);
_providerName = providerName;
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
public MyDatabase(DbConnection connection)
: this(connection, null, null, DefaultEnableAutoSelect)
{ }
public MyDatabase(DbConnection connection, DatabaseType dbType)
: this(connection, dbType, null, DefaultEnableAutoSelect)
{ }
public MyDatabase(DbConnection connection, DatabaseType dbType, IsolationLevel? isolationLevel)
: this(connection, dbType, isolationLevel, DefaultEnableAutoSelect)
{ }
public MyDatabase(DbConnection connection, DatabaseType dbType, IsolationLevel? isolationLevel, bool enableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = true;
_connectionPassedIn = true;
_sharedConnection = connection;
_connectionString = connection.ConnectionString;
_dbType = dbType ?? DatabaseType.Resolve(_sharedConnection.GetType().Name, null);
_providerName = _dbType.GetProviderName();
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
// Cause it is an external connection ensure that the isolation level matches ours
//using (var cmd = _sharedConnection.CreateCommand())
//{
// cmd.CommandTimeout = CommandTimeout;
// cmd.CommandText = _dbType.GetSQLForTransactionLevel(_isolationLevel);
// cmd.ExecuteNonQuery();
//}
}
#if !DNXCORE50
public MyDatabase(string connectionString, string providerName)
: this(connectionString, providerName, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionString, string providerName, IsolationLevel isolationLevel)
: this(connectionString, providerName, isolationLevel, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionString, string providerName, bool enableAutoSelect)
: this(connectionString, providerName, null, enableAutoSelect)
{ }
public MyDatabase(string connectionString, string providerName, IsolationLevel? isolationLevel, bool enableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = false;
_connectionString = connectionString;
_factory = DbProviderFactories.GetFactory(providerName);
var dbTypeName = (_factory == null ? _sharedConnection.GetType() : _factory.GetType()).Name;
_dbType = DatabaseType.Resolve(dbTypeName, providerName);
_providerName = providerName;
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
public MyDatabase(string connectionString, DatabaseType dbType)
: this(connectionString, dbType, null, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionString, DatabaseType dbType, IsolationLevel? isolationLevel)
: this(connectionString, dbType, isolationLevel, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionString, DatabaseType dbType, IsolationLevel? isolationLevel, bool enableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = false;
_connectionString = connectionString;
_dbType = dbType;
_providerName = _dbType.GetProviderName();
_factory = DbProviderFactories.GetFactory(_dbType.GetProviderName());
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
#endif
public MyDatabase(string connectionString, DatabaseType databaseType, DbProviderFactory provider)
: this(connectionString, databaseType, provider, null, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionString, DatabaseType databaseType, DbProviderFactory provider, IsolationLevel? isolationLevel = null, bool enableAutoSelect = DefaultEnableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = false;
_connectionString = connectionString;
_factory = provider;
_dbType = databaseType ?? DatabaseType.Resolve(_factory.GetType().Name, null);
_providerName = _dbType.GetProviderName();
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
#if !DNXCORE50
public MyDatabase(string connectionStringName)
: this(connectionStringName, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionStringName, IsolationLevel isolationLevel)
: this(connectionStringName, isolationLevel, DefaultEnableAutoSelect)
{ }
public MyDatabase(string connectionStringName, bool enableAutoSelect)
: this(connectionStringName, (IsolationLevel?) null, enableAutoSelect)
{ }
public MyDatabase(string connectionStringName, IsolationLevel? isolationLevel, bool enableAutoSelect)
{
EnableAutoSelect = enableAutoSelect;
KeepConnectionAlive = false;
// Use first?
if (connectionStringName == "") connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
// Work out connection string and provider name
var providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
{
providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
}
else
{
throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'");
}
// Store factory and connection string
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = providerName;
_factory = DbProviderFactories.GetFactory(_providerName);
_dbType = DatabaseType.Resolve(_factory.GetType().Name, _providerName);
_isolationLevel = isolationLevel.HasValue ? isolationLevel.Value : _dbType.GetDefaultTransactionIsolationLevel();
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
#endif
private DatabaseType _dbType;
public DatabaseType DatabaseType { get { return _dbType; } }
public IsolationLevel IsolationLevel { get { return _isolationLevel; } }
private IDictionary<string, object> _data;
public IDictionary<string, object> Data => _data ?? (_data = new Dictionary<string, object>());
// Automatically close connection
public void Dispose()
{
if (KeepConnectionAlive) return;
CloseSharedConnection();
}
// Set to true to keep the first opened connection alive until this object is disposed
public bool KeepConnectionAlive { get; set; }
private bool ShouldCloseConnectionAutomatically { get; set; }
// Open a connection (can be nested)
public IDatabase OpenSharedConnection()
{
OpenSharedConnectionImp(false);
return this;
}
private void OpenSharedConnectionInternal()
{
OpenSharedConnectionImp(true);
}
private void OpenSharedConnectionImp(bool isInternal)
{
if (string.IsNullOrEmpty(this.curTableName))
{
this.curTableName = "default";
foreach (Regex regex in regexList)
{
Match m = regex.Match(curSQL);
if (m.Success)
{
this.curTableName = m.Groups[1].Value;
break;
}
}
}
Db db = DbConfig.GetDb(this.curTableName, this.curOpName);
this.ReInit(db.ConnectionString, db.ProviderName, null, DefaultEnableAutoSelect);
if (_connectionPassedIn && _sharedConnection != null && _sharedConnection.State != ConnectionState.Open)
throw new Exception("You must explicitly open the connection before executing anything when passing in a DbConnection to Database");
if (_sharedConnection != null && _sharedConnection.State != ConnectionState.Broken && _sharedConnection.State != ConnectionState.Closed)
return;
ShouldCloseConnectionAutomatically = isInternal;
_sharedConnection = _factory.CreateConnection();
if (_sharedConnection == null) throw new Exception("SQL Connection failed to configure.");
_sharedConnection.ConnectionString = _connectionString;
if (_sharedConnection.State == ConnectionState.Broken)
{
_sharedConnection.Close();
}
if (_sharedConnection.State == ConnectionState.Closed)
{
_sharedConnection.Open();
_sharedConnection = OnConnectionOpenedInternal(_sharedConnection);
//using (var cmd = _sharedConnection.CreateCommand())
//{
// cmd.CommandTimeout = CommandTimeout;
// cmd.CommandText = _dbType.GetSQLForTransactionLevel(_isolationLevel);
// cmd.ExecuteNonQuery();
//}
}
}
private void CloseSharedConnectionInternal()
{
if (ShouldCloseConnectionAutomatically && _transaction == null)
CloseSharedConnection();
}
// Close a previously opened connection
public void CloseSharedConnection()
{
if (KeepConnectionAlive) return;
if (_transaction != null)
{
_transaction.Dispose();
_transaction = null;
}
if (_sharedConnection == null) return;
OnConnectionClosingInternal(_sharedConnection);
_sharedConnection.Close();
_sharedConnection.Dispose();
_sharedConnection = null;
}
public VersionExceptionHandling VersionException
{
get { return _versionException; }
set { _versionException = value; }
}
// Access to our shared connection
public DbConnection Connection
{
get { return _sharedConnection; }
}
public DbTransaction Transaction
{
get { return _transaction; }
}
public DbParameter CreateParameter()
{
using (var conn = _sharedConnection ?? _factory.CreateConnection())
{
if (conn == null) throw new Exception("DB Connection no longer active and failed to reset.");
using (var comm = conn.CreateCommand())
{
return comm.CreateParameter();
}
}
}
// Helper to create a transaction scope
public ITransaction GetTransaction()
{
return GetTransaction(_isolationLevel);
}
public ITransaction GetTransaction(IsolationLevel isolationLevel)
{
return new Transaction(this, isolationLevel);
}
public void SetTransaction(DbTransaction tran)
{
_transaction = tran;
}
private void OnBeginTransactionInternal()
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("Created new transaction using isolation level of " + _transaction.IsolationLevel + ".");
#endif
OnBeginTransaction();
foreach (var interceptor in Interceptors.OfType<ITransactionInterceptor>())
{
interceptor.OnBeginTransaction(this);
}
}
protected virtual void OnBeginTransaction()
{
}
private void OnAbortTransactionInternal()
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("Rolled back a transaction");
#endif
OnAbortTransaction();
foreach (var interceptor in Interceptors.OfType<ITransactionInterceptor>())
{
interceptor.OnAbortTransaction(this);
}
}
protected virtual void OnAbortTransaction()
{
}
private void OnCompleteTransactionInternal()
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("Committed the transaction");
#endif
OnCompleteTransaction();
foreach (var interceptor in Interceptors.OfType<ITransactionInterceptor>())
{
interceptor.OnCompleteTransaction(this);
}
}
protected virtual void OnCompleteTransaction()
{
}
public void BeginTransaction()
{
BeginTransaction(_isolationLevel);
}
// Start a new transaction, can be nested, every call must be
// matched by a call to AbortTransaction or CompleteTransaction
// Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics
public void BeginTransaction(IsolationLevel isolationLevel)
{
if (_transaction == null)
{
TransactionCount = 0;
OpenSharedConnectionInternal();
_transaction = _sharedConnection.BeginTransaction(isolationLevel);
OnBeginTransactionInternal();
}
if (_transaction != null)
{
TransactionCount++;
}
}
// Abort the entire outer most transaction scope
public void AbortTransaction()
{
TransactionIsAborted = true;
AbortTransaction(false);
}
public void AbortTransaction(bool fromComplete)
{
if (_transaction == null)
{
TransactionIsAborted = false;
return;
}
if (fromComplete == false)
{
TransactionCount--;
if (TransactionCount >= 1)
{
TransactionIsAborted = true;
return;
}
}
if (TransactionIsOk())
_transaction.Rollback();
if (_transaction != null)
_transaction.Dispose();
_transaction = null;
TransactionIsAborted = false;
// You cannot continue to use a connection after a transaction has been rolled back
if (_sharedConnection != null)
{
_sharedConnection.Close();
_sharedConnection.Open();
}
OnAbortTransactionInternal();
CloseSharedConnectionInternal();
}
// Complete the transaction
public void CompleteTransaction()
{
if (_transaction == null)
return;
TransactionCount--;
if (TransactionCount >= 1)
return;
if (TransactionIsAborted)
{
AbortTransaction(true);
return;
}
if (TransactionIsOk())
_transaction.Commit();
if (_transaction != null)
_transaction.Dispose();
_transaction = null;
OnCompleteTransactionInternal();
CloseSharedConnectionInternal();
}
internal bool TransactionIsAborted { get; set; }
internal int TransactionCount { get; set; }
private bool TransactionIsOk()
{
return _sharedConnection != null
&& _transaction != null
&& _transaction.Connection != null
&& _transaction.Connection.State == ConnectionState.Open;
}
// Add a parameter to a DB command
public virtual void AddParameter(DbCommand cmd, object value)
{
// Convert value to from poco type to db type
if (Mappers != null && value != null)
{
value = Mappers.FindAndExecute(x => x.GetParameterConverter(cmd, value.GetType()), value);
}
// Support passed in parameters
var idbParam = value as DbParameter;
if (idbParam != null)
{
idbParam.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
cmd.Parameters.Add(idbParam);
return;
}
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
SetParameterValue(p, value);
cmd.Parameters.Add(p);
}
private void SetParameterValue(DbParameter p, object value)
{
if (value == null)
{
p.Value = DBNull.Value;
return;
}
// Give the database type first crack at converting to DB required type
value = _dbType.MapParameterValue(value);
var dbtypeSet = false;
var t = value.GetType();
var underlyingT = Nullable.GetUnderlyingType(t);
if (t.GetTypeInfo().IsEnum || (underlyingT != null && underlyingT.GetTypeInfo().IsEnum)) // PostgreSQL .NET driver wont cast enum to int
{
p.Value = (int)value;
}
else if (t == typeof(Guid))
{
p.Value = value;
p.DbType = DbType.Guid;
p.Size = 40;
dbtypeSet = true;
}
else if (t == typeof(string))
{
var strValue = value as string;
if (strValue == null)
{
p.Size = 0;
p.Value = String.Empty;
}
else
{
// out of memory exception occurs if trying to save more than 4000 characters to SQL Server CE NText column. Set before attempting to set Size, or Size will always max out at 4000
if (strValue.Length + 1 > 4000 && p.GetType().Name == "SqlCeParameter")
{
p.GetType().GetProperty("SqlDbType").SetValue(p, SqlDbType.NText, null);
}
p.Size = Math.Max(strValue.Length + 1, 4000); // Help query plan caching by using common size
p.Value = value;
}
}
else if (t == typeof(AnsiString))
{
var ansistrValue = value as AnsiString;
if (ansistrValue == null)
{
p.Size = 0;
p.Value = String.Empty;
p.DbType = DbType.AnsiString;
}
else
{
// Thanks @DataChomp for pointing out the SQL Server indexing performance hit of using wrong string type on varchar
p.Size = Math.Max(ansistrValue.Value.Length + 1, 4000);
p.Value = ansistrValue.Value;
p.DbType = DbType.AnsiString;
}
dbtypeSet = true;
}
else if (value.GetType().Name == "SqlGeography") //SqlGeography is a CLR Type
{
p.GetType().GetProperty("UdtTypeName").SetValue(p, "geography", null); //geography is the equivalent SQL Server Type
p.Value = value;
}
else if (value.GetType().Name == "SqlGeometry") //SqlGeometry is a CLR Type
{
p.GetType().GetProperty("UdtTypeName").SetValue(p, "geometry", null); //geography is the equivalent SQL Server Type
p.Value = value;
}
else
{
p.Value = value;
}
if (!dbtypeSet)
{
var dbType = _dbType.LookupDbType(p.Value.GetTheType(), p.ParameterName);
if (dbType.HasValue)
{
p.DbType = dbType.Value;
}
}
}
// Create a command
private DbCommand CreateCommand(DbConnection connection, string sql, params object[] args)
{
return CreateCommand(connection, CommandType.Text, sql, args);
}
public virtual DbCommand CreateCommand(DbConnection connection, CommandType commandType, string sql, params object[] args)
{
if (commandType == CommandType.StoredProcedure)
{
return CreateStoredProcedureCommand(connection, sql, args);
}
// Perform parameter prefix replacements
if (_paramPrefix != "@")
sql = ParameterHelper.rxParamsPrefix.Replace(sql, m => _paramPrefix + m.Value.Substring(1));
sql = sql.Replace("@@", "@"); // <- double @@ escapes a single @
// Create the command and add parameters
DbCommand cmd = connection.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = sql;
cmd.Transaction = _transaction;
foreach (var item in args)
{
AddParameter(cmd, item);
}
// Notify the DB type
_dbType.PreExecute(cmd);
return cmd;
}
protected virtual void OnException(Exception exception)
{
}
// Override this to log/capture exceptions
private void OnExceptionInternal(Exception exception)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("***** EXCEPTION *****" + Environment.NewLine + Environment.NewLine + exception.Message + Environment.NewLine + exception.StackTrace);
System.Diagnostics.Debug.WriteLine("***** LAST COMMAND *****" + Environment.NewLine + Environment.NewLine + LastCommand);
System.Diagnostics.Debug.WriteLine("***** CONN INFO *****" + Environment.NewLine + Environment.NewLine + "Provider: " + _providerName + Environment.NewLine + "Connection String: " + _connectionString + Environment.NewLine + "DB Type: " + _dbType);
#endif
OnException(exception);
foreach (var interceptor in Interceptors.OfType<IExceptionInterceptor>())
{
interceptor.OnException(this, exception);
}
}
protected virtual DbConnection OnConnectionOpened(DbConnection conn)
{
return conn;
}
private DbConnection OnConnectionOpenedInternal(DbConnection conn)
{
var newConnection = OnConnectionOpened(conn);
foreach (var interceptor in Interceptors.OfType<IConnectionInterceptor>())
{
newConnection = interceptor.OnConnectionOpened(this, newConnection);
}
return newConnection;
}
protected virtual void OnConnectionClosing(DbConnection conn)
{
}
private void OnConnectionClosingInternal(DbConnection conn)
{
OnConnectionClosing(conn);
foreach (var interceptor in Interceptors.OfType<IConnectionInterceptor>())
{
interceptor.OnConnectionClosing(this, conn);
}
}
protected virtual void OnExecutingCommand(DbCommand cmd)
{
}
private void OnExecutingCommandInternal(DbCommand cmd)
{
OnExecutingCommand(cmd);
foreach (var interceptor in Interceptors.OfType<IExecutingInterceptor>())
{
interceptor.OnExecutingCommand(this, cmd);
}
}
protected virtual void OnExecutedCommand(DbCommand cmd)
{
}
private void OnExecutedCommandInternal(DbCommand cmd)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(LastCommand);
#endif
OnExecutedCommand(cmd);
foreach (var interceptor in Interceptors.OfType<IExecutingInterceptor>())
{
interceptor.OnExecutedCommand(this, cmd);
}
}
protected virtual bool OnInserting(InsertContext insertContext)
{
return true;
}
private bool OnInsertingInternal(InsertContext insertContext)
{
var result = OnInserting(insertContext);
return result && Interceptors.OfType<IDataInterceptor>().All(x => x.OnInserting(this, insertContext));
}
protected virtual bool OnUpdating(UpdateContext updateContext)
{
return true;
}
private bool OnUpdatingInternal(UpdateContext updateContext)
{
var result = OnUpdating(updateContext);
return result && Interceptors.OfType<IDataInterceptor>().All(x => x.OnUpdating(this, updateContext));
}
protected virtual bool OnDeleting(DeleteContext deleteContext)
{
return true;
}
private bool OnDeletingInternal(DeleteContext deleteContext)
{
var result = OnDeleting(deleteContext);
return result && Interceptors.OfType<IDataInterceptor>().All(x => x.OnDeleting(this, deleteContext));
}
public DbCommand CreateStoredProcedureCommand(DbConnection connection, string name, params object[] args)
{
DbCommand cmd = connection.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = name;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = _transaction;
if (args.Length == 1)
{
var arg = args[0] as DbParameter;
if (arg != null)
{
cmd.Parameters.Add(arg);
}
else
{
var props = args[0].GetType().GetProperties().Select(x => new { x.Name, Value = x.GetValue(args[0], null) }).ToList();
foreach(var item in props)
{
DbParameter param = cmd.CreateParameter();
param.ParameterName = item.Name;
SetParameterValue(param, item.Value);
cmd.Parameters.Add(param);
}
}
}
else
{
cmd.Parameters.AddRange(args.OfType<DbParameter>().ToArray());
}
// Notify the DB type
_dbType.PreExecute(cmd);
return cmd;
}
// Execute a non-query command
public int Execute(string sql, params object[] args)
{
return Execute(new Sql(sql, args));
}
public int Execute(Sql Sql)
{
return Execute(Sql.SQL, CommandType.Text, Sql.Arguments);
}
public int Execute(string sql, CommandType commandType, params object[] args)
{
try
{
this.curSQL = sql;
this.curTableName = "";
this.curOpName = "Write";
OpenSharedConnectionInternal();
using (var cmd = CreateCommand(_sharedConnection, commandType, sql, args))
{
var result = ExecuteNonQueryHelper(cmd);
return result;
}
}
catch (Exception x)
{
OnExceptionInternal(x);
throw;
}
finally
{
CloseSharedConnectionInternal();
}
}
// Execute and cast a scalar property
public T ExecuteScalar<T>(string sql, params object[] args)
{
return ExecuteScalar<T>(new Sql(sql, args));
}
public T ExecuteScalar<T>(Sql Sql)
{
return ExecuteScalar<T>(Sql.SQL, CommandType.Text, Sql.Arguments);
}
public T ExecuteScalar<T>(string sql, CommandType commandType, params object[] args)
{
try
{
this.curSQL = sql;
this.curTableName = "";
this.curOpName = "Read";
OpenSharedConnectionInternal();
using (var cmd = CreateCommand(_sharedConnection, commandType, sql, args))
{
object val = ExecuteScalarHelper(cmd);
if (val == null || val == DBNull.Value)
return default(T);
Type t = typeof(T);
Type u = Nullable.GetUnderlyingType(t);
return (T)Convert.ChangeType(val, u ?? t);
}
}
catch (Exception x)
{
OnExceptionInternal(x);
throw;
}
finally
{
CloseSharedConnectionInternal();
}
}
public bool EnableAutoSelect { get; set; }
// Return a typed list of pocos
public List<T> Fetch<T>(string sql, params object[] args)
{
return Fetch<T>(new Sql(sql, args));
}
public List<T> Fetch<T>(Sql sql)
{
return Query<T>(sql).ToList();
}
public List<T> Fetch<T>()
{
return Fetch<T>("");
}
public void BuildPageQueries<T>(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage)
{
// Add auto select clause
if (EnableAutoSelect)
sql = AutoSelectHelper.AddSelectClause(this, typeof(T), sql);
// Split the SQL
PagingHelper.SQLParts parts;
if (!PagingHelper.SplitSQL(sql, out parts)) throw new Exception("Unable to parse SQL statement for paged query");
sqlPage = _dbType.BuildPageQuery(skip, take, parts, ref args);
sqlCount = parts.sqlCount;
}
// Fetch a page
public Page<T> Page<T>(long page, long itemsPerPage, Sql sql)
{
return Page<T>(page, itemsPerPage, sql.SQL, sql.Arguments);
}
public List<T> Fetch<T>(long page, long itemsPerPage, string sql, params object[] args)
{
return SkipTake<T>((page - 1) * itemsPerPage, itemsPerPage, sql, args);
}
public List<T> Fetch<T>(long page, long itemsPerPage, Sql sql)
{
return SkipTake<T>((page - 1) * itemsPerPage, itemsPerPage, sql.SQL, sql.Arguments);
}
public List<T> SkipTake<T>(long skip, long take, string sql, params object[] args)
{
string sqlCount, sqlPage;
BuildPageQueries<T>(skip, take, sql, ref args, out sqlCount, out sqlPage);
return Fetch<T>(sqlPage, args);
}
public List<T> SkipTake<T>(long skip, long take, Sql sql)
{
return SkipTake<T>(skip, take, sql.SQL, sql.Arguments);
}
public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(Sql Sql)
{
return Dictionary<TKey, TValue>(Sql.SQL, Sql.Arguments);
}
public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(string sql, params object[] args)
{
var newDict = new Dictionary<TKey, TValue>();
bool isConverterSet = false;
Func<object, object> converter1 = x => x, converter2 = x => x;
foreach (var line in Query<Dictionary<string, object>>(sql, args))
{
object key = line.ElementAt(0).Value;
object value = line.ElementAt(1).Value;
if (isConverterSet == false)
{
converter1 = MappingHelper.GetConverter(Mappers, null, typeof(TKey), key.GetType()) ?? (x => x);
converter2 = (value != null ? MappingHelper.GetConverter(Mappers, null, typeof(TValue), value.GetType()) : null) ?? (x => x);
isConverterSet = true;
}
var keyConverted = (TKey)Convert.ChangeType(converter1(key), typeof(TKey));
var valueType = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
var valConv = converter2(value);
var valConverted = valConv != null ? (TValue)Convert.ChangeType(valConv, valueType) : default(TValue);
if (keyConverted != null)
{
newDict.Add(keyConverted, valConverted);
}
}
return newDict;
}
// Return an enumerable collection of pocos
public IEnumerable<T> Query<T>(string sql, params object[] args)
{
return Query<T>(new Sql(sql, args));
}
public IEnumerable<T> Query<T>(Sql Sql)