-
Notifications
You must be signed in to change notification settings - Fork 0
/
DatabaseUtility.cls
1291 lines (1039 loc) · 50.3 KB
/
DatabaseUtility.cls
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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "DatabaseUtility"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Option Explicit
Private DAC As DataAccessClass
Private cmd As New ADODB.Command
Private conn As New ADODB.connection
Public rs As New ADODB.Recordset
Public pTable As String
Public pField As String
Dim pDateString As String
Dim pfieldDataTypes As Dictionary
Dim pRecordsAffected As Double
Dim pDbPath As String, pDbName As String
' ==================================================
' LETTERS
' ==================================================
Public Property Let table(theTable As String)
pTable = theTable
End Property
Public Property Let field(theFieldName As String)
pField = theFieldName
End Property
Public Property Let dateString(theValue As String)
pDateString = theValue
End Property
Public Property Let dbName(theValue As String)
pDbName = theValue
End Property
Public Property Let dbPath(theValue As String)
pDbPath = theValue
End Property
Public Property Let recordsAffected(theValue As Double)
pRecordsAffected = recordsAffected
End Property
' ==================================================
' GETTERS
' ==================================================
Public Property Get table() As String
table = pTable
End Property
Public Property Get field() As String
field = pField
End Property
Public Property Get dateString() As String
dateString = pDateString
End Property
Public Property Get dbName() As String
dbName = pDbName
End Property
Public Property Get dbPath() As String
dbPath = pDbPath
End Property
Public Property Get fieldDataTypes() As Dictionary
Set fieldDataTypes = pfieldDataTypes
End Property
Public Property Get recordsAffected() As Double
recordsAffected = pRecordsAffected
End Property
Public Property Get commandText() As String
commandText = cmd.commandText
End Property
' ==================================================
' INITIALIZE AND TERMINATE
' ==================================================
Private Sub Class_Initialize()
''' Sets DataAccessClass object, its command and connection
Set DAC = New DataAccessClass
Set cmd = DAC.cmd
Set conn = DAC.conn
dateString = ""
End Sub
Private Sub Class_Terminate()
On Error Resume Next
Set DAC = Nothing
End Sub
' ==================================================
' CONNECTION FUNCTIONS
' ==================================================
Public Sub ConnectToDB(Optional theDbName As String = "", Optional theDbPath As String = "")
''' Sets connection to database according to given parameters or attributes
''' (dbName, dbPath) of the class.
'''
''' @input:
''' theDbName: Name of the MS Access database file with extension.
''' If not given, dbName is used.
''' theDbPath: Path of the MS Access database folder with backslash at the end.
''' If not given, dbPath is used.
'''
''' @output:
''' None
' Check db name
If theDbName = "" Then theDbName = dbName
' Check db path
If theDbPath = "" Then theDbPath = dbPath
If Right(theDbPath, 1) <> "\" Then theDbPath = theDbPath & "\"
Call DAC.ConnectToDB(theDbName, theDbPath)
End Sub
Public Sub DisconnectFromDB()
''' Disconnects from the connected database and resets variables
'''
''' @input:
''' None
'''
''' @output:
''' None
On Error Resume Next
Call DAC.DisconnectFromDB
End Sub
' ==================================================
' INTERFACE FUNCTIONS
' ==================================================
Function ExecuteSql(theSql As String) As ADODB.Recordset
''' Executes sql on connected database.
''' If sql fetches records, they are saved into ADODB.Recordset (rs).
''' If sql changes records in database, number of affected rows can be acquired from recordsAffected.
'''
''' Example:
''' ' let "db" be an object of DatabaseUtility
''' db.ExecutreSql([sql])
''' Do While Not db.rs.EOF
''' [variable] = db.rs.fields([field name]).Value
''' db.rs.MoveNext
''' Loop
'''
''' @input:
''' theSql: sql to be executed
'''
''' @output:
''' None
cmd.commandText = theSql
' executes the sql and number of affected rows are given to recordsAffected
Set rs = cmd.Execute(pRecordsAffected)
Set ExecuteSql = rs
End Function
Function GetTableNames() As Collection
''' Returns table names as strings of the connected database in a collection
'''
''' @input:
''' None
'''
''' @output:
''' GetTableNames: Collection of strings. It contains all table names in the
''' connected database.
Dim tableNames As Collection
Set rs = conn.OpenSchema(adSchemaTables, _
Array(Empty, Empty, Empty, "Table"))
Set tableNames = New Collection
With rs
Do While Not .EOF
If .Fields("TABLE_TYPE") <> "VIEW" Then
tableNames.Add .Fields("TABLE_NAME").Value
End If
.MoveNext
Loop
End With
Set GetTableNames = tableNames
Sortie:
Set tableNames = Nothing
End Function
Sub InsertRecord(theTable As String, theSetFields As Collection, theSetValues As Collection)
''' Inserts a new row into a table of connected database.
''' Field names and their respective values must be passed in two collections with respective order.
''' Table name is optional. If it is not passed, table attribute of the class is used.
'''
''' @input:
''' theTable: String of table name.
''' theSetFields: Collection of field names. It can be Nothing if all fields will be filled
''' and theSetValues consist of all field values with order.
''' theSetValues: Collection of field values.
'''
''' @output:
''' None
cmd.commandText = InsertSql(theTable, theSetFields, theSetValues)
' Debug.Print cmd.commandText
cmd.Execute
End Sub
Function SelectRecords(theTable As String, _
Optional theSelectionFields As Collection, _
Optional theCriteriaFields As Collection, Optional theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theDistinct As Boolean = False, _
Optional theLimitBy As Double = 0, _
Optional theOrderBy As String = "", Optional theAsc As Boolean = False) As ADODB.Recordset
''' Returns set of selected records according to the given criteria.
''' Contents of criteria fields and criteria values must be in the same order respectively.
'''
''' @input:
''' theTable: String of table name.
''' theCriteriaFields: Collection of database field names which has criteria.
''' theCriteriaValues: Collection of criteria values.
''' theSelectionFields: Collection of database field names which wanted to be returned.
''' This parameter is optional. If it is not sent, all fields in table are returned.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, relationship between
''' criteria fields and criteria values are taken as "=".
''' theDistinct: Boolean value which indicates if returned result values should be distinct or not.
''' This parameter is optional. If it is not sent, returned results will not be distinct.
''' theLimitBy: Number of desired records. Top records are returned. It is advised to be used with theOrderBy.
''' This parameter is optional. If not sent, all selected records are returned.
''' theOrderBy: String of database field which can be used to sort result collection.
''' This parameter is optional. If it is not sent, no sorting occurs.
''' theAsc: Boolean value which indicates if sorting should be ascending or not.
''' This parameter is optional. If it is not sent, sorting will be descending.
''' @output:
''' SelectRecords: ADODB recordset of values in a database table.
cmd.commandText = SelectSql(theTable, theSelectionFields, theCriteriaFields, theCriteriaValues, _
theOperators, theDistinct, theLimitBy, theOrderBy, theAsc)
Set rs = cmd.Execute
Set SelectRecords = rs
Sortie:
Exit Function
End Function
Function SelectField(theTable As String, _
theSelectionField As String, _
Optional theCriteriaFields As Collection, Optional theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theDistinct As Boolean = False, _
Optional theLimitBy As Double = 0, _
Optional theOrderBy As String = "", Optional theAsc As Boolean = False, _
Optional isBlankIncluded As Boolean = True) As Collection
''' Returns single database field according to the given criteria
''' Contents of criteria fields and criteria values must be in the same order respectively.
'''
''' @input:
''' theTable: String of table name.
''' theSelectionField: String of database field name in which data is wanted to be returned.
''' This parameter is optional. If it is not sent, field attribute of the class is used.
''' theCriteriaFields: Collection of database field names which has criteria.
''' This parameter is optional.
''' theCriteriaValues: Collection of criteria values.
''' This parameter is optional.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
''' theDistinct: Boolean value which indicates if returned result values should be distinct or not.
''' This parameter is optional. If it is not sent, returned results will not be distinct.
''' theLimitBy: Number of desired records. Top records are returned. It is advised to be used with theOrderBy.
''' This parameter is optional. If not sent, all selected records are returned.
''' theOrderBy: String of database field which can be used to sort result collection.
''' This parameter is optional. If it is not sent, no sorting occurs.
''' theAsc: Boolean value which indicates if sorting should be ascending or not.
''' This parameter is optional. If it is not sent, sorting will be descending.
''' isBlankIncluded: Boolean value which indicates if blanks values should be included in the result or not.
''' This parameter is optional. If it is not sent, blank values will be included.
''' @output:
''' SelectField: Collection of values in a database table field.
Dim selectionFields As New Collection, _
results As New Collection
selectionFields.Add theSelectionField
cmd.commandText = SelectSql(theTable, selectionFields, theCriteriaFields, theCriteriaValues, _
theOperators, theDistinct, theLimitBy, theOrderBy, theAsc)
Set rs = cmd.Execute
If Not rs.EOF Then
rs.MoveFirst
If isBlankIncluded Then
Do Until rs.EOF
results.Add rs.Fields(0).Value
rs.MoveNext
Loop
Else
Do Until rs.EOF
If Not IsNull(rs.Fields(0)) And rs.Fields(0) <> "" And rs.Fields(0) <> 0 Then
results.Add rs.Fields(0).Value
End If
rs.MoveNext
Loop
End If
End If
Set SelectField = results
Sortie:
Set results = Nothing
Set selectionFields = Nothing
End Function
Sub UpdateRecords(theTable As String, _
theSetFields As Collection, _
theSetValues As Collection, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection)
''' Updates records in database according to the given parameters.
'''
''' @input:
''' theTable: String of table name.
''' theSetFields: Collection of field names which will be updated.
''' theSetValues: Collection of field values which will be updated to.
''' theCriteriaFields: Collection of criteria field names.
''' theCriteriaValues: Collection of criteria field values.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
'''
''' @output:
''' None
cmd.commandText = UpdateSql(theTable, theSetFields, theSetValues, theCriteriaFields, _
theCriteriaValues, theOperators)
cmd.Execute
End Sub
Function SelectFieldCell(theTable As String, _
theSelectionField As String, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theOrderBy As String = "", _
Optional theAscending As Boolean) As Variant
''' Returns single cell value from database table according to the given parameters.
''' if query returns multiple records, top record is returned.
'''
''' @input:
''' theTable: String of database table name.
''' theSelectionField: String of database field name.
''' theCriteriaFields: Collection of database criteria field names.
''' theCriteriaValues: Collection of database criteria field values.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
''' theOrderBy: String of database field which can be used to sort result collection.
''' This parameter is optional. If it is not sent, no sorting occurs.
''' theAsc: Boolean value which indicates if sorting should be ascending or not.
''' This parameter is optional. If it is not sent, sorting will be descending.
'''
''' @output:
''' SelectFieldCell: Variant of database cell value.
Dim cellValue As Variant, i As Double
Dim theSelectionFields As New Collection
theSelectionFields.Add theSelectionField
cmd.commandText = SelectSql(theTable, theSelectionFields, theCriteriaFields, theCriteriaValues, _
theOperators, False, 1, theOrderBy, theAscending)
Set rs = cmd.Execute
If rs.EOF = True Then
cellValue = "NOTINDB"
' ElseIf IsNull(rs.Fields(0).Value) Then
' cellValue = ""
Else
cellValue = rs.Fields(0).Value
End If
SelectFieldCell = cellValue
Sortie:
Set theSelectionFields = Nothing
End Function
Function SelectFieldSum(theTable As String, _
theSelectionField As String, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theLimitBy As Double = 0, _
Optional theOrderByFieldName As String = "", _
Optional theAscending As Boolean) As Double
''' Returns sum of the selected field values according to the given parameters.
'''
''' @input:
''' theTable: String of database table name.
''' theSelectionField: String of database field name which is wanted to be summed.
''' The field must be a summable field.
''' theCriteriaFields: Collection of database criteria field names.
''' theCriteriaValues: Collection of database criteria field values.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
''' theLimitBy: Number of desired records. Top records are returned. It is advised to be used with theOrderBy.
''' This parameter is optional. If not sent, all selected records are returned.
''' theOrderBy: String of database field which can be used to sort result collection.
''' This parameter is optional. If it is not sent, no sorting occurs.
''' theAsc: Boolean value which indicates if sorting should be ascending or not.
''' This parameter is optional. If it is not sent, sorting will be descending.
'''
''' @output:
''' SelectFieldSum: Double of sum of database field values.
Dim sumValue As Double, i As Double
Dim selectionFields As New Collection
selectionFields.Add "SUM(" & theSelectionField & ")"
cmd.commandText = SelectSql(theTable, selectionFields, theCriteriaFields, theCriteriaValues, _
theOperators, , theLimitBy, theOrderByFieldName, theAscending)
Set rs = cmd.Execute
If rs.EOF = True Then
sumValue = 0
ElseIf rs.Fields(0) = Null Then
sumValue = 0
Else
sumValue = rs.Fields(0).Value
End If
SelectFieldSum = sumValue
Sortie:
Set selectionFields = Nothing
End Function
Function SelectFieldCount(theTable As String, _
theSelectionField As String, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theLimitBy As Double = 0, _
Optional theOrderByFieldName As String = "", _
Optional theAscending As Boolean) As Double
''' Returns count of the selected field values according to the given parameters.
'''
''' @input:
''' theTable: String of database table name.
''' theSelectionField: String of database field name which is wanted to be counted.
''' The field must be a countable field.
''' theCriteriaFields: Collection of database criteria field names.
''' theCriteriaValues: Collection of database criteria field values.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
''' theLimitBy: Number of desired records. Top records are returned. It is advised to be used with theOrderBy.
''' This parameter is optional. If not sent, all selected records are returned.
''' theOrderBy: String of database field which can be used to sort result collection.
''' This parameter is optional. If it is not sent, no sorting occurs.
''' theAsc: Boolean value which indicates if sorting should be ascending or not.
''' This parameter is optional. If it is not sent, sorting will be descending.
'''
''' @output:
''' SelectFieldCount: Double of count of database field values.
Dim countValue As Double, i As Double
Dim selectionFields As New Collection
selectionFields.Add "COUNT(" & theSelectionField & ")"
cmd.commandText = SelectSql(theTable, selectionFields, theCriteriaFields, theCriteriaValues, _
theOperators, , theLimitBy, theOrderByFieldName, theAscending)
Set rs = cmd.Execute
If rs.EOF = True Then
countValue = 0
ElseIf rs.Fields(0) = Null Then
countValue = 0
Else
countValue = rs.Fields(0).Value
End If
SelectFieldCount = countValue
Sortie:
Set selectionFields = Nothing
End Function
Sub DeleteRecords(theTable As String, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection)
''' Deletes records in database table according to the given parameters.
'''
''' @input:
''' theTable: String of database table name.
''' theCriteriaFields: Collection of database criteria field names.
''' theCriteriaValues: Collection of database criteria field values.
''' theOperators: Collection of operators which define relationship between
''' criteria fields and criteria values. Such as; "=", ">", "<", "<=", ">=".
''' This parameter is optional. If it is not sent, releationship between
''' criteria fields and criteria values are taken as "=".
'''
''' @output:
''' None
cmd.commandText = DeleteSql(theTable, theCriteriaFields, theCriteriaValues, theOperators)
cmd.Execute
End Sub
' ==================================================
' SQL GENERATOR FUNCTIONS
' ==================================================
Private Function DeleteSql(theTable As String, _
Optional theCriteriaFields As Collection, _
Optional theCriteriaValues As Collection, _
Optional theOperators As Collection) As String
''' Generates delete sql query according to the parameters.
'''
''' @input:
''' theTable: String of the table name.
''' theCriteriaFields: Collection of criteria fields.
''' This parameter is optional. If not sent, delete query select query does not have a criteria.
''' theCriteriaValues: Collection of criteria values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
''' theOperators: Collection of operators for criteria fields and values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
'''
''' @output:
''' DeleteSql: String of delete SQL query.
Dim SQLString As String, _
fieldsString As String, _
criteriaString As String, _
tableString As String
tableString = theTable
criteriaString = ""
fieldsString = "*"
If Not theCriteriaFields Is Nothing Then
criteriaString = CriteriaSqlString(theTable, theCriteriaFields, theCriteriaValues, theOperators)
End If
SQLString = "DELETE "
SQLString = SQLString & fieldsString & _
" FROM " & tableString
If Not criteriaString = "" Then
SQLString = SQLString & " WHERE (" & criteriaString & ")"
End If
DeleteSql = SQLString & ";"
End Function
Private Function SelectSql(theTable As String, _
Optional theSelectionFields As Collection, _
Optional theCriteriaFields As Collection, Optional theCriteriaValues As Collection, _
Optional theOperators As Collection, _
Optional theDistinct As Boolean = False, _
Optional theLimitBy As Double = 0, _
Optional theOrderByFieldName As String = "", _
Optional theAscending As Boolean = True) As String
''' Generates select sql query according to the parameters.
'''
''' @input:
''' theTable: String of the table name.
''' theSelectionField: Collection of fields to select.
''' This parameter is opetional. If not sent, select query includes a star(*), e.g. SELECT * ...
''' theCriteriaFields: Collection of criteria fields.
''' This parameter is optional. If not sent, select query select query does not have a criteria.
''' theCriteriaValues: Collection of criteria values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
''' theOperators: Collection of operators for criteria fields and values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
''' theDistinct: Boolean which indicates if distinct values should be returned or not.
''' This parameter is optional. If not sent, returned query does not have DISTINCT clause.
''' theLimitBy: Number of values which should be returned.
''' This parameter is optional. If not sent, returned query does not have LIMIT BY clause.
''' theOrderByFieldName:String of field name to order returned records.
''' This parameter is optional. If not sent, returned query does not have ORDER BY clause.
''' theAscending: Boolean which indicates if ordered records should be ascending or not.
''' This parameter is optional. If not sent and theOrderByFieldName is sent,
''' returned query contains ASCENDING clause.
'''
''' @output:
''' SelectSql: String of select SQL query.
Dim SQLString As String, _
fieldsString As String, _
criteriaString As String, _
length As Double, _
i As Double
fieldsString = ""
criteriaString = ""
If Not theSelectionFields Is Nothing Then
length = theSelectionFields.Count
For i = 1 To length
fieldsString = fieldsString & CStr(theSelectionFields(i))
If i <> length Then
fieldsString = fieldsString & ", "
End If
Next i
Else:
fieldsString = "*"
End If
If Not theCriteriaFields Is Nothing Then
criteriaString = CriteriaSqlString(theTable, theCriteriaFields, theCriteriaValues, theOperators)
End If
If theDistinct Then
SQLString = "SELECT DISTINCT "
Else
SQLString = "SELECT "
End If
'This kind of select distinct sql works ridiculously fast
If theDistinct Then
Dim distinctSelectionString As String
distinctSelectionString = CStr(theSelectionFields(1))
If Not theCriteriaFields Is Nothing Then
length = theCriteriaFields.Count
For i = 1 To length
distinctSelectionString = distinctSelectionString + ", " + CStr(theCriteriaFields(i))
Next i
End If
theTable = "(SELECT DISTINCT " + distinctSelectionString + " FROM " + theTable + ")"
End If
If Not theLimitBy = 0 Then
SQLString = SQLString & "TOP " & CStr(theLimitBy) & " " & fieldsString & _
" FROM " & theTable
Else
SQLString = SQLString & fieldsString & _
" FROM " & theTable
End If
If Not criteriaString = "" Then
SQLString = SQLString & " WHERE (" & criteriaString & ")"
End If
If Not theOrderByFieldName = "" Then
If theAscending Then
SQLString = SQLString & " ORDER BY " & theOrderByFieldName & " ASC"
Else
SQLString = SQLString & " ORDER BY " & theOrderByFieldName & " DESC"
End If
End If
SelectSql = SQLString & ";"
End Function
Private Function InsertSql(theTable As String, _
theFields As Collection, _
theValues As Collection) As String
''' Generates an insert query according to the parameters.
''' All parameters must be sent because they are needed to find out if quote is necessary
''' for each field.
'''
''' @input:
''' theTable: String of the table name to generate insert query.
''' theFields: Collection of field names to insert.
''' theValues: Collection of values to generate insert query.
'''
''' @output:
''' InsertSql: String of insert query.
Dim SQLString As String, _
fieldsString As String, _
valuesString As String, _
criteriaString As String, _
length As Double, _
i As Double
fieldsString = ""
valuesString = ""
For i = 1 To theFields.Count
fieldsString = fieldsString & CStr(theFields(i))
If i <> theFields.Count Then
fieldsString = fieldsString & ", "
End If
Next i
For i = 1 To theValues.Count
If IsNull(theValues(i)) Then
valuesString = valuesString & FixSQLValueString(theTable, _
theFields(i), "")
If i <> theValues.Count Then
valuesString = valuesString & ", "
End If
Else
valuesString = valuesString & FixSQLValueString(theTable, _
theFields(i), CStr(theValues(i)))
If i <> theValues.Count Then
valuesString = valuesString & ", "
End If
End If
Next i
If fieldsString = "" Then
SQLString = "INSERT INTO " & theTable & _
" VALUES (" & valuesString & ");"
Else
SQLString = "INSERT INTO " & theTable & _
" (" & fieldsString & ") " & _
"VALUES (" & valuesString & ");"
End If
' MsgBox SQLString
InsertSql = SQLString
End Function
Private Function UpdateSql(theTable As String, _
theSetFields As Collection, _
theSetValues As Collection, _
theCriteriaFields As Collection, _
theCriteriaValues As Collection, _
Optional theOperators As Collection) As String
''' Generates an update query according to the parameters.
''' All parameters must be sent because they are needed to find out if quote is necessary
''' for each field.
'''
''' @input:
''' theTable: String of the table name to generate update query.
''' theSetFields: Collection of field names to update.
''' theSetValues: Collection of field values to update.
''' theCriteriaFields: Collection of criteria field names.
''' theCriteriaValues: Collection of criteria field values.
''' theOperators: Collection of operators for criteria fields and values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
'''
''' @output:
''' UpdateSql: String of update query.
Dim SQLString As String, _
criteriaString As String, _
setString As String, orCriteriaString As String, _
length As Double, orLength As Double, _
i As Double, j As Double
criteriaString = ""
setString = ""
length = theSetValues.Count
For i = 1 To length
setString = setString & CStr(theSetFields(i)) _
& "=" & FixSQLValueString(theTable, theSetFields(i), CStr(theSetValues(i)))
If i <> length Then
setString = setString & ", "
End If
Next i
criteriaString = CriteriaSqlString(theTable, theCriteriaFields, theCriteriaValues, theOperators)
SQLString = "UPDATE " & table & _
" SET " & setString & " " & _
"WHERE (" & criteriaString & ");"
UpdateSql = SQLString
End Function
' =================================================
' HELPER FUNCTIONS FOR SQL GENERATORS
' =================================================
Private Function CriteriaSqlString(theTable As String, _
Optional theCriteriaFields As Collection, Optional theCriteriaValues As Collection, _
Optional theOperators As Collection) As String
''' Generates criteria part of an sql query according to the parameters.
'''
''' @input:
''' theTable: String of the table name.
''' theCriteriaFields: Collection of criteria fields.
''' This parameter is optional. If not sent, select query select query does not have a criteria.
''' theCriteriaValues: Collection of criteria values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
''' theOperators: Collection of operators for criteria fields and values.
''' This parameter is optional. It must be sent if theCriteriaFields is sent.
'''
''' @output:
''' None
Dim criteriaString As String, _
orCriteriaString As String, _
length As Double, _
i As Double, _
j As Double, _
orLength As Double
criteriaString = ""
orCriteriaString = ""
If Not theCriteriaFields Is Nothing Then
length = theCriteriaFields.Count
If theOperators Is Nothing Then
Set theOperators = New Collection
For i = 1 To length
theOperators.Add "="
Next i
End If
For i = 1 To length
'CHECK IF theCriteriaValues(i) IS A COLLECTION. IF IT IS, WHICH MEANS IT WILL BE "OR" STATEMENT
If IsObject(theCriteriaValues(i)) Then
orLength = theCriteriaValues(i).Count
orCriteriaString = ""
For j = 1 To orLength
'------------------------------------
'NULL QUERY
If theCriteriaValues(i)(j) = "NULL" Or theCriteriaValues(i)(j) = """""" _
Or IsNull(theCriteriaValues(i)(j)) Then
If theOperators(i) = "=" Then
orCriteriaString = orCriteriaString & "(" & CStr(theCriteriaFields(i)) _
& " IS NULL"
'Check if criteria field requires quotes, add second "OR" argument to the criteria string
If isQuoteNecessary(theTable, CStr(theCriteriaFields(i))) Then
orCriteriaString = orCriteriaString & " OR " & CStr(theCriteriaFields(i)) & "='')"
Else
orCriteriaString = orCriteriaString & ")"
End If
If j <> orLength Then
orCriteriaString = orCriteriaString & " OR "
End If
ElseIf theOperators(i) = "<>" Then
orCriteriaString = orCriteriaString & "(" & CStr(theCriteriaFields(i)) _
& " IS NOT NULL"
'Check if criteria field requires quotes, add second "OR" argument to the criteria string
If isQuoteNecessary(theTable, CStr(theCriteriaFields(i))) Then
orCriteriaString = orCriteriaString & " OR " & CStr(theCriteriaFields(i)) & "<>'')"
Else
orCriteriaString = orCriteriaString & ")"
End If
If j <> orLength Then
orCriteriaString = orCriteriaString & " OR "
End If
End If
'------------------------------------
'SEARCH QUERY
ElseIf Left(theCriteriaValues(i)(j), 1) = "*" Then
If theOperators(i) = "=" Then
orCriteriaString = orCriteriaString & "(" & CStr(theCriteriaFields(i)) _
& " LIKE " & "'%" & Replace(CStr(theCriteriaValues(i)(j)), "*", "") & "%')"
If j <> orLength Then
orCriteriaString = orCriteriaString & " OR "
End If
ElseIf theOperators(i) = "<>" Then
orCriteriaString = orCriteriaString & "(" & CStr(theCriteriaFields(i)) _
& " NOT LIKE " & "'%" & Replace(CStr(theCriteriaValues(i)(j)), "*", "") & "%')"
If j <> orLength Then
orCriteriaString = orCriteriaString & " OR "
End If
End If
Else
orCriteriaString = orCriteriaString & CStr(theCriteriaFields(i)) _
& theOperators(i) & FixSQLValueString(theTable, _
theCriteriaFields(i), CStr(theCriteriaValues(i)(j)), True)
If j <> orLength Then
orCriteriaString = orCriteriaString & " OR "
End If
End If
Next j
criteriaString = criteriaString & " (" & orCriteriaString & ") "
If i <> length Then
criteriaString = criteriaString & " AND "
End If
Else
'------------------------------------
'NULL QUERY
If theCriteriaValues(i) = "NULL" Or theCriteriaValues(i) = """""" _
Or IsNull(theCriteriaValues(i)) Then
If theOperators(i) = "=" Then
criteriaString = criteriaString & "(" & CStr(theCriteriaFields(i)) _
& " IS NULL"
'Check if criteria field requires quotes, add second "OR" argument to the criteria string
If isQuoteNecessary(theTable, CStr(theCriteriaFields(i))) Then
criteriaString = criteriaString & " OR " & CStr(theCriteriaFields(i)) & "='')"
Else
criteriaString = criteriaString & ")"
End If
If i <> length Then
criteriaString = criteriaString & " AND "
End If
ElseIf theOperators(i) = "<>" Then
criteriaString = criteriaString & "(" & CStr(theCriteriaFields(i)) _
& " IS NOT NULL"
'Check if criteria field requires quotes, add second "OR" argument to the criteria string
If isQuoteNecessary(theTable, CStr(theCriteriaFields(i))) And _
GetFieldDataType(theTable, CStr(theCriteriaFields(i))) <> 7 And _
GetFieldDataType(theTable, CStr(theCriteriaFields(i))) <> 133 And _
GetFieldDataType(theTable, CStr(theCriteriaFields(i))) <> 135 Then
criteriaString = criteriaString & " OR " & CStr(theCriteriaFields(i)) & "<>'')"
Else
criteriaString = criteriaString & ")"
End If
If i <> length Then