/
Database.cs
2078 lines (1866 loc) · 79.7 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
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
// ___________________________________________________
//
// © Hi-Integrity Systems 2010. All rights reserved.
// www.hisystems.com.au - Toby Wicks
// ___________________________________________________
//
using System.Collections;
using System;
using System.Data;
using DatabaseObjects;
using System.Diagnostics;
using System.Transactions;
using System.Collections.Generic;
/// --------------------------------------------------------------------------------
/// <summary>
/// Represents a database connection and provides a set of functions that work
/// in conjunction with classes implementing IDatabaseObjects and IDatabaseObject.
/// The Database class automatically generates and executes the required SQL
/// statements to perform common database operations such as saving, deleting
/// searching etc. based on the values returned via the IDatabaseObjects and
/// IDatabaseObject interfaces.
/// Typically, this class is only used when explicitly implementing the IDatabaseObjects
/// and IDatabaseObject interfaces rather than inheriting from DatabaseObjects (or
/// DatabaseObjectsEnumerable) and DatabaseObject.
/// </summary>
/// --------------------------------------------------------------------------------
///
namespace DatabaseObjects
{
public class Database
{
public enum ConnectionType
{
SQLServer,
MicrosoftAccess,
MySQL,
Pervasive,
SQLServerCompactEdition,
HyperSQL
}
private ConnectionController pobjConnection;
private TransactionsClass pobjTransactions;
/// --------------------------------------------------------------------------------
/// <summary>
/// Creates a new Database instance specifying the database to connect to and SQL
/// syntax to use with the database. Each function call of the Database class opens
/// and closes a connection. Therefore, connection pooling should be enabled
/// for optimal performance.
/// </summary>
///
/// <param name="strConnectionString">
/// A database connection string to either a Microsoft Access, SQLServer, Pervasive or MySQL
/// database. For example, 'Provider=Microsoft.Jet.OLEDB.4.0;Data
/// Source=northwind.mdb;Jet OLEDB:Database Password=;'.
/// </param>
///
/// <param name="eConnectionType">
/// Indicates the SQL syntax to generate for the database specified in strConnectionString.
/// </param>
/// --------------------------------------------------------------------------------
///
public Database(string strConnectionString, ConnectionType eConnectionType)
{
pobjConnection = new ConnectionController(strConnectionString, eConnectionType);
pobjTransactions = new TransactionsClass(pobjConnection);
}
/// <summary>
/// Initializes the Database instance with the database connection to utilise.
/// The connection is not opened until it is required.
/// The supplied connection should not be opened.
/// </summary>
/// <param name="objDatabaseConnection">An unopened connection to the database.</param>
/// <remarks></remarks>
public Database(IDbConnection objDatabaseConnection, ConnectionType eConnectionType)
{
pobjConnection = new ConnectionController(objDatabaseConnection, eConnectionType);
pobjTransactions = new TransactionsClass(pobjConnection);
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an instance of an object from the collection using a distinct value (see
/// IDatabaseObjects.DistinctFieldName). If the collection has implemented the
/// IDatabaseObjects.Subset function then the objDistinctValue need only be unique
/// within the collection's subset, not the entire database table.
/// </summary>
///
/// <param name="objCollection">
/// The collection that contains the object.
/// </param>
///
/// <param name="objDistinctValue">
/// The value that uniquely identifies the object within the collection. This is the value
/// of the field defined by the collection's IDatabaseObjects.DistinctFieldName function.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example> Loads a product using a product ID of 123
/// <code>
/// objProduct = objDatabase.Object(NorthwindDB.Products, 123)
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject Object(IDatabaseObjects objCollection, object objDistinctValue)
{
return ObjectFromFieldValues(objCollection, this.ObjectFieldValues(objCollection, objDistinctValue));
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an instance of an object from the collection using a distinct value (see
/// IDatabaseObjects.DistinctFieldName). If the collection has implemented the
/// IDatabaseObjects.Subset function then the objDistinctValue need only be unique
/// within the collection's subset, not the entire database table.
/// Returns Nothing/null if the distinct value does not exist in the database.
/// This feature is what differentiates Database.Object() from Database.ObjectIfExists().
/// </summary>
///
/// <param name="objCollection">
/// The collection that contains the object.
/// </param>
///
/// <param name="objDistinctValue">
/// The value that uniquely identifies the object within the collection. This is the value
/// of the field defined by the collection's IDatabaseObjects.DistinctFieldName function.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example> Loads a product using a product ID of 123
/// <code>
/// objProduct = objDatabase.Object(NorthwindDB.Products, 123)
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject ObjectIfExists(IDatabaseObjects objCollection, object objDistinctValue)
{
SQL.SQLFieldValues objFieldValues = this.ObjectFieldValuesIfExists(objCollection, objDistinctValue);
if (objFieldValues == null)
return null;
else
return ObjectFromFieldValues(objCollection, objFieldValues);
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns the database fields for an object from the collection using a distinct value
/// (see IDatabaseObjects.DistinctFieldName). If the collection has implemented the
/// IDatabaseObjects.Subset function then the objDistinctValue need only be unique
/// within the collection's subset, not the entire database table.
/// This is typically used to interogate the database fields before loading the
/// object with a call to ObjectFromFieldValues.
/// This function is rarely used and generally the Object function suffices.
/// </summary>
///
/// <param name="objCollection">
/// The collection that contains the object.
/// </param>
///
/// <param name="objDistinctValue">
/// The value that uniquely identifies the object within the collection. This is the value
/// of the field defined by the collection's IDatabaseObjects.DistinctFieldName function.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
/// --------------------------------------------------------------------------------
///
public SQL.SQLFieldValues ObjectFieldValues(IDatabaseObjects objCollection, object objDistinctValue)
{
SQL.SQLFieldValues objFieldValues = ObjectFieldValuesIfExists(objCollection, objDistinctValue);
if (objFieldValues == null)
throw new Exceptions.ObjectDoesNotExistException(objCollection, objDistinctValue);
return objFieldValues;
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns the database fields for an object from the collection using a distinct value
/// (see IDatabaseObjects.DistinctFieldName).
/// Returns Nothing/null if the distinct value does not exist.
/// </summary>
/// --------------------------------------------------------------------------------
///
private SQL.SQLFieldValues ObjectFieldValuesIfExists(IDatabaseObjects objCollection, object objDistinctValue)
{
SQL.SQLSelect objSelect = new SQL.SQLSelect();
SQL.SQLConditions objSubset;
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where.Add(objCollection.DistinctFieldName(), SQL.ComparisonOperator.EqualTo, objDistinctValue);
objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
objSelect.Where.Add(objSubset);
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
if (objReader.Read())
return FieldValuesFromDataReader(objCollection, objReader);
else
return null;
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns whether an object exists for the specified distinct value in the collection.
/// </summary>
///
/// <param name="objCollection">
/// The collection that is searched for the distinct value.
/// </param>
///
/// <param name="objDistinctValue">
/// The value to search for in the collection. This is the value of the field defined
/// by the collection's IDatabaseObjects.DistinctFieldName function.
/// </param>
/// --------------------------------------------------------------------------------
///
public bool ObjectExistsByDistinctValue(IDatabaseObjects objCollection, object objDistinctValue)
{
SQL.SQLSelect objSelect = new SQL.SQLSelect();
SQL.SQLConditions objSubset;
objSelect.Tables.Add(objCollection.TableName());
objSelect.Where.Add(objCollection.DistinctFieldName(), SQL.ComparisonOperator.EqualTo, objDistinctValue);
objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
objSelect.Where.Add(objSubset);
using (ConnectionScope objConnection = new ConnectionScope(this))
using (IDataReader objReader = objConnection.Execute(objSelect))
return objReader.Read();
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Extracts the fields to save to the database from the objItem.SaveFields function.
/// The fields are then written to the database using either an SQL INSERT or UPDATE
/// depending on whether the object has already been saved. If the collection has
/// implemented IDatabaseObjects.KeyFieldName then objItem's key is also validated to
/// ensure it is not null and unique within the collection. If objCollection has
/// implemented IDatabaseObjects.Subset then objItem should exist within objCollection.
/// If not, a duplicate key error may occur if the obItem's key is being used in
/// another subset in the same table. If a record is being amended
/// (IDatabaseObject.IsSaved returns true) then the function will "AND" the collection's
/// IDatabaseObjects.Subset conditions and the objItem's IDatabaseObject.DistinctValue
/// value to create the WHERE clause in the UPDATE statement. Therefore, the
/// combination of the IDatabaseObjects.Subset and IDatabaseObject.DistinctValue
/// conditions MUST identify only one record in the table. Otherwise multiple records
/// will be updated with the same data. If data is only inserted and not amended
/// (usually a rare occurance) then this requirement is unnecessary.
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains or will contain the object to save.
/// </param>
///
/// <param name="objItem">
/// The object to save to the database. The values saved to the database are extracted from the
/// SQLFieldValues object returned from IDatabaseObject.SaveFields.
/// </param>
///
/// <example> Saves a product object (Me) to the database.
/// <code>
/// Public Sub Save()
///
/// objDatabase.ObjectSave(NorthwindDB.Products, Me)
///
/// End Sub
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public void ObjectSave(IDatabaseObjects objCollection, IDatabaseObject objItem)
{
SQL.SQLFieldValues objFieldValues;
var objNewGUID = Guid.Empty;
var autoAssignment = MergeDistinctFieldAutoAssignmentAndDistinctFieldAutoIncrements(objCollection);
objFieldValues = objItem.SaveFields();
if (objFieldValues == null)
throw new Exceptions.DatabaseObjectsException(objItem.GetType().Name + " IDatabaseObject.SaveFields not implemented");
//Add the distinct field value if it hasn't been added via the SaveFields sub
if (!objFieldValues.Exists(objCollection.DistinctFieldName()))
{
if (autoAssignment == SQL.FieldValueAutoAssignmentType.None)
objFieldValues.Add(objCollection.DistinctFieldName(), objItem.DistinctValue);
else if (autoAssignment == SQL.FieldValueAutoAssignmentType.NewUniqueIdentifier)
{
//For a new object, with a GUID that should be automatically assigned
//Create a new GUID for the distinct field so that it saved for the INSERT
if (!objItem.IsSaved)
{
objNewGUID = System.Guid.NewGuid();
objFieldValues.Add(objCollection.DistinctFieldName(), objNewGUID);
}
}
}
#if !DEBUG
ItemKeyEnsureValid(objCollection, objItem, objFieldValues);
#endif
using (ConnectionScope objConnection = new ConnectionScope(this))
{
if (objItem.IsSaved)
{
var objUpdate = new SQL.SQLUpdate();
objUpdate.TableName = objCollection.TableName();
objUpdate.Fields.Add(objFieldValues);
objUpdate.Where.Add(objCollection.DistinctFieldName(), SQL.ComparisonOperator.EqualTo, objItem.DistinctValue);
var objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
{
objUpdate.Where.Add(objSubset);
}
objConnection.ExecuteNonQuery(objUpdate);
}
else
{
var objInsert = new SQL.SQLInsert();
objInsert.TableName = objCollection.TableName();
objInsert.Fields = objFieldValues;
objConnection.ExecuteNonQuery(objInsert);
if (autoAssignment == SQL.FieldValueAutoAssignmentType.NewUniqueIdentifier)
objItem.DistinctValue = objNewGUID;
else if (autoAssignment == SQL.FieldValueAutoAssignmentType.AutoIncrement)
objItem.DistinctValue = Connection.ExecuteScalar(new SQL.SQLAutoIncrementValue());
object objRollbackDistinctValue = objItem.DistinctValue;
objItem.IsSaved = true;
if (Transaction.Current != null)
{
Transaction.Current.EnlistVolatile(new TransactionExecuteActionOnRollback(() => objItem.IsSaved = false), EnlistmentOptions.None);
Transaction.Current.EnlistVolatile(new TransactionExecuteActionOnRollback(() => objItem.DistinctValue = objRollbackDistinctValue), EnlistmentOptions.None);
}
}
}
}
/// <summary>
/// Merges the obsolete function DistinctFieldAutoIncrements with the new DistinctFieldAutoAssignment function.
/// </summary>
private SQL.FieldValueAutoAssignmentType MergeDistinctFieldAutoAssignmentAndDistinctFieldAutoIncrements(IDatabaseObjects collection)
{
if (collection.DistinctFieldAutoIncrements())
return SQL.FieldValueAutoAssignmentType.AutoIncrement;
else
return collection.DistinctFieldAutoAssignment();
}
private void ItemKeyEnsureValid(IDatabaseObjects objCollection, IDatabaseObject objItem, SQL.SQLFieldValues objFieldValues)
{
SQL.SQLSelect objSelect;
object objKeyFieldValue;
SQL.SQLConditions objSubset;
//If the key field is set and the key field is specified in the object
if (objCollection.KeyFieldName() != string.Empty && objFieldValues.Exists(objCollection.KeyFieldName()))
{
objKeyFieldValue = ItemKeyFieldValue(objCollection, objItem, objFieldValues);
if (objKeyFieldValue is string)
{
if (String.IsNullOrEmpty((string)objKeyFieldValue))
throw new Exceptions.DatabaseObjectsException(objItem.GetType().Name + " " + objCollection.KeyFieldName() + " field is Null");
}
objSelect = new SQL.SQLSelect();
objSelect.Tables.Add(objCollection.TableName());
objSelect.Fields.Add(objCollection.KeyFieldName());
objSelect.Where.Add(objCollection.KeyFieldName(), SQL.ComparisonOperator.EqualTo, objKeyFieldValue);
objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
objSelect.Where.Add(objSubset);
if (objItem.IsSaved)
objSelect.Where.Add(objCollection.DistinctFieldName(), SQL.ComparisonOperator.NotEqualTo, objItem.DistinctValue);
using (ConnectionScope objConnection = new ConnectionScope(this))
using (IDataReader objReader = objConnection.Execute(objSelect))
if (objReader.Read())
throw new Exceptions.ObjectAlreadyExistsException(objItem, objKeyFieldValue);
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an object from the collection using a unique key value.
/// The key must be unique within the collection. If the collection's
/// IDatabaseObjects.Subset has been implemented then the key need only be unique
/// within the subset specified, not the entire database table.
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains the object.
/// </param>
///
/// <param name="objKey">
/// The key that identifies the object with the collection. The key is the value of
/// the field defined by the collection's IDatabaseObjects.KeyFieldName.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example>
/// <code>
/// Default Public ReadOnly Property Item(ByVal strProductCode As String) As Product
/// Get
///
/// Return objDatabase.ObjectByKey(Me, strProductCode)
///
/// End Get
/// End Property
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject ObjectByKey(IDatabaseObjects objCollection, object objKey)
{
IDatabaseObject objObject = ObjectByKeyIfExists(objCollection, objKey);
if (objObject == null)
throw new Exceptions.ObjectDoesNotExistException(objCollection, objKey);
return objObject;
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an object from the collection using a unique key value.
/// The key must be unique within the collection. If the collection's
/// IDatabaseObjects.Subset has been implemented then the key need only be unique
/// within the subset specified, not the entire database table.
/// Returns Nothing/null if the object does exist with the specified key.
/// This feature is what differentiates Database.ObjectByKey() from Database.ObjectByKeyExists().
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains the object.
/// </param>
///
/// <param name="objKey">
/// The key that identifies the object with the collection. The key is the value of
/// the field defined by the collection's IDatabaseObjects.KeyFieldName.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example>
/// <code>
/// Default Public ReadOnly Property Item(ByVal strProductCode As String) As Product
/// Get
///
/// Return objDatabase.ObjectByKey(Me, strProductCode)
///
/// End Get
/// End Property
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject ObjectByKeyIfExists(IDatabaseObjects objCollection, object objKey)
{
var objSelect = new SQL.SQLSelect();
string keyFieldName = objCollection.KeyFieldName();
EnsureKeyFieldNameIsSet(keyFieldName, objCollection);
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where.Add(keyFieldName, SQL.ComparisonOperator.EqualTo, objKey);
var objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
{
objSelect.Where.Add(objSubset);
}
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
if (objReader.Read())
return ObjectFromDataReader(objCollection, objReader);
else
return null;
}
}
}
/// <summary>
/// Throwns an exception if the key field name is "".
/// </summary>
private void EnsureKeyFieldNameIsSet(string keyFieldName, IDatabaseObjects collection)
{
if (String.IsNullOrEmpty(keyFieldName))
throw new InvalidOperationException("The KeyFieldAttribute has not been specified or the KeyFieldName function overridden for " + collection.GetType().FullName);
}
/// --------------------------------------------------------------------------------
/// <summary>
/// ObjectByOrdinalFirst returns the first object in the collection respectively
/// filtered and sorted by the collection's IDatabaseObjects.Subset and
/// IDatabaseObjects.OrderBy values. It differs from ObjectByOrdinal in that it only
/// loads the first record from the database table not the entire table.
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains the object.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example>
/// <code>
/// 'Ideal for loading default objects
/// Dim objDefaultSupplier As Supplier = objDatabase.ObjectByOrdinalFirst(objGlobalSuppliersInstance)
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject ObjectByOrdinalFirst(IDatabaseObjects objCollection)
{
var objSelect = new SQL.SQLSelect();
//only select the first row of the recordset
objSelect.Top = 1;
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where = objCollection.Subset();
objSelect.OrderBy = objCollection.OrderBy();
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
if (objReader.Read())
return ObjectFromDataReader(objCollection, objReader);
else
throw new Exceptions.ObjectDoesNotExistException(objCollection, "TOP 1");
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns the last object in the collection respectively
/// filtered and sorted by the collection's IDatabaseObjects.Subset and
/// IDatabaseObjects.OrderBy values. It differs from ObjectByOrdinal in that it only
/// loads the first record from the database table not the entire table.
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains the object.
/// </param>
///
/// <returns><see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)</returns>
///
/// <example>
/// <code>
/// 'Ideal for loading default objects
/// Dim objDefaultSupplier As Supplier = objDatabase.ObjectByOrdinalFirst(objGlobalSuppliersInstance)
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IDatabaseObject ObjectByOrdinalLast(IDatabaseObjects objCollection)
{
var objSelect = new SQL.SQLSelect();
//only select the first row of the recordset
objSelect.Top = 1;
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where = objCollection.Subset();
SQL.SQLSelectOrderByFields objOrderBy = objCollection.OrderBy();
if (objOrderBy != null)
{
objOrderBy.OrderingReverseAll();
objSelect.OrderBy = objOrderBy;
}
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
if (objReader.Read())
return ObjectFromDataReader(objCollection, objReader);
else
throw new Exceptions.ObjectDoesNotExistException(objCollection, "TOP 1 with reversed ordering");
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns the number of items in the collection. If the collection's
/// IDatabaseObjects.Subset has been implemented then this function returns the
/// number of records within the subset, not the entire table.
/// Also utilises the table joins so that any filters specified on the subset
/// can be used.
/// </summary>
///
/// <param name="objCollection">
/// The object for which the number of records are returned.
/// </param>
///
/// <returns><see cref="Int32" /> (System.Int32)</returns>
///
/// <example>
/// <code>
/// 'Return the number of items in this collection.
/// Public ReadOnly Property Count() As Integer
/// Get
///
/// Return objDatabase.ObjectsCount(Me)
///
/// End Get
/// End Property
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public int ObjectsCount(IDatabaseObjects objCollection)
{
var objSelect = new SQL.SQLSelect();
objSelect.Where = objCollection.Subset();
objSelect.Fields.Add(string.Empty, SQL.AggregateFunction.Count);
objSelect.Tables.Add(objCollection.TableName());
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
objReader.Read();
return System.Convert.ToInt32(objReader[0]);
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns whether the key exists within the collection. If the collection's
/// IDatabaseObjects.Subset has been set then only the subset is searched not the
/// entire table.
/// </summary>
///
/// <param name="objCollection">
/// The collection to search within.
/// </param>
///
/// <param name="objKey">
/// The key value to search by.
/// </param>
///
/// <returns><see cref="Boolean" /> (System.Boolean)</returns>
///
/// <example>
/// <code>
/// Public Function Exists(ByVal strProductCode As String) As Boolean
///
/// Return objDatabase.ObjectExists(Me, strProductCode)
///
/// End Function
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public bool ObjectExists(IDatabaseObjects objCollection, object objKey)
{
var objSelect = new SQL.SQLSelect();
string keyFieldName = objCollection.KeyFieldName();
EnsureKeyFieldNameIsSet(keyFieldName, objCollection);
objSelect.Tables.Add(objCollection.TableName());
//.Fields.Add objCollection.DistinctFieldName
objSelect.Where.Add(keyFieldName, SQL.ComparisonOperator.EqualTo, objKey);
var objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
{
objSelect.Where.Add(objSubset);
}
using (ConnectionScope objConnection = new ConnectionScope(this))
using (IDataReader objReader = objConnection.Execute(objSelect))
return objReader.Read();
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Deletes an object's database record. If the collection's IDatabaseObjects.Subset
/// has been implemented then the object must exist within the subset, otherwise the
/// object will not be deleted. If the object has not been saved to the database the
/// function will exit without executing an SQL DELETE command. After deleting the
/// database record the object is set to Nothing. The calling function should receive
/// the object ByRef for this to have any affect. Setting the object to Nothing
/// minimises the possibility of the deleted object being used in code after
/// ObjectDelete has been called.
/// </summary>
///
/// <param name="objCollection">
/// The collection that contains the object to delete. If the item does not exist
/// within the collection then the object will not be deleted.
/// </param>
///
/// <param name="objItem">
/// The object to delete. The calling function should receive this object ByRef
/// as the object is set to Nothing after deletion.
/// Reference Type: <see cref="IDatabaseObject" /> (DatabaseObjects.IDatabaseObject)
/// </param>
///
/// <example>
/// <code>
/// Public Sub Delete(ByRef objProduct As Product)
///
/// objDatabase.ObjectDelete(Me, objProduct)
/// 'objProduct will now be Nothing
///
/// End Sub
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public void ObjectDelete(IDatabaseObjects objCollection, ref IDatabaseObject objItem)
{
if (objItem.IsSaved)
{
SQL.SQLDelete objDelete = new SQL.SQLDelete();
SQL.SQLConditions objSubset;
objDelete.TableName = objCollection.TableName();
objDelete.Where.Add(objCollection.DistinctFieldName(), SQL.ComparisonOperator.EqualTo, objItem.DistinctValue);
objSubset = objCollection.Subset();
if (objSubset != null && !objSubset.IsEmpty)
objDelete.Where.Add(objSubset);
using (ConnectionScope objConnection = new ConnectionScope(this))
objConnection.ExecuteNonQuery(objDelete);
objItem.IsSaved = false;
if (Transaction.Current != null)
{
IDatabaseObject objItemCopy = objItem;
Transaction.Current.EnlistVolatile(new TransactionExecuteActionOnRollback(() => objItemCopy.IsSaved = true), EnlistmentOptions.None);
}
}
//The function that calls ObjectDelete objItem MUST be ByRef for this to have any effect
objItem = null;
}
private class TransactionExecuteActionOnRollback : IEnlistmentNotification
{
private Action pobjAction;
public TransactionExecuteActionOnRollback(Action objAction)
{
if (objAction == null)
throw new ArgumentNullException();
pobjAction = objAction;
}
public void Commit(System.Transactions.Enlistment enlistment)
{
}
public void InDoubt(System.Transactions.Enlistment enlistment)
{
}
public void Prepare(System.Transactions.PreparingEnlistment preparingEnlistment)
{
preparingEnlistment.Prepared();
}
public void Rollback(System.Transactions.Enlistment enlistment)
{
pobjAction.Invoke();
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Deletes all of the objects in the collection. If IDatabaseObjects.Subset
/// has been implemented then only the objects within the subset are deleted, not
/// the table's entire contents.
/// </summary>
///
/// <param name="objCollection">
/// The collection from which all objects are to be deleted.
/// </param>
/// --------------------------------------------------------------------------------
///
public void ObjectsDeleteAll(IDatabaseObjects objCollection)
{
SQL.SQLDelete objDelete = new SQL.SQLDelete();
objDelete.TableName = objCollection.TableName();
objDelete.Where = objCollection.Subset();
using (ConnectionScope objConnection = new ConnectionScope(this))
objConnection.ExecuteNonQuery(objDelete);
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an IList object containing all of the collection's associated child
/// objects. This function is useful when loading a set of objects for a subset or
/// for use with the IEnumerable interface.
/// </summary>
///
/// <param name="objCollection">
/// The collection which contains the objects to load.
/// </param>
///
/// <returns><see cref="Collections.IList" /> (System.Collections.IList)</returns>
///
/// <example>
/// <code>
/// 'Can be used to provide an enumerator for use with the "For Each" clause
/// Private Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
///
/// Return objDatabase.ObjectsList(objGlobalProductsInstance).GetEnumerator
///
/// End Function
/// </code>
/// </example>
/// --------------------------------------------------------------------------------
///
public IList ObjectsList(IDatabaseObjects objCollection)
{
IList objArrayList = new ArrayList();
SQL.SQLSelect objSelect = new SQL.SQLSelect();
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where = objCollection.Subset();
objSelect.OrderBy = objCollection.OrderBy();
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
while (objReader.Read())
objArrayList.Add(ObjectFromDataReader(objCollection, objReader));
return objArrayList;
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an array of IDatabaseObject objects contained within this collection.
/// </summary>
/// --------------------------------------------------------------------------------
public IDatabaseObject[] ObjectsArray(IDatabaseObjects objCollection)
{
IList objList = this.ObjectsList(objCollection);
IDatabaseObject[] objArray = new IDatabaseObject[objList.Count - 1 + 1];
objList.CopyTo(objArray, 0);
return objArray;
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an IDictionary object. Each key/value pair contains a key and
/// the object associated with the key.
/// </summary>
///
/// <param name="objCollection">
/// The collection which specifies the objects to load.
/// </param>
///
/// <returns><see cref="Collections.IDictionary" /> (System.Collections.IDictionary)</returns>
/// --------------------------------------------------------------------------------
///
public IDictionary ObjectsDictionary(IDatabaseObjects objCollection)
{
return ObjectsDictionaryBase(objCollection);
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns an IDictionary object. Each key/value pair contains a distinct
/// value and the object associated with the distinct value.
/// </summary>
///
/// <param name="objCollection">
/// The collection which specifies the objects to load.
/// </param>
///
/// <returns><see cref="Collections.IDictionary" /> (System.Collections.IDictionary)</returns>
/// --------------------------------------------------------------------------------
///
public IDictionary ObjectsDictionaryByDistinctValue(IDatabaseObjects objCollection)
{
return ObjectsDictionaryBase(objCollection, true);
}
private IDictionary ObjectsDictionaryBase(IDatabaseObjects objCollection, bool bKeyIsDistinctField = false)
{
//Returns an IDictionary with the key being either the DistinctField or KeyField
IDictionary objDictionary = new Hashtable();
SQL.SQLSelect objSelect = new SQL.SQLSelect();
string strKeyField;
SQL.SQLSelectTable objPrimaryTable = objSelect.Tables.Add(objCollection.TableName());
objSelect.Tables.Joins = objCollection.TableJoins(objPrimaryTable, objSelect.Tables);
objSelect.Where = objCollection.Subset();
objSelect.OrderBy = objCollection.OrderBy();
using (ConnectionScope objConnection = new ConnectionScope(this))
{
using (IDataReader objReader = objConnection.Execute(objSelect))
{
if (bKeyIsDistinctField)
strKeyField = objCollection.DistinctFieldName();
else
strKeyField = objCollection.KeyFieldName();
while (objReader.Read())
objDictionary.Add(objReader[strKeyField], ObjectFromDataReader(objCollection, objReader));
return objDictionary;
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Returns a collection of objects that match the specified search criteria.
/// This function utilises any subsets, ordering or table joins specified in the
/// collection. To add a set of conditions to the objSearchCriteria object with
/// higher precendance use the "Add(SQLConditions)" overloaded function as this will
/// wrap the conditions within parentheses.
/// </summary>
///
/// <param name="objCollection">
/// The collection to search within.
/// </param>
///
/// <param name="objSearchCriteria">
/// The criteria to search for within the collection. To add a set of conditions with
/// with higher precendance use the "Add(SQLConditions)" overloaded function as this
/// will wrap the conditions within parentheses.
/// </param>
///
/// <returns><see cref="Collections.IList" /> (System.Collections.IList)</returns>
///
/// <remarks>
/// The following wildcard characters are used when using the LIKE operator (extract
/// from Microsoft Transact-SQL Reference)
///
///
/// <font size="1">
/// <table width="659" border="1" cellspacing="1" cellpadding="4">
/// <tr>
/// <th width="16%" height="20">Wildcard character</th>
/// <th width="22%">Description</th>
/// <th width="62%">Example</th>
/// </tr>
/// <tr>
/// <td>%</td>
/// <td>Any string of zero or more characters.</td>
/// <td>WHERE title LIKE '%computer%' finds all book titles with the word
/// 'computer' anywhere in the book title.</td>
/// </tr>
/// <tr>
/// <td>_ (underscore)</td>