/
Database.vb
executable file
·2256 lines (1893 loc) · 93.1 KB
/
Database.vb
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
' ___________________________________________________
'
Option Strict On
Option Explicit On
Imports DatabaseObjects
Imports System.Data
Imports System.Diagnostics
Imports System.Transactions
''' --------------------------------------------------------------------------------
''' <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>
''' --------------------------------------------------------------------------------
'''
Public Class Database
Public Enum ConnectionType
SQLServer
MicrosoftAccess
MySQL
Pervasive
SQLServerCompactEdition
HyperSQL
End Enum
Private pobjConnection As ConnectionController
Private pobjTransactions As TransactionsClass
''' --------------------------------------------------------------------------------
''' <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 Sub New( _
ByVal strConnectionString As String, _
ByVal eConnectionType As ConnectionType)
pobjConnection = New ConnectionController(strConnectionString, eConnectionType)
pobjTransactions = New TransactionsClass(pobjConnection)
End Sub
''' <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 Sub New( _
ByVal objDatabaseConnection As IDbConnection, _
ByVal eConnectionType As ConnectionType)
pobjConnection = New ConnectionController(objDatabaseConnection, eConnectionType)
pobjTransactions = New TransactionsClass(pobjConnection)
End Sub
' ''' --------------------------------------------------------------------------------
' ''' <summary>
' ''' Allows the DatabaseUsingSchemaTranslations to override the connection controller
' ''' and override the field and table name translations.
' ''' </summary>
' ''' --------------------------------------------------------------------------------
'Protected Sub New(ByVal objConnection As ConnectionController)
' If objConnection Is Nothing Then
' Throw New ArgumentNullException
' End If
' pobjConnection = objConnection
' pobjTransactions = New TransactionsClass(pobjConnection)
'End Sub
''' --------------------------------------------------------------------------------
''' <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 Function [Object]( _
ByVal objCollection As IDatabaseObjects, _
ByVal objDistinctValue As Object) As IDatabaseObject
Return ObjectFromFieldValues(objCollection, Me.ObjectFieldValues(objCollection, objDistinctValue))
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectIfExists( _
ByVal objCollection As IDatabaseObjects, _
ByVal objDistinctValue As Object) As IDatabaseObject
Dim objFieldValues As SQL.SQLFieldValues = Me.ObjectFieldValuesIfExists(objCollection, objDistinctValue)
If objFieldValues Is Nothing Then
Return Nothing
Else
Return ObjectFromFieldValues(objCollection, objFieldValues)
End If
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectFieldValues( _
ByVal objCollection As IDatabaseObjects, _
ByVal objDistinctValue As Object) As SQL.SQLFieldValues
Dim objFieldValues As SQL.SQLFieldValues = ObjectFieldValuesIfExists(objCollection, objDistinctValue)
If objFieldValues Is Nothing Then
Throw New Exceptions.ObjectDoesNotExistException(objCollection, objDistinctValue)
End If
Return objFieldValues
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectFieldValuesIfExists( _
ByVal objCollection As IDatabaseObjects, _
ByVal objDistinctValue As Object) As SQL.SQLFieldValues
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
Dim objSubset As SQL.SQLConditions
With objSelect
Dim objPrimaryTable As SQL.SQLSelectTable = .Tables.Add(objCollection.TableName)
.Tables.Joins = objCollection.TableJoins(objPrimaryTable, .Tables)
.Where.Add(objCollection.DistinctFieldName, SQL.ComparisonOperator.EqualTo, objDistinctValue)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
If objReader.Read() Then
Return FieldValuesFromDataReader(objCollection, objReader)
Else
Return Nothing
End If
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectExistsByDistinctValue( _
ByVal objCollection As IDatabaseObjects, _
ByVal objDistinctValue As Object) As Boolean
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
Dim objSubset As SQL.SQLConditions
With objSelect
.Tables.Add(objCollection.TableName)
.Where.Add(objCollection.DistinctFieldName, SQL.ComparisonOperator.EqualTo, objDistinctValue)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
Return objReader.Read
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Sub ObjectSave( _
ByVal objCollection As IDatabaseObjects, _
ByVal objItem As IDatabaseObject)
Dim objFieldValues As SQL.SQLFieldValues
Dim objUpdate As SQL.SQLUpdate
Dim objInsert As SQL.SQLInsert
Dim objSubset As SQL.SQLConditions
Dim objNewGUID As System.Guid
Dim autoAssignment As SQL.FieldValueAutoAssignmentType = MergeDistinctFieldAutoAssignmentAndDistinctFieldAutoIncrements(objCollection)
objFieldValues = objItem.SaveFields
If objFieldValues Is Nothing Then
Throw New Exceptions.DatabaseObjectsException(Misc.TypeName(objItem) & " IDatabaseObject.SaveFields not implemented")
End If
'Add the distinct field value if it hasn't been added via the SaveFields sub
If Not objFieldValues.Exists(objCollection.DistinctFieldName) Then
Select Case autoAssignment
Case SQL.FieldValueAutoAssignmentType.None
objFieldValues.Add(objCollection.DistinctFieldName, objItem.DistinctValue)
Case 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 Not objItem.IsSaved Then
objNewGUID = System.Guid.NewGuid
objFieldValues.Add(objCollection.DistinctFieldName, objNewGUID)
End If
End Select
End If
#If Not Debug Then
ItemKeyEnsureValid(objCollection, objItem, objFieldValues)
#End If
Using objConnection As New ConnectionScope(Me)
If objItem.IsSaved Then
objUpdate = New SQL.SQLUpdate
objUpdate.TableName = objCollection.TableName
objUpdate.Fields.Add(objFieldValues)
objUpdate.Where.Add(objCollection.DistinctFieldName, SQL.ComparisonOperator.EqualTo, objItem.DistinctValue)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
objUpdate.Where.Add(objSubset)
End If
objConnection.ExecuteNonQuery(objUpdate)
Else
objInsert = New SQL.SQLInsert
objInsert.TableName = objCollection.TableName
objInsert.Fields = objFieldValues
objConnection.ExecuteNonQuery(objInsert)
Select Case autoAssignment
Case SQL.FieldValueAutoAssignmentType.NewUniqueIdentifier
objItem.DistinctValue = objNewGUID
Case SQL.FieldValueAutoAssignmentType.AutoIncrement
objItem.DistinctValue = Connection.ExecuteScalar(New SQL.SQLAutoIncrementValue)
End Select
Dim objRollbackDistinctValue As Object = objItem.DistinctValue
objItem.IsSaved = True
If Transaction.Current IsNot Nothing Then
Transaction.Current.EnlistVolatile(New TransactionExecuteActionOnRollback(Sub() objItem.IsSaved = False), EnlistmentOptions.None)
Transaction.Current.EnlistVolatile(New TransactionExecuteActionOnRollback(Sub() objItem.DistinctValue = objRollbackDistinctValue), EnlistmentOptions.None)
End If
End If
End Using
End Sub
''' <summary>
''' Merges the obsolete function DistinctFieldAutoIncrements with the new DistinctFieldAutoAssignment function.
''' </summary>
Private Function MergeDistinctFieldAutoAssignmentAndDistinctFieldAutoIncrements(collection As IDatabaseObjects) As SQL.FieldValueAutoAssignmentType
If collection.DistinctFieldAutoIncrements Then
Return SQL.FieldValueAutoAssignmentType.AutoIncrement
Else
Return collection.DistinctFieldAutoAssignment
End If
End Function
Private Sub ItemKeyEnsureValid( _
ByVal objCollection As IDatabaseObjects, _
ByVal objItem As IDatabaseObject, _
ByVal objFieldValues As SQL.SQLFieldValues)
Dim objSelect As SQL.SQLSelect
Dim objKeyFieldValue As Object
Dim objSubset As SQL.SQLConditions
'If the key field is set and the key field is specified in the object
If objCollection.KeyFieldName <> String.Empty AndAlso objFieldValues.Exists(objCollection.KeyFieldName) Then
objKeyFieldValue = ItemKeyFieldValue(objCollection, objItem, objFieldValues)
EnsureKeyDataTypeValid(objKeyFieldValue)
If TypeOf objKeyFieldValue Is String Then
If DirectCast(objKeyFieldValue, String).Trim = String.Empty Then
Throw New Exceptions.DatabaseObjectsException(Misc.TypeName(objItem) & " " & objCollection.KeyFieldName & " field is Null")
End If
End If
objSelect = New SQL.SQLSelect
With objSelect
.Tables.Add(objCollection.TableName)
.Fields.Add(objCollection.KeyFieldName)
.Where.Add(objCollection.KeyFieldName, SQL.ComparisonOperator.EqualTo, objKeyFieldValue)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
If objItem.IsSaved Then
.Where.Add(objCollection.DistinctFieldName, SQL.ComparisonOperator.NotEqualTo, objItem.DistinctValue)
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
If objReader.Read Then
Throw New Exceptions.ObjectAlreadyExistsException(objItem, objKeyFieldValue)
End If
End Using
End Using
End If
End Sub
''' --------------------------------------------------------------------------------
''' <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 Function ObjectByKey( _
ByVal objCollection As IDatabaseObjects, _
ByVal objKey As Object) As IDatabaseObject
Dim objObject As IDatabaseObject = ObjectByKeyIfExists(objCollection, objKey)
If objObject Is Nothing Then
Throw New Exceptions.ObjectDoesNotExistException(objCollection, objKey)
End If
Return objObject
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectByKeyIfExists( _
ByVal objCollection As IDatabaseObjects, _
ByVal objKey As Object) As IDatabaseObject
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
Dim objSubset As SQL.SQLConditions
Dim keyFieldName As String = objCollection.KeyFieldName
EnsureKeyFieldNameIsSet(keyFieldName, objCollection)
EnsureKeyDataTypeValid(objKey)
With objSelect
Dim objPrimaryTable As SQL.SQLSelectTable = .Tables.Add(objCollection.TableName)
.Tables.Joins = objCollection.TableJoins(objPrimaryTable, .Tables)
.Where.Add(keyFieldName, SQL.ComparisonOperator.EqualTo, objKey)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
If objReader.Read Then
Return ObjectFromDataReader(objCollection, objReader)
Else
Return Nothing
End If
End Using
End Using
End Function
''' <summary>
''' Throwns an exception if the key field name is "".
''' </summary>
Private Sub EnsureKeyFieldNameIsSet(ByVal keyFieldName As String, collection As IDatabaseObjects)
If keyFieldName = String.Empty Then
Throw New InvalidOperationException("The KeyFieldAttribute has not been specified or the KeyFieldName function overridden for " & collection.GetType.FullName)
End If
End Sub
''' --------------------------------------------------------------------------------
''' <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 Function ObjectByOrdinalFirst( _
ByVal objCollection As IDatabaseObjects) As IDatabaseObject
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
With objSelect
'only select the first row of the recordset
.Top = 1
Dim objPrimaryTable As SQL.SQLSelectTable = .Tables.Add(objCollection.TableName)
.Tables.Joins = objCollection.TableJoins(objPrimaryTable, .Tables)
.Where = objCollection.Subset
.OrderBy = objCollection.OrderBy
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
If objReader.Read() Then
Return ObjectFromDataReader(objCollection, objReader)
Else
Throw New Exceptions.ObjectDoesNotExistException(objCollection, "TOP 1")
End If
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectByOrdinalLast( _
ByVal objCollection As IDatabaseObjects) As IDatabaseObject
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
With objSelect
'only select the first row of the recordset
.Top = 1
Dim objPrimaryTable As SQL.SQLSelectTable = .Tables.Add(objCollection.TableName)
.Tables.Joins = objCollection.TableJoins(objPrimaryTable, .Tables)
.Where = objCollection.Subset
Dim objOrderBy As SQL.SQLSelectOrderByFields = objCollection.OrderBy
If objOrderBy IsNot Nothing Then
objOrderBy.OrderingReverseAll()
.OrderBy = objOrderBy
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
If objReader.Read() Then
Return ObjectFromDataReader(objCollection, objReader)
Else
Throw New Exceptions.ObjectDoesNotExistException(objCollection, "TOP 1 with reversed ordering")
End If
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectsCount( _
ByVal objCollection As IDatabaseObjects) As Integer
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
With objSelect
.Where = objCollection.Subset
.Fields.Add(String.Empty, SQL.AggregateFunction.Count)
.Tables.Add(objCollection.TableName)
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
objReader.Read()
Return CType(objReader(0), Integer)
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Function ObjectExists( _
ByVal objCollection As IDatabaseObjects, _
ByVal objKey As Object) As Boolean
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
Dim objSubset As SQL.SQLConditions
Dim keyFieldName As String = objCollection.KeyFieldName
EnsureKeyFieldNameIsSet(keyFieldName, objCollection)
EnsureKeyDataTypeValid(objKey)
With objSelect
.Tables.Add(objCollection.TableName)
'.Fields.Add objCollection.DistinctFieldName
.Where.Add(keyFieldName, SQL.ComparisonOperator.EqualTo, objKey)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
Return objReader.Read
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <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 Sub ObjectDelete( _
ByVal objCollection As IDatabaseObjects, _
ByRef objItem As IDatabaseObject)
If objItem.IsSaved Then
Dim objDelete As SQL.SQLDelete = New SQL.SQLDelete
Dim objSubset As SQL.SQLConditions
With objDelete
.TableName = objCollection.TableName
.Where.Add(objCollection.DistinctFieldName, SQL.ComparisonOperator.EqualTo, objItem.DistinctValue)
objSubset = objCollection.Subset
If Not objSubset Is Nothing AndAlso Not objSubset.IsEmpty Then
.Where.Add(objSubset)
End If
End With
Using objConnection As New ConnectionScope(Me)
objConnection.ExecuteNonQuery(objDelete)
End Using
objItem.IsSaved = False
If Transaction.Current IsNot Nothing Then
Dim objItemCopy As IDatabaseObject = objItem
Transaction.Current.EnlistVolatile(New TransactionExecuteActionOnRollback(Sub() objItemCopy.IsSaved = True), EnlistmentOptions.None)
End If
End If
'The function that calls ObjectDelete objItem MUST be ByRef for this to have any effect
objItem = Nothing
End Sub
Private Class TransactionExecuteActionOnRollback
Implements IEnlistmentNotification
Private pobjAction As Action
Public Sub New(ByVal objAction As Action)
If objAction Is Nothing Then
Throw New ArgumentNullException
End If
pobjAction = objAction
End Sub
Private Sub Commit(ByVal enlistment As System.Transactions.Enlistment) Implements System.Transactions.IEnlistmentNotification.Commit
End Sub
Private Sub InDoubt(ByVal enlistment As System.Transactions.Enlistment) Implements System.Transactions.IEnlistmentNotification.InDoubt
End Sub
Private Sub Prepare(ByVal preparingEnlistment As System.Transactions.PreparingEnlistment) Implements System.Transactions.IEnlistmentNotification.Prepare
preparingEnlistment.Prepared()
End Sub
Private Sub Rollback(ByVal enlistment As System.Transactions.Enlistment) Implements System.Transactions.IEnlistmentNotification.Rollback
pobjAction.Invoke()
End Sub
End Class
''' --------------------------------------------------------------------------------
''' <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 Sub ObjectsDeleteAll( _
ByVal objCollection As IDatabaseObjects)
Dim objDelete As SQL.SQLDelete = New SQL.SQLDelete
With objDelete
.TableName = objCollection.TableName
.Where = objCollection.Subset
End With
Using objConnection As New ConnectionScope(Me)
objConnection.ExecuteNonQuery(objDelete)
End Using
End Sub
''' --------------------------------------------------------------------------------
''' <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 Function ObjectsList( _
ByVal objCollection As IDatabaseObjects) As IList
Dim objArrayList As IList = New ArrayList
Dim objSelect As SQL.SQLSelect = New SQL.SQLSelect
With objSelect
Dim objPrimaryTable As SQL.SQLSelectTable = .Tables.Add(objCollection.TableName)
.Tables.Joins = objCollection.TableJoins(objPrimaryTable, .Tables)
.Where = objCollection.Subset
.OrderBy = objCollection.OrderBy
End With
Using objConnection As New ConnectionScope(Me)
Using objReader As IDataReader = objConnection.Execute(objSelect)
While objReader.Read
objArrayList.Add(ObjectFromDataReader(objCollection, objReader))
End While
Return objArrayList
End Using
End Using
End Function
''' --------------------------------------------------------------------------------
''' <summary>
''' Returns an array of IDatabaseObject objects contained within this collection.
''' </summary>
''' --------------------------------------------------------------------------------
Public Function ObjectsArray( _
ByVal objCollection As IDatabaseObjects) As IDatabaseObject()
Dim objList As IList = Me.ObjectsList(objCollection)
Dim objArray(objList.Count - 1) As IDatabaseObject
objList.CopyTo(objArray, 0)
Return objArray