-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseDAO.cs
1970 lines (1825 loc) · 72.4 KB
/
BaseDAO.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
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
using Microsoft.Practices.EnterpriseLibrary.Data;
using NetLog.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Text.RegularExpressions;
using System.Collections.Concurrent;
namespace org.wonderly.model.DAO {
/// <summary>
/// The functions in this base class, provide convenience methods for access to database access and operation
/// on the associated data. There are methods with Transaction<typeparamref name="T"/>, Operation<typeparamref name="T"/> and Action<typeparamref name="T"/>
/// signature.
/// </summary>
public class BaseDAO {
private static Logger log = Logger.GetLogger(typeof(BaseDAO).FullName);
public delegate T DelDataSetOperation<T>( DataRow row );
public delegate T DelDataSetOperationIndexed<T>( DataRow row, int idx, int cnt );
public delegate T DelDatabaseTransaction<T>( Database db, DbTransaction trans );
public delegate T DelDatabaseTask<T>( Database db );
public delegate T DelScalarAction<T>( T val );
public delegate void DelDataSetAction( DataRow row );
public delegate void DelDataSetActionIndexed( DataRow row, int idx, int cnt );
public delegate void DelDatabaseActionTransaction( Database db, DbTransaction trans );
public delegate void DelDatabaseActionTask( Database db );
public delegate void DelDatabaseOptionTask( Database db, DbCommand dbCommand );
/// <summary>
/// Get int value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static int intValue( DataRow row, string columnName ) {
return (int)Convert.ChangeType( row[ columnName ], typeof( int ) );
}
/// <summary>
/// Get long value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static long longValue( DataRow row, string columnName ) {
return (long)Convert.ChangeType( row[ columnName ], typeof( long ) );
}
/// <summary>
/// Get float value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static float floatValue( DataRow row, string columnName ) {
return (float)Convert.ChangeType( row[ columnName ], typeof( float ) );
}
/// <summary>
/// Get double value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static double doubleValue( DataRow row, string columnName ) {
return (double)Convert.ChangeType( row[ columnName ], typeof( double ) );
}
/// <summary>
/// Get bool value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static bool boolValue( DataRow row, string columnName ) {
return (bool)Convert.ChangeType( row[ columnName ], typeof( bool ) );
}
/// <summary>
/// Get DateTime value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static DateTime DateTimeValue( DataRow row, string columnName ) {
return (DateTime)Convert.ChangeType( row[ columnName ], typeof( DateTime ) );
}
/// <summary>
/// Get string value for column in data row
/// </summary>
/// <param name="row"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static string stringValue( DataRow row, string columnName ) {
return row[ columnName ].ToString();
}
/// <summary>
/// Get int value for the passed value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int intValue( object value ) {
return (int)Convert.ChangeType( value, typeof( int ) );
}
/// <summary>
/// Get long value for the passed value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static long longValue( object value ) {
return (long)Convert.ChangeType( value, typeof( long ) );
}
/// <summary>
/// Get float value for the passed value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static float floatValue( object value ) {
return (float)Convert.ChangeType( value, typeof( float ) );
}
/// <summary>
/// Get double value for the passed value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static double doubleValue( object value ) {
return (double)Convert.ChangeType( value, typeof( double ) );
}
/// <summary>
/// Get bool value for the passed value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool boolValue( object value ) {
return (bool)Convert.ChangeType( value, typeof( bool ) );
}
/// <summary>
/// A shortened function to construct a KeyValuePair instance.
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public static KeyValuePair<string,object> KV( string key, object val, bool validate = true ) {
//if (validate && val != null && val.ToString().Length > 2)
//{
// val = regexString(val.ToString());
//}
return new KeyValuePair<string,object>( key, val );
}
public static string regexString( string inputString ) {
string outputString = inputString;
Regex tagRegex = new Regex( @"<[^>]+>" );
while( tagRegex.IsMatch( outputString ) ) {
int index1 = outputString.IndexOf( '<' );
int index2 = outputString.IndexOf( '>' );
string filterString = outputString.Substring( index1, index2 - index1 + 1 );
outputString = outputString.Replace( filterString, "" );
}
return outputString;
}
/// <summary>
/// Creates a foreign key index on the passed parameters
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="fromTable">The table the reference is from</param>
/// <param name="toTable">The table the references is to</param>
/// <param name="fromKeyFieldName">The column holding the referenced value in the from table</param>
/// <param name="toKeyFieldName">The column holding the refererred to key in the to table</param>
public static void AddForeignKeyFromToOnKey( Database db, DbTransaction trans, string fromTable, string toTable, string fromKeyFieldName, string toKeyFieldName ) {
Update(db, trans, @"
ALTER TABLE `"+fromTable+@"`
ADD FOREIGN KEY FK_"+fromKeyFieldName+"_"+fromTable+"_"+toTable + " ("+fromKeyFieldName+") references `"+toTable+"` ("+toKeyFieldName+@")
");
}
/// <summary>
/// The types of index keys to use in CreateNewIndexIfNotExists
/// </summary>
public enum IndexType { INDEX_UNIQUE, INDEX_KEY };
/// <summary>
/// Create an index with the passed parameters if it does not already exist. If it
/// does exist, do nothing.
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="table"></param>
/// <param name="type"></param>
/// <param name="keys"></param>
/// <returns>true if the index was created, false if it already existed</returns>
public static bool CreateNewIndexIfNotExists( Database db, DbTransaction trans, string table, IndexType type, params string[] keys ) {
string typestr = type == IndexType.INDEX_UNIQUE ? "unique" : "";
string prefstr = type == IndexType.INDEX_UNIQUE ? "UNQ" : "IDX";
string fieldstr = "";
string fieldlist = "";
foreach( string fld in keys ) {
if( fieldstr.Length > 0 )
fieldstr += "_";
if( fieldlist.Length > 0 )
fieldlist += ",";
fieldstr += fld.Split(' ')[ 0 ].Replace("`", "");
fieldlist += fld;
}
string indexname = prefstr + "_" + table + "_" + fieldstr;
int haveIndex = DataSetActionWith(db, trans,
@"SHOW INDEX FROM "+table+" WHERE KEY_NAME = @indexName",
KV("indexName", indexname)).Tables[ 0 ].Rows.Count;
int maxIndexLen = 64;
if( indexname.Length > maxIndexLen ) {
string origIndex = indexname;
string rest = indexname.Substring( maxIndexLen-6 );
indexname = indexname.Substring( 0, maxIndexLen-6 ) + "_" +
( Math.Abs( ( indexname + rest ).GetHashCode() ) % 100000 ).ToString();
log.warning("index name, \"{0}\" was too long ({1} of {2} chars), using \"{3}\" instead",
origIndex, origIndex.Length, maxIndexLen, indexname );
}
string sql = @"CREATE " + typestr + " INDEX "+
indexname+" ON "+table+"("+fieldlist+");";
if( haveIndex == 0 ) {
log.info("Creating new index: {0}", sql);
Update(db, trans, sql);
return true;
}
log.info("Already have index for {0}", indexname);
return false;
}
/// <summary>
/// Delete an index with the passed parameters if it already exist. If it
/// does exist, do nothing.
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="table"></param>
/// <param name="type"></param>
/// <param name="keys"></param>
/// <returns>true if the index was deleted, false if it already was gone</returns>
public static bool DeleteIndexIfExists( Database db, DbTransaction trans, string table, IndexType type, params string[] keys ) {
string typestr = type == IndexType.INDEX_UNIQUE ? "unique" : "";
string prefstr = type == IndexType.INDEX_UNIQUE ? "UNQ" : "IDX";
string fieldstr = "";
string fieldlist = "";
foreach( string fld in keys ) {
if( fieldstr.Length > 0 )
fieldstr += "_";
if( fieldlist.Length > 0 )
fieldlist += ",";
fieldstr += fld.Split( ' ' )[ 0 ].Replace( "`", "" );
fieldlist += fld;
}
string indexname = prefstr + "_" + table + "_" + fieldstr;
int haveIndex = DataSetActionWith( db, trans,
@"SHOW INDEX FROM " + table + " WHERE KEY_NAME = @indexName",
KV( "indexName", indexname ) ).Tables[ 0 ].Rows.Count;
string sql = @"ALTER TABLE `"+table+"` DROP INDEX " +
indexname +";";
if( haveIndex == 1 ) {
log.info( "Dropping index: {0}", sql );
Update( db, trans, sql );
return true;
}
log.info( "Do not have an index named {0}, cannot delete", indexname );
return false;
}
/// <summary>
/// Check for the existance of a function in the schema
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="function"></param>
/// <param name="schema"></param>
/// <returns></returns>
public static bool FunctionExistsInSchema( Database db, DbTransaction trans, string function, string schema ) {
return DataRowExistsWith(db, trans, @"
SELECT * FROM information_schema.routines p WHERE routine_schema = @schema AND routine_name = @routine",
KV("schema", schema),
KV("routine", function ));
}
/// <summary>
/// Get a dataset as a mapped set of name/value pairs in a dictionary using a delegate to create the KeyValuePair objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="V"></typeparam>
/// <param name="sql"></param>
/// <param name="rvc"></param>
/// <returns></returns>
public static Dictionary<T, V> MappedDataSet<T, V>( string sql, DelDataSetOperation<KeyValuePair<T, V>> rvc ) {
return MappedDataSet(sql, ( DataRow row, int idx, int count ) => {
return rvc(row);
});
}
/// <summary>
/// Get a dataset as a mapped set of name/value pairs in a dictionary using a delegate to create the KeyValuePair objects, with parameters to the dataset query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="V"></typeparam>
/// <param name="sql"></param>
/// <param name="rvc"></param>
/// <param name="args"></param>
/// <returns></returns>
public static Dictionary<T, V> MappedDataSetWith<T, V>( string sql, DelDataSetOperation<KeyValuePair<T, V>> rvc, params KeyValuePair<string, object>[] args ) {
return MappedDataSetWith(sql, ( DataRow row, int idx, int count ) => {
return rvc(row);
}, args);
}
/// <summary>
/// Get a dataset as a mapped set of name/value pairs in a dictionary using a delegate to create the KeyValuePair objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="V"></typeparam>
/// <param name="sql"></param>
/// <param name="rvc"></param>
/// <returns></returns>
public static Dictionary<T, V> MappedDataSet<T, V>( string sql, DelDataSetOperationIndexed<KeyValuePair<T, V>> rvc ) {
Dictionary<T,V> dict = new Dictionary<T, V>();
List<KeyValuePair<T,V>> v = ListForDataSet<KeyValuePair<T, V>>(
DataSetAction(sql),
( DataRow row, int idx, int count ) => {
return rvc(row, idx, count);
});
foreach( KeyValuePair<T,V> kp in v ) {
dict.Add(kp.Key, kp.Value);
}
return dict;
}
/// <summary>
/// Get a dataset as a mapped set of name/value pairs in a dictionary using a delegate to create the KeyValuePair objects, with parameters to the dataset query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="V"></typeparam>
/// <param name="sql"></param>
/// <param name="rvc"></param>
/// <param name="args"></param>
/// <returns>returns the dictionary created by 'rvc' as envoked with all returned rows</returns>
public static Dictionary<T, V> MappedDataSetWith<T, V>( string sql, DelDataSetOperationIndexed<KeyValuePair<T, V>> rvc,
params KeyValuePair<string, object>[] args ) {
Dictionary<T,V> dict = new Dictionary<T, V>();
List<KeyValuePair<T,V>> v = ListForDataSet<KeyValuePair<T, V>>(
DataSetActionWith(sql, args),
( DataRow row, int idx, int count ) => {
return rvc(row, idx, count);
});
foreach( KeyValuePair<T,V> kp in v ) {
dict.Add(kp.Key, kp.Value);
}
return dict;
}
/// <summary>
/// Check if there are any rows returned from the passed transaction
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="sqlCommand"></param>
/// <param name="args"></param>
/// <returns>true if there is at least one row returned, false if not</returns>
public static bool DataRowExistsWith( Database db, DbTransaction trans, string sqlCommand, params KeyValuePair<string, object>[] args ) {
using( DbCommand dbCommand = db.GetSqlStringCommand( sqlCommand ) ) {
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
AddInParameters( db, dbCommand, args );
DataSet ds = db.ExecuteDataSet( dbCommand );
log.fine( "DataRowExistsWith( {0} ): {1}", sqlCommand, ds.Tables[ 0 ].Rows.Count );
return ds.Tables[ 0 ].Rows.Count > 0;
}
}
/// <summary>
/// Get the first DataSet element from the query with parameters, or null.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="nullValue">The appropriate null value to return when there are no rows, must be null</param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <returns></returns>
public static T FirstDataSetElementOrNullWith<T>( T nullValue, string sqlCommand, DelDataSetOperationIndexed<T> act,
params KeyValuePair<string, object>[] args ) {
if( nullValue != null ) {
log.warning("non null value {0} in this API should be using FirstDataSetElementOrDefaultWith()", nullValue);
}
return DataSetElementOrDefaultAt<T>( nullValue, Transaction<DataSet>(( Database db, DbTransaction trans ) => {
using (DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand))
{
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
AddInParameters(db, dbCommand, args);
return db.ExecuteDataSet(dbCommand);
}
}), 0, act);
}
/// <summary>
/// Get first result row or throw KeyNotFoundException
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <exception cref="KeyNotFoundException">When there are no rows returned</exception>
/// <returns></returns>
public static T FirstDataSetElementOrMissingKeyWith<T>( string sqlCommand, DelDataSetOperation<T> act,
params KeyValuePair<string, object>[] args) {
return DataSetElementOrMissingKeyAt<T>( Transaction<DataSet>((Database db, DbTransaction trans) => {
return DataSetActionWith(db, trans, sqlCommand, args);
}), 0, act);
}
/// <summary>
/// Get first result row or throw KeyNotFoundException
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <exception cref="KeyNotFoundException">When there are no rows returned</exception>
/// <returns></returns>
public static T FirstDataSetElementOrMissingKeyWith<T>( Database db, DbTransaction trans, string sqlCommand, DelDataSetOperation<T> act,
params KeyValuePair<string, object>[] args) {
return DataSetElementOrMissingKeyAt<T>( DataSetAction(db, trans, sqlCommand), 0, act);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="nullValue"></param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <returns></returns>
public static T FirstDataSetElementOrNullWith<T>( Database db, DbTransaction trans, T nullValue, string sqlCommand, DelDataSetOperationIndexed<T> act,
params KeyValuePair<string, object>[] args ) {
if( nullValue != null ) {
log.warning( "non null value {0} in this API should be using FirstDataSetElementOrDefaultWith()", nullValue );
}
return DataSetElementOrDefaultAt<T>( nullValue, DataSetActionWith( db, trans, sqlCommand, args ), 0, act );
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="nullValue"></param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <returns></returns>
public static T FirstDataSetElementOrNull<T>( Database db, DbTransaction trans, T nullValue, string sqlCommand, DelDataSetOperationIndexed<T> act ) {
if( nullValue != null ) {
log.warning("non null value {0} in this API should be using FirstDataSetElementOrDefaultWith()", nullValue);
}
return DataSetElementOrDefaultAt<T>(nullValue, DataSetAction(db, trans, sqlCommand), 0, act);
}
private static IsolationLevel databaseIsolationLevel;
private static bool isolationLevelSet;
public static IsolationLevel DatabaseIsolationLevel {
get {
if (isolationLevelSet) {
return databaseIsolationLevel;
}
// The default isolation level
return IsolationLevel.RepeatableRead;
}
set {
databaseIsolationLevel = value;
isolationLevelSet = true;
}
}
/// <summary>
/// A global behavior boolean which turns On or Off, the use of timeouts on all transactions created within this
/// class. This is used for database schema updates or other places where timeouts are not needed and can, in fact,
/// break the desired behavior of a long running transaction.
/// </summary>
public static bool UseDatabaseCommandTimeout { get; set; }
private static int databaseCommandTimeout;
private static bool databaseCommandTimeoutSet;
/// <summary>
///
/// </summary>
public static int DatabaseCommandTimeout {
get {
if( databaseCommandTimeoutSet ) {
return databaseCommandTimeout;
}
if( UseDatabaseCommandTimeout ) {
string str = ConfigurationManager.AppSettings[ "Database:TransactionTimeout" ];
if( str != null ) {
return databaseCommandTimeout = int.Parse(str);
}
return 900; // 15 minutes by default.
}
// DbCommand.CommandTimeout documentation says that 0 should mean no timeout
return 0;
}
set {
databaseCommandTimeout = value;
databaseCommandTimeoutSet = true;
}
}
/// <summary>
/// Get the first row value for the returned dataset or the passed default value with parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue">must be non-null</param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <returns></returns>
public static T FirstDataSetElementOrDefaultWith<T>( T defaultValue, string sqlCommand, DelDataSetOperationIndexed<T> act, params KeyValuePair<string,object>[] args ) {
if( defaultValue == null ) {
log.warning("null value {0} in this API should be using FirstDataSetElementOrNullWith()", "defaultValue");
}
return Transaction<T>(( Database db, DbTransaction trans ) =>
FirstDataSetElementOrDefaultWith<T>(db, trans, defaultValue, sqlCommand, act, args)
);
}
/// <summary>
/// Get the first row value for the returned dataset or the passed default value with parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="defaultValue"></param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <param name="args"></param>
/// <returns></returns>
public static T FirstDataSetElementOrDefaultWith<T>( Database db, DbTransaction trans, T defaultValue, string sqlCommand, DelDataSetOperationIndexed<T> act, params KeyValuePair<string, object>[] args) {
if (defaultValue == null) {
log.warning("null value {0} in this API should be using FirstDataSetElementOrNullWith()", "defaultValue");
}
return DataSetElementOrDefaultAt<T>(defaultValue, DataSetActionWith(db, trans, sqlCommand, args), 0, act);
}
/// <summary>
/// Get the first row value for the returned dataset or the passed default value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="sqlCommand"></param>
/// <param name="act"></param>
/// <returns></returns>
public static T FirstDataSetElementOrDefault<T>( T defaultValue, string sqlCommand, DelDataSetOperationIndexed<T> act ) {
return FirstDataSetElementOrDefaultWith<T>( defaultValue, sqlCommand, act );
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="dataSet"></param>
/// <param name="act"></param>
/// <returns></returns>
public static T FirstDataSetElementOrDefault<T>( T defaultValue, DataSet dataSet, DelDataSetOperation<T> act ) {
return DataSetElementOrDefaultAt<T>(defaultValue, dataSet, 0, act);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="dataSet"></param>
/// <param name="act"></param>
/// <returns></returns>
public static T FirstDataSetElementOrDefault<T>( T defaultValue, DataSet dataSet, DelDataSetOperationIndexed<T> act ) {
return DataSetElementOrDefaultAt<T>(defaultValue, dataSet, 0, act);
}
/// <summary>
/// Execute the passed action on the indicated row of the passed dataset or return the default value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="ds"></param>
/// <param name="rowIdx"></param>
/// <param name="act"></param>
public static T DataSetElementOrDefaultAt<T>(T defaultValue, DataSet ds, int rowIdx, DelDataSetOperationIndexed<T> act) {
int cnt = ds.Tables[ 0 ].Rows.Count;
if( cnt <= rowIdx )
return defaultValue;
return act( ds.Tables[ 0 ].Rows[ rowIdx ], rowIdx, cnt );
}
/// <summary>
/// If there is a row at rowIdx, pass it to 'act' and return the result value,
/// otherwise, return defaultValue when there is no such row.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="ds"></param>
/// <param name="rowIdx"></param>
/// <param name="act"></param>
/// <returns></returns>
public static T DataSetElementOrDefaultAt<T>(T defaultValue, DataSet ds, int rowIdx, DelDataSetOperation<T> act) {
int cnt = ds.Tables[ 0 ].Rows.Count;
if( cnt <= rowIdx )
return defaultValue;
return act( ds.Tables[ 0 ].Rows[ rowIdx ] );
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue"></param>
/// <param name="ds"></param>
/// <param name="rowIdx"></param>
/// <param name="act"></param>
/// <exception cref="KeyNotFoundException">When the requested row does not exist</exception>
/// <returns></returns>
public static T DataSetElementOrMissingKeyAt<T>( DataSet ds, int rowIdx, DelDataSetOperation<T> act) {
int cnt = ds.Tables[0].Rows.Count;
if (cnt <= rowIdx)
throw new KeyNotFoundException(string.Format("No row at index {0} for DataSet with {1} items", rowIdx, ds.Tables[0].Rows.Count ) );
return act(ds.Tables[0].Rows[rowIdx]);
}
/// <summary>
/// Use this to create lists of values from columns or combinations/functions on columns in a DataSet.
/// The simplest example would be getting the 'name' values from a table as shown here.
///
/// List<typeparamref name="string"/> values = ForDataSet<typeparamref name="string"/>( DataSetAction( "select name from table"), (DataRow row) ==> row["name"].ToString() );
///
/// A more complex example might include manipulation of the value.
///
/// List<typeparamref name="string"/> values = ForDataSet<typeparamref name="string"/>( DataSetAction( "select name from table"), (DataRow row) ==> {
/// string nm = row["name"].ToString();
/// // nm is of the form "text-data" and we just want "text"
/// return nm.Substring( 0, nm.LastIndexOf('-') );
/// }
/// );
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ds"></param>
/// <param name="dos"></param>
/// <returns></returns>
public static List<T> ListForDataSet<T>( DataSet ds, DelDataSetOperation<T> dos ) {
List<T> l = new List<T>();
int cnt = ds.Tables[ 0 ].Rows.Count;
for( int i = 0; i < cnt; ++i ) {
l.Add(dos(ds.Tables[ 0 ].Rows[ i ]));
}
return l;
}
/// <summary>
/// This method includes a delegate signature which includes the index of the current row and the total row count.
///
/// List<typeparamref name="string"/> values = ForDataSet<typeparamref name="string"/>( DataSetAction( "select name from table"), (DataRow row, int row, int count) ==> {
/// showprogress( row, count );
/// return row["name"].ToString();
/// }
/// );
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ds"></param>
/// <param name="dos"></param>
/// <returns></returns>
public static List<T> ListForDataSet<T>( DataSet ds, DelDataSetOperationIndexed<T> dos ) {
List<T> l = new List<T>();
int cnt = ds.Tables[ 0 ].Rows.Count;
for( int i = 0; i < cnt; ++i ) {
l.Add(dos(ds.Tables[ 0 ].Rows[ i ], i, cnt ));
}
return l;
}
/// <summary>
/// This method provides the ability to act on each row in a dataset to perform some function.
///
/// AcrossDataSet( DataSetAction("select name from table"), (DataRow row) => {
/// ProcessData( row["name"].ToString() );
/// }
/// );
///
/// or more simply when there is a single function call:
///
/// AcrossDataSet( DataSetAction("select name from table"),
/// (DataRow row) => ProcessData( row["name"].ToString() ) );
///
/// </summary>
/// <param name="ds"></param>
/// <param name="dos"></param>
public static void AcrossDataSet( DataSet ds, DelDataSetAction dos ) {
for( int i = 0; i < ds.Tables[ 0 ].Rows.Count; ++i ) {
dos(ds.Tables[ 0 ].Rows[ i ]);
}
}
/// <summary>
/// This method provides the ability to act on each row in a dataset to perform some function
/// with the row and count of rows provided.
///
/// AcrossDataSet( DataSetAction("select name from table"), (DataRow row, int row, int count) => {
/// ProcessData( row["name"].ToString(), row, count );
/// }
/// );
///
/// or more simply when there is a single function call:
///
/// AcrossDataSet( DataSetAction("select name from table"),
/// (DataRow row) => ProcessData( row["name"].ToString(), row, count ) );
/// </summary>
/// <param name="ds"></param>
/// <param name="dos"></param>
public static void AcrossDataSet( DataSet ds, DelDataSetActionIndexed dos ) {
int cnt = ds.Tables[ 0 ].Rows.Count;
for( int i = 0; i < cnt; ++i ) {
DataRow row = ds.Tables[ 0 ].Rows[ i ];
dos( row, i, cnt );
}
}
/// <summary>
/// Perform an operation with transactional control
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="oper"></param>
/// <returns></returns>
public static T Transaction<T>( DelDatabaseTransaction<T> oper, string descr = "Transaction" ) {
Database db = null;
try {
db = CreateDatabase();
using(DbConnection conn = db.CreateConnection() ) {
conn.Open();
using( DbTransaction trans = conn.BeginTransaction( DatabaseIsolationLevel ) ) {
try {
log.fine( "Starting transaction with Isolation: {0}", trans.IsolationLevel );
T v = oper( db, trans );
trans.Commit();
return v;
} catch {
trans.Rollback();
throw;
}
};
};
} catch( Exception ex ) {
log.fine( ex );
throw;
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="databaseName"></param>
/// <param name="oper"></param>
/// <returns></returns>
public static T Transaction<T>( string databaseName, DelDatabaseTransaction<T> oper, string descr = "Transaction" ) {
Database db = null;
try {
db = CreateDatabase( databaseName );
using(DbConnection conn = db.CreateConnection() ) {
conn.Open();
using( DbTransaction trans = conn.BeginTransaction( DatabaseIsolationLevel ) ) {
try {
log.fine( "Starting transaction with Isolation: {0}", trans.IsolationLevel );
T v = oper( db, trans );
trans.Commit();
return v;
} catch {
trans.Rollback();
throw;
}
};
}
} catch( Exception ex ) {
log.fine( ex );
throw;
}
}
/// <summary>
/// Create a DataSet for a simple query
/// </summary>
/// <param name="sqlCommand"></param>
/// <returns></returns>
public static DataSet DataSetAction( string sqlCommand ) {
return Transaction<DataSet>(( Database db, DbTransaction trans ) => {
return DataSetAction(db, trans, sqlCommand);
}, "DataSetAction");
}
/// <summary>
///
/// </summary>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="sqlCommand"></param>
/// <returns></returns>
public static DataSet DataSetAction( Database db, DbTransaction trans, string sqlCommand, params KeyValuePair<string, object>[] args ) {
using( DbCommand dbCommand = db.GetSqlStringCommand( sqlCommand ) ) {
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
AddInParameters( db, dbCommand, args );
return db.ExecuteDataSet( dbCommand, trans );
}
}
/// <summary>
/// Run a query with a list of objects to be included as a comma separated list. To use this, the sqlString
/// value needs to contains a "special" formatted string which will be replaced with the comma separated list
/// of values.
///
/// If the method is called as:
///
/// List<string> myList = new List<string>();
/// myList.Add("item1");
/// myList.Add("item2");
/// myList.Add("item3");
/// DataSetActionIncluding<string>( db, trans, "select * from table where colname in (@LIST_items)",
/// "items", myList );
///
/// then the sql statement will be rewritten to read
///
/// "select * from table where colname in (@items0,@items1,@items2)"
///
/// and then the db.GetSqlStringCommand() call will be used to get the DbCommand. Then, the parameter values
/// will be added with Database.AddInParameter().
///
/// </summary>
/// <typeparam name="T">Provide a type qualifier to manage that the list type doesn't change</typeparam>
/// <param name="db"></param>
/// <param name="trans"></param>
/// <param name="sqlCommand"></param>
/// <param name="ofName"></param>
/// <param name="items"></param>
/// <returns></returns>
public static DataSet DataSetActionIncluding<T>(Database db, DbTransaction trans, string sqlCommand, string ofName, List<T> items) {
sqlCommand = ReplaceListInStatement<T>(sqlCommand, ofName, items);
using (DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand)) {
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
AddInValuesForList<T>(db, dbCommand, ofName, items);
return db.ExecuteDataSet(dbCommand, trans);
}
}
/// <summary>
/// Provide name of parameter at idx offset in list, named, 'name'.
/// </summary>
/// <param name="sqlCommand"></param>
/// <param name="idx"></param>
/// <param name="name"></param>
/// <returns></returns>
public delegate string DelIndexNamesProvider( string sqlCommand, int idx, string name );
/// <summary>
/// Add the data values for the specified parameter at idx offset in list, named, 'name'.
/// </summary>
/// <param name="db"></param>
/// <param name="cmd"></param>
/// <param name="idx"></param>
/// <param name="name"></param>
public delegate void DelIndexListProvider( Database db, DbCommand cmd, int idx, string name );
/// <summary>
/// This method provides a mechanism for substituting multiple lists of objects into
/// a SQL statement. The typical use of this would be something like the following:
///
/// List<string> field1List;
/// List<int> field2List;
/// DataSet ds = DataSetActionIncludingMulti( db, trans, @"
/// select * from table1 where field1 in (@LIST_field1)
/// and field2 in (@LIST_field2)",
/// /* number of lists */ 2,
/// /* replace name lists in sql statement*/( sql, idx, name ) {
/// if( name.equals("field1") )
/// return BaseDAO.ReplaceListInStatement<string>( sql, "field1", field1List );
/// return BaseDAO.ReplaceListInStatement<int>( sql, "field2", field2List );
/// },
/// /* add values in lists */ (db, dbcmd, idx, name ) {
/// if( name.equals("field1") )
/// BaseDAO.AddInValuesForList<string>( db, cmd, "field1", field1List );
/// BaseDAO.AddInValuesForList<int>( db, cmd, "field2", field2List );
/// });
/// </summary>
///
/// <param name="db">The database instance to use</param>
/// <param name="trans">The transaction to use</param>
/// <param name="sqlCommand">the base SQL statement</param>
/// <param name="itemNames">the names of each type of item having an "in" clause</param>
/// <param name="names">the names provider callback delegate</param>
/// <param name="list">the values provided callback delegate</param>
/// <param name="args">Any other parameters to the SQL query that need to be added as values</param>
/// <returns>The result DataSet from the database query</returns>
public static DataSet DataSetActionIncludingMulti( Database db, DbTransaction trans, string sqlCommand, List<string> itemNames,
DelIndexNamesProvider names, DelIndexListProvider list, params KeyValuePair<string, object>[] args ) {
for( int i = 0; i < itemNames.Count; ++i ) {
sqlCommand = names( sqlCommand, i, itemNames[ i ] );
}
using( DbCommand dbCommand = db.GetSqlStringCommand( sqlCommand ) ) {
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
for( int i = 0; i < itemNames.Count; ++i ) {
list( db, dbCommand, i, itemNames[ i ] );
}
AddInParameters( db, dbCommand, args );
return db.ExecuteDataSet( dbCommand, trans );
}
}
public static int DataSetUpdateIncludingMulti( Database db, DbTransaction trans, string sqlCommand, List<string> itemNames,
DelIndexNamesProvider names, DelIndexListProvider list, params KeyValuePair<string, object>[] args ) {
for( int i = 0; i < itemNames.Count; ++i ) {
sqlCommand = names( sqlCommand, i, itemNames[ i ] );
}
using( DbCommand dbCommand = db.GetSqlStringCommand( sqlCommand ) ) {
dbCommand.Transaction = trans;
dbCommand.CommandTimeout = DatabaseCommandTimeout;
for( int i = 0; i < itemNames.Count; ++i ) {
list( db, dbCommand, i, itemNames[ i ] );
}
AddInParameters( db, dbCommand, args );
return db.ExecuteNonQuery( dbCommand, trans );
}
}
/// <summary>
/// Populates parameter values into a SQL command string as @ofNameN, where N is the index into
/// the items list. Can be used for an 'in' clause or other place where multiple values are included
/// in a SQL command string.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="dbCommand"></param>
/// <param name="ofName"></param>
/// <param name="items"></param>
public static void AddInValuesForList<T>(Database db, DbCommand dbCommand, string ofName, List<T>items ) {
for( int i = 0; i < items.Count; ++i ) {
// object seems to work correctly for every type
// except DateTime and DateTimeOffset types which
// need explicit typing to not be converted to
// string values which then don't parse correctly
// by the SQL statement parser.
DbType type = DbType.Object;
if( items[ i ] is DateTime ) {
type = DbType.DateTime;