-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path_DataMgr.cfc
6553 lines (5689 loc) · 279 KB
/
_DataMgr.cfc
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
<!--- 2.6 (Build 180) --->
<!--- Last Updated: 2017-08-08 --->
<!--- Created by Steve Bryant 2004-12-08 --->
<!--- Information: http://www.bryantwebconsulting.com/docs/datamgr/?version=2.5 --->
<cfcomponent displayname="Data Manager" hint="I manage data interactions with the database. I can be used to handle inserts/updates.">
<cfset variables.DataMgrVersion = "2.6">
<cfset variables.DefaultDatasource = getDefaultDatasource()>
<cffunction name="init" access="public" returntype="DataMgr" output="no" hint="I instantiate and return this object.">
<cfargument name="datasource" type="string" required="no" default="#variables.DefaultDatasource#">
<cfargument name="database" type="string" required="no">
<cfargument name="username" type="string" required="no">
<cfargument name="password" type="string" required="no">
<cfargument name="SmartCache" type="boolean" default="false">
<cfargument name="SpecialDateType" type="string" default="CF">
<cfargument name="XmlData" type="string" required="no">
<cfargument name="logfile" type="string" required="no">
<cfargument name="Observer" type="any" required="no">
<cfargument name="databasename" type="string" required="no" hint="If DataMgr should manage in a different database than the default, indicate that here.">
<cfset var me = 0>
<cfset variables.datasource = arguments.datasource>
<cfset variables.CFServer = Server.ColdFusion.ProductName>
<cfset variables.CFVersion = ListFirst(Server.ColdFusion.ProductVersion)>
<cfset variables.SpecialDateType = arguments.SpecialDateType>
<cfif StructKeyExists(arguments,"username") AND StructKeyExists(arguments,"password")>
<cfset variables.username = arguments.username>
<cfset variables.password = arguments.password>
</cfif>
<cfif StructKeyExists(arguments,"logfile") AND Len(Arguments.logfile)>
<cfset variables.logfile = arguments.logfile>
</cfif>
<cfif StructKeyExists(arguments,"Observer")>
<cfset variables.Observer = arguments.Observer>
</cfif>
<cfif StructKeyExists(arguments,"defaultdatabase")>
<cfset variables.defaultdatabase = arguments.defaultdatabase>
</cfif>
<cfset variables.SmartCache = arguments.SmartCache>
<cfset Variables.dbprefix = "">
<cfset Variables.prefix = "">
<cfif StructKeyExists(arguments,"databasename")>
<cfset variables.databasename = arguments.databasename>
<cfset Variables.dbprefix = "#variables.databasename#.">
<cfif NOT StructKeyExists(arguments,"owner")>
<cfset Variables.owner = "dbo">
</cfif>
<cfset Variables.prefix = "#Variables.dbprefix#dbo.">
</cfif>
<cfset Variables.DataMgr = This>
<cfset variables.dbprops = getProps()>
<cfset variables.tables = StructNew()><!--- Used to internally keep track of table fields used by DataMgr --->
<cfset variables.tableprops = StructNew()><!--- Used to internally keep track of tables properties used by DataMgr --->
<cfset setCacheDate()><!--- Used to internally keep track caching --->
<!--- instructions for special processing decisions --->
<cfset variables.nocomparetypes = "CF_SQL_LONGVARCHAR,CF_SQL_CLOB,CF_SQL_BLOB"><!--- Don't run comparisons against fields of these cf_datatypes for queries --->
<cfset variables.dectypes = "CF_SQL_DECIMAL"><!--- Decimal types (shouldn't be rounded by DataMgr) --->
<cfset variables.aggregates = "avg,count,max,min,sum">
<!--- Information for logging --->
<cfset variables.doLogging = false>
<cfset variables.logtable = "datamgrLogs">
<cfset variables.UUID = CreateUUID()>
<!--- Code to run only if not in a database adaptor already --->
<cfif ListLast(getMetaData(this).name,".") EQ "DataMgr">
<cfif NOT StructKeyExists(arguments,"database")>
<cfset addEngineEnhancements(true)>
<cfset arguments.database = getDatabase()>
</cfif>
<!--- This will make sure that if a database is passed the component for that database is returned --->
<cfif StructKeyExists(arguments,"database")>
<cfif StructKeyExists(variables,"username") AND StructKeyExists(variables,"password")>
<cfset me = CreateObject("component","DataMgr_#arguments.database#").init(ArgumentCollection=Arguments)>
<cfelse>
<cfset me = CreateObject("component","DataMgr_#arguments.database#").init(ArgumentCollection=Arguments)>
</cfif>
</cfif>
<cfelse>
<cfset addEngineEnhancements(false)>
<cfset me = this>
</cfif>
<cfif StructKeyExists(arguments,"XmlData")>
<cfset me.loadXml(arguments.XmlData,true,true)/>
</cfif>
<cfreturn me>
</cffunction>
<cffunction name="addEngineEnhancements" access="private" returntype="void" output="no">
<cfargument name="isLoadingDatabaseType" type="boolean" default="false">
<cfset var oMixer = 0>
<cfset var key = "">
<cfif ListFirst(variables.CFServer," ") EQ "ColdFusion" AND variables.CFVersion GTE 8>
<cfset oMixer = CreateObject("component","DataMgrEngine_cf8")>
<cfelseif variables.CFServer EQ "BlueDragon">
<cfset oMixer = CreateObject("component","DataMgrEngine_openbd")>
<cfelseif variables.CFServer EQ "Railo">
<cfset oMixer = CreateObject("component","DataMgrEngine_railo")>
<cfelseif variables.CFServer EQ "Lucee">
<cfset oMixer = CreateObject("component","DataMgrEngine_lucee")>
</cfif>
<cfif isObject(oMixer)>
<cfloop collection="#oMixer#" item="key">
<cfif key NEQ "getDatabase" OR arguments.isLoadingDatabaseType>
<cfset variables[key] = oMixer[key]>
<cfif StructKeyExists(This,key)>
<cfset This[key] = oMixer[key]>
</cfif>
</cfif>
</cfloop>
</cfif>
</cffunction>
<cffunction name="getAdvSQLDelimiter" access="private" returntype="string" output="no">
<cfargument name="key" type="string" required="true">
<cfswitch expression="#Arguments.key#">
<cfcase value="SELECT,ORDER BY,GROUP BY,HAVING,SET">
<cfreturn ",">
</cfcase>
<cfcase value="WHERE,">
<cfreturn "AND">
</cfcase>
<cfdefaultcase>
<cfreturn "">
</cfdefaultcase>
</cfswitch>
</cffunction>
<cffunction name="addAdvSQL" access="public" returntype="void" output="no">
<cfargument name="Args" type="struct" required="true">
<cfargument name="key" type="string" required="true">
<cfargument name="sql" type="any" required="true">
<cfscript>
var delim = getAdvSQLDelimiter(Arguments.key);
var sql_start = "";
//This just allows a string to be passed in for the SQL for simple cases.
if ( isSimpleValue(Arguments.sql) ) {
Arguments.sql = [Arguments.sql];
}
//If the SQL isn't usable, throw an exception.
if ( NOT isArray(Arguments.sql) ) {
throwDMError("The sql argument of addAdvSQL must be either a string or a sqlarray.");
}
//Make sure AdvSQL exists.
if ( NOT StructKeyExists(Arguments.Args,"AdvSQL") ) {
Arguments.Args["AdvSQL"] = {};
}
//Make sure this key for AdvSQL exists.
if ( NOT StructKeyExists(Arguments.Args.AdvSQL,Arguments.key) ) {
Arguments.Args["AdvSQL"][Arguments.key] = [];
}
//Make sure we include delimiter ahead of incoming sql if it is needed.
if ( Len(delim) AND ArrayLen(Arguments.Args["AdvSQL"][Arguments.key]) ) {
if ( isSimpleValue(Arguments.sql[1]) ) {
sql_start = Trim(Arguments.sql[1]);
}
//If the SQL doesn't start with the delimiter, add it to the start
//Not adding it to the end of AdvSQL, just in case multiple things are messing with that at once.
if ( NOT ( Len(sql_start) GTE Len(delim) AND Left(sql_start,Len(delim)) EQ delim ) ) {
ArrayPrepend(Arguments.sql," #delim# ");
}
}
ArrayAppend(Arguments.Args["AdvSQL"][Arguments.key],Arguments.sql);
</cfscript>
</cffunction>
<cffunction name="addRelationListValue" access="public" returntype="void" output="no" hint="I add a value to a list field if it doesn't already exist. Can be used with any list value (not just relation fields).">
<cfargument name="tablename" type="string" required="yes">
<cfargument name="pkvalue" type="string" required="yes">
<cfargument name="field" type="string" required="yes">
<cfargument name="value" type="string" required="yes">
<cfset var pklist = getPrimaryKeyFieldNames(arguments.tablename)>
<cfset var sPKData = {"#pklist#":Arguments.pkvalue}>
<cfset var qRecord = getRecords(tablename=Arguments.tablename,data=sPKData,fieldlist=Arguments.field)>
<cfset var OldValue = qRecord[Arguments.field][1]>
<cfset var sData = StructCopy(sPKData)>
<cfif NOT ListFindNoCase(OldValue,Arguments.value)>
<cfset sData[Arguments.field] = ListAppend(OldValue,Arguments.value)>
<cfset saveRecord(
tablename=Arguments.tablename,
data=sData
)>
</cfif>
</cffunction>
<cffunction name="announceEvent" access="private" returntype="void" output="no">
<cfargument name="tablename" type="string" required="yes">
<cfargument name="action" type="string" required="yes" hint="The action taken.">
<cfargument name="method" type="string" required="yes" hint="The DataMgr method executed.">
<cfargument name="data" type="struct" required="yes" hint="The data passed to the method.">
<cfargument name="fieldlist" type="string" default="">
<cfargument name="Args" type="struct" required="yes" hint="The arguments passed to the method.">
<cfargument name="sql" type="any" required="no">
<cfargument name="pkvalue" type="any" required="no">
<cfargument name="ChangeUUID" type="string" required="no">
<cfif StructKeyExists(variables,"Observer") AND StructKeyExists(variables.Observer,"announceEvent")>
<cfset variables.Observer.announceEvent(
EventName="DataMgr:#arguments.action#",
Args=Arguments
)>
</cfif>
</cffunction>
<cffunction name="setCacheDate" access="public" returntype="void" output="no">
<cfset variables.CacheDate = now()>
</cffunction>
<cffunction name="setObserver" access="public" returntype="void" output="no">
<cfargument name="Observer" type="any" required="no">
<cfset variables.Observer = Arguments.Observer>
</cffunction>
<cffunction name="getDefaultDatasource" access="public" returntype="string" output="no">
<cfset var result = "">
<cftry>
<cfif isDefined("Application") AND StructKeyExists(Application,"Datasource")>
<cfset result = Application.Datasource>
</cfif>
<cfcatch>
</cfcatch>
</cftry>
<cfreturn result>
</cffunction>
<cffunction name="clean" access="public" returntype="struct" output="no" hint="I return a clean version (stripped of MS-Word characters) of the given structure.">
<cfargument name="Struct" type="struct" required="yes">
<cfset var key = "">
<cfset var sResult = StructNew()>
<cfscript>
for (key in arguments.Struct) {
if ( Len(key) AND StructKeyExists(arguments.Struct,key) AND isSimpleValue(arguments.Struct[key]) ) {
// Trim the field value. -- Don't do it! This causes trouble with encrypted strings
//sResult[key] = Trim(sResult[key]);
// Replace the special characters that Microsoft uses.
sResult[key] = arguments.Struct[key];
sResult[key] = Replace(sResult[key], Chr(8211), "-", "ALL");// dashes
sResult[key] = Replace(sResult[key], Chr(8212), "-", "ALL");// dashes
sResult[key] = Replace(sResult[key], Chr(8216), Chr(39), "ALL");// apostrophe / single-quote
sResult[key] = Replace(sResult[key], Chr(8217), Chr(39), "ALL");// apostrophe / single-quote
sResult[key] = Replace(sResult[key], Chr(8220), Chr(34), "ALL");// quotes
sResult[key] = Replace(sResult[key], Chr(8221), Chr(34), "ALL");// quotes
sResult[key] = Replace(sResult[key], Chr(8230), "...", "ALL");// elipses
sResult[key] = Replace(sResult[key], Chr(8482), "™", "ALL");// trademark
sResult[key] = Replace(sResult[key], "&##39;", Chr(39), "ALL");// apostrophe / single-quote
sResult[key] = Replace(sResult[key], "&##160;", Chr(39), "ALL");// space
sResult[key] = Replace(sResult[key], "&##8211;", "-", "ALL");// dashes
sResult[key] = Replace(sResult[key], "&##8212;", "-", "ALL");// dashes
sResult[key] = Replace(sResult[key], "&##8216;", Chr(39), "ALL");// apostrophe / single-quote
sResult[key] = Replace(sResult[key], "&##8217;", Chr(39), "ALL");// apostrophe / single-quote
sResult[key] = Replace(sResult[key], "&##8220;", Chr(34), "ALL");// quotes
sResult[key] = Replace(sResult[key], "&##8221;", Chr(34), "ALL");// quotes
sResult[key] = Replace(sResult[key], "&##8230;", "...", "ALL");// elipses
sResult[key] = Replace(sResult[key], "&##8482;", "™", "ALL");// trademark
}
}
</cfscript>
<cfreturn sResult>
</cffunction>
<cffunction name="createTable" access="public" returntype="string" output="no" hint="I take a table (for which the structure has been loaded) and create the table in the database.">
<cfargument name="tablename" type="string" required="yes">
<cfset var CreateSQL = getCreateSQL(arguments.tablename)>
<cfset var thisSQL = "">
<cfset var ii = 0><!--- generic counter --->
<cfset var arrFields = getFields(arguments.tablename)><!--- table structure --->
<cfset var increments = 0>
<!--- Make sure table has no more than one increment field --->
<cfloop index="ii" from="1" to="#ArrayLen(arrFields)#" step="1">
<cfif arrFields[ii].Increment>
<cfset increments = increments + 1>
</cfif>
</cfloop>
<cfif increments GT 1>
<cfset throwDMError("#arguments.tablename# has more than one increment field. A table is limited to only one increment field.","MultipleIncrements")>
</cfif>
<cfset StructDelete(variables,"cache_dbtables")>
<!--- try to create table --->
<cftry>
<cfloop index="thisSQL" list="#CreateSQL#" delimiters=";"><cfif thisSQL CONTAINS " ">
<!--- Ugly hack to get around Oracle's need for a semi-colon in SQL that doesn't split up SQL commands --->
<cfset thisSQL = ReplaceNoCase(thisSQL,"|DataMgr_SemiColon|",";","ALL")>
<cfset runSQL(thisSQL)>
</cfif></cfloop>
<cfcatch><!--- If the ceation fails, throw an error with the sql code used to create the database. --->
<cfif NOT (
CFCATCH.Message CONTAINS "There is already an object named"
OR (
StructKeyExists(CFCATCH,"Cause")
AND StructKeyExists(CFCATCH.Cause,"Message")
AND CFCATCH.Cause.Message CONTAINS "There is already an object named"
)
)>
<cfset throwDMError("SQL Error in Creation. Verify Datasource (#chr(34)##variables.datasource##chr(34)#) is valid.","CreateFailed",CreateSQL)>
</cfif>
</cfcatch>
</cftry>
<cfset setCacheDate()>
<cfreturn CreateSQL>
</cffunction>
<cffunction name="dbtableexists" access="public" returntype="boolean" output="no" hint="I indicate whether or not the given table exists in the database">
<cfargument name="tablename" type="string" required="true">
<cfargument name="dbtables" type="string" default="">
<cfset var result = false>
<cfset var qTest = 0>
<cfif NOT ( StructKeyExists(arguments,"dbtables") AND Len(Trim(arguments.dbtables)) )>
<cfset arguments.dbtables = "">
<cftry><!--- Try to get a list of tables load in DataMgr --->
<cfset arguments.dbtables = getDatabaseTablesCache()>
<cfcatch>
</cfcatch>
</cftry>
</cfif>
<cfif Len(arguments.dbtables)><!--- If we have tables loaded in DataMgr --->
<cfif ListFindNoCase(arguments.dbtables, arguments.tablename)>
<cfset result = true>
</cfif>
</cfif>
<!--- SEB 2010-04-25: This seems a tad aggresive (a lot of penalty for a just in case measure). Let's ditch it unless it proves essential. --->
<cfif false AND NOT result>
<cfset result = true>
<cftry><!--- create any table on which a select statement errors --->
<cfset qTest = runSQL("SELECT #getMaxRowsPrefix(1)# #escape(variables.tables[arguments.tablename][1].ColumnName)# FROM #escape(arguments.tablename)# #getMaxRowsSuffix(1)#")>
<cfcatch>
<cfset result = false>
</cfcatch>
</cftry>
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="CreateTables" access="public" returntype="string" output="no" hint="I create any tables that I know should exist in the database but don't.">
<cfargument name="tables" type="string" required="no" hint="I am a list of tables to create. If I am not provided createTables will try to create any table that has been loaded into it but does not exist in the database.">
<cfargument name="dbtables" type="string" required="false">
<cfset var table = "">
<cfset var tablesExist = StructNew()>
<cfset var qTest = 0>
<cfset var FailedSQL = "">
<cfset var DBErr = "">
<cfset var result = "">
<cfif NOT StructKeyExists(arguments,"tables")>
<cfset arguments.tables = StructKeyList(variables.tables)>
</cfif>
<cfif NOT ( StructKeyExists(arguments,"dbtables") AND Len(Trim(arguments.dbtables)) )>
<cfset arguments.dbtables = "">
<cftry><!--- Try to get a list of tables load in DataMgr --->
<cfset arguments.dbtables = getDatabaseTablesCache()>
<cfcatch>
</cfcatch>
</cftry>
</cfif>
<cfloop index="table" list="#arguments.tables#">
<!--- Create table if it doesn't exist --->
<cfif NOT dbtableexists(table,arguments.dbtables)>
<cftry>
<cfset createTable(table)>
<cfset arguments.dbtables = ListAppend(arguments.dbtables,table)>
<cfset result = ListAppend(result,table)>
<cfcatch type="DataMgr">
<cfif Len(CFCATCH.Detail)>
<cfset FailedSQL = ListAppend(FailedSQL,CFCATCH.Detail,";")>
<cfelse>
<cfset FailedSQL = ListAppend(FailedSQL,CFCATCH.Message,";")>
</cfif>
<cfif Len(CFCATCH.ExtendedInfo)>
<cfset DBErr = CFCATCH.ExtendedInfo>
</cfif>
</cfcatch>
</cftry>
</cfif>
</cfloop>
<cfif Len(FailedSQL)>
<cfset throwDMError("SQL Error in Creation. Verify Datasource (#chr(34)##variables.datasource##chr(34)#) is valid.","CreateFailed",FailedSQL,DBErr)>
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="deleteRecord" access="public" returntype="void" output="no" hint="I delete the record with the given Primary Key(s).">
<cfargument name="tablename" type="string" required="yes" hint="The name of the table from which to delete a record.">
<cfargument name="data" type="any" required="yes" hint="A structure indicating the record to delete. A key indicates a field. The structure should have a key for each primary key in the table.">
<cfset var i = 0><!--- just a counter --->
<cfset var fields = getUpdateableFields(arguments.tablename)>
<cfset var pkfields = getPKFields(arguments.tablename)><!--- the primary key fields for this table --->
<cfset var rfields = getRelationFields(arguments.tablename)><!--- relation fields in table --->
<cfset var in = arguments.data><!--- The incoming data structure --->
<cfset var isLogicalDelete = isLogicalDeletion(arguments.tablename)>
<cfset var qRecord = 0>
<cfset var sqlarray = ArrayNew(1)>
<cfset var out = 0>
<cfset var temp2 = 0>
<!---<cfset var qRelationList = 0>--->
<!---<cfset var subdatum = StructNew()>--->
<!---<cfset var sArgs = StructNew()>--->
<cfset var conflicttables = "">
<cfset var sCascadeDeletions = 0>
<cfset var ChangeUUID = CreateUUID()>
<cfset var pklist = getPrimaryKeyFieldNames(arguments.tablename)>
<!--- Throw exception if any pkfields are missing from incoming data --->
<cfloop index="i" from="1" to="#ArrayLen(pkfields)#" step="1">
<cfif NOT StructKeyExists(in,pkfields[i].ColumnName)>
<cfset throwDMError("All Primary Key fields (#pklist#) must be used when deleting a record. (Passed = #StructKeyList(in)#, Table=#arguments.tablename#)","RequiresAllPkFields")>
</cfif>
</cfloop>
<!--- Only get records by primary key --->
<cfloop collection="#in#" item="temp2">
<cfif NOT ListFindNoCase(pklist,temp2)>
<cfset StructDelete(in,temp2)>
</cfif>
</cfloop>
<cfset arguments.data = in>
<!--- Get the record containing the given data --->
<cfset qRecord = getRecord(arguments.tablename,in)>
<cfif qRecord.RecordCount EQ 1>
<!--- Look for onDelete errors --->
<cfset conflicttables = getDeletionConflicts(tablename=arguments.tablename,data=arguments.data,qRecord=qRecord)>
<cfif Len(conflicttables)>
<cfset throwDMError("You cannot delete a record in #arguments.tablename# when associated records exist in #conflicttables#.","NoDeletesWithRelated")>
</cfif>
<cfinvoke
method="announceEvent"
tablename="#arguments.tablename#"
action="beforeDelete"
data="#arguments.data#"
Args="#Arguments#"
ChangeUUID="#ChangeUUID#"
>
<cfinvokeargument name="method" value="deleteRecord">
<cfif ArrayLen(pkfields) EQ 1 AND StructKeyExists(in,pkfields[1].ColumnName)>
<cfinvokeargument name="pkvalue" value="#in[pkfields[1].ColumnName]#">
</cfif>
</cfinvoke>
<!--- Look for onDelete cascade --->
<cfset sCascadeDeletions = getCascadeDeletions(tablename=arguments.tablename,data=arguments.data,qRecord=qRecord)>
<cfloop item="temp2" collection="#sCascadeDeletions#">
<cfset deleteRecords(tablename=temp2,data=sCascadeDeletions[temp2])>
</cfloop>
<!--- Perform the delete --->
<cfif isLogicalDelete>
<!--- Look for DeletionMark field --->
<cfloop index="i" from="1" to="#ArrayLen(fields)#" step="1">
<cfif StructKeyExists(fields[i],"Special") AND fields[i].Special EQ "DeletionMark">
<cfif fields[i].CF_DataType EQ "CF_SQL_BIT">
<cfset in[fields[i].ColumnName] = 1>
<cfelseif fields[i].CF_DataType EQ "CF_SQL_DATE" OR fields[i].CF_DataType EQ "CF_SQL_DATETIME">
<cfset in[fields[i].ColumnName] = now()>
</cfif>
</cfif>
</cfloop>
<cfset updateRecord(arguments.tablename,in)>
<cfelse>
<!--- Delete Record --->
<cfset sqlarray = ArrayNew(1)>
<cfset ArrayAppend(sqlarray,"DELETE FROM #escape(Variables.prefix & arguments.tablename)# WHERE 1 = 1")>
<cfset ArrayAppend(sqlarray,getWhereSQL(argumentCollection=arguments))>
<cfset runSQLArray(sqlarray)>
<!--- Log delete --->
<cfif variables.doLogging AND NOT arguments.tablename EQ variables.logtable>
<cfinvoke method="logAction">
<cfinvokeargument name="tablename" value="#arguments.tablename#">
<cfif ArrayLen(pkfields) EQ 1 AND StructKeyExists(in,pkfields[1].ColumnName)>
<cfinvokeargument name="pkval" value="#in[pkfields[1].ColumnName]#">
</cfif>
<cfinvokeargument name="action" value="delete">
<cfinvokeargument name="data" value="#in#">
<cfinvokeargument name="sql" value="#sqlarray#">
</cfinvoke>
</cfif>
</cfif>
<cfinvoke
method="announceEvent"
tablename="#arguments.tablename#"
action="afterDelete"
data="#arguments.data#"
Args="#Arguments#"
ChangeUUID="#ChangeUUID#"
>
<cfinvokeargument name="method" value="deleteRecord">
<cfif ArrayLen(pkfields) EQ 1 AND StructKeyExists(in,pkfields[1].ColumnName)>
<cfinvokeargument name="pkvalue" value="#in[pkfields[1].ColumnName]#">
</cfif>
<cfif isArray(sqlarray) AND ArrayLen(sqlarray)>
<cfinvokeargument name="sql" value="#sqlarray#">
</cfif>
</cfinvoke>
<cfset setCacheDate()>
</cfif>
</cffunction>
<cffunction name="deleteRecords" access="public" returntype="void" output="no" hint="I delete the records with the given data.">
<cfargument name="tablename" type="string" required="yes" hint="The name of the table from which to delete a record.">
<cfargument name="data" type="struct" default="#StructNew()#" hint="A structure indicating the record to delete. A key indicates a field. The structure should have a key for each primary key in the table.">
<cfset var qRecords = getRecords(tablename=arguments.tablename,data=arguments.data,fieldlist=getPrimaryKeyFieldNames(arguments.tablename))>
<cfset var out = StructNew()>
<cfoutput query="qRecords">
<cfset out = QueryRowToStruct(qRecords,CurrentRow)>
<cfset deleteRecord(arguments.tablename,out)>
</cfoutput>
</cffunction>
<cffunction name="getBooleanSqlValue" access="public" returntype="string" output="no">
<cfargument name="value" type="string" required="yes">
<cfset var result = "NULL">
<cfif isBoolean(arguments.value)>
<cfif arguments.value>
<cfset result = "1">
<cfelse>
<cfset result = "0">
</cfif>
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="getCascadeDeletions" access="public" returntype="struct" output="no">
<cfargument name="tablename" type="string" required="yes" hint="The name of the table from which to delete a record.">
<cfargument name="data" type="struct" required="yes" hint="A structure indicating the record to delete. A key indicates a field. The structure should have a key for each primary key in the table.">
<cfset var rfields = getRelationFields(arguments.tablename)><!--- relation fields in table --->
<cfset var ii = 0>
<cfset var sResult = StructNew()>
<cfif NOT StructKeyExists(arguments,"qRecord")>
<cfset arguments.qRecord = getRecord(tablename=arguments.tablename,data=arguments.data)>
</cfif>
<cfloop index="ii" from="1" to="#ArrayLen(rfields)#" step="1">
<cfif
(
ListFindNoCase(variables.aggregates,rfields[ii].Relation["type"])
OR rfields[ii].Relation["type"] EQ "list"
)
AND (
(
StructKeyExists(rfields[ii].Relation,"onDelete")
AND rfields[ii].Relation["onDelete"] EQ "Cascade"
)
OR (
StructKeyExists(rfields[ii].Relation,"join-table")
AND NOT (
StructKeyExists(rfields[ii].Relation,"onDelete")
AND rfields[ii].Relation["onDelete"] NEQ "Cascade"
)
)
)
AND (
StructKeyExists(rfields[ii].Relation,"table")
AND NOT StructKeyExists(sResult,rfields[ii].Relation["table"])
)
>
<cfif StructKeyExists(rfields[ii].Relation,"join-table")>
<cfset sResult[rfields[ii].Relation["join-table"]] = StructNew()>
<cfset sResult[rfields[ii].Relation["join-table"]][rfields[ii].Relation["join-table-field-local"]] = arguments.qRecord[rfields[ii].Relation["local-table-join-field"]][1]>
<cfelse>
<cfset sResult[rfields[ii].Relation["table"]] = StructNew()>
<cfset sResult[rfields[ii].Relation["table"]][rfields[ii].Relation["join-field-remote"]] = arguments.qRecord[rfields[ii].Relation["join-field-local"]][1]>
</cfif>
</cfif>
</cfloop>
<cfreturn sResult>
</cffunction>
<cffunction name="getCheckFields" access="public" returntype="string" output="no">
<cfargument name="tablename" type="string" required="yes">
<cfif
StructKeyExists(variables.tableprops,arguments.tablename)
AND
StructKeyExists(variables.tableprops[arguments.tablename],"checkfields")
>
<cfreturn variables.tableprops[arguments.tablename]["checkfields"]>
<cfelse>
<cfreturn "">
</cfif>
</cffunction>
<cffunction name="getConstraintConflicts" access="public" returntype="any" output="no">
<cfargument name="tablename" type="string" required="true">
<cfargument name="ftable" type="string" required="false">
<cfargument name="field" type="string" required="false">
<cfset var result = 0>
<cfif StructKeyExists(Arguments,"ftable")>
<cfset result = getConstraintConflicts_Field(ArgumentCollection=Arguments)>
<cfelse>
<cfset result = getConstraintConflicts_Table(ArgumentCollection=Arguments)>
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="getDataBase" access="public" returntype="string" output="no" hint="I return the database platform being used.">
<cfset var connection = 0>
<cfset var db = "">
<cfset var type = "">
<!---<cfset var qDatabases = getSupportedDatabases()>--->
<cfif Len(variables.datasource)>
<cftry>
<cfset connection = getConnection()>
<cfcatch>
<cfif StructKeyExists(variables,"defaultdatabase")>
<cfset type = variables.defaultdatabase>
<cfelse>
<cftry>
<cfset connection.close()>
<cfcatch>
</cfcatch>
</cftry>
<cfif cfcatch.Message CONTAINS "Permission denied">
<cfset throwDMError("DataMgr was unable to determine database type.","DatabaseTypeRequired","DataMgr was unable to determine database type. Please pass the database argument (second argument of init method) to DataMgr.")>
<cfelse>
<cfrethrow>
</cfif>
</cfif>
</cfcatch>
</cftry>
<cfset db = connection.getMetaData().getDatabaseProductName()>
<cfset connection.close()>
<cfswitch expression="#db#">
<cfcase value="Microsoft SQL Server">
<cfset type = "MSSQL">
</cfcase>
<cfcase value="MySQL">
<cfset type = "MYSQL">
</cfcase>
<cfcase value="PostgreSQL">
<cfset type = "PostGreSQL">
</cfcase>
<cfcase value="Oracle">
<cfset type = "Oracle">
</cfcase>
<cfcase value="MS Jet">
<cfset type = "Access">
</cfcase>
<cfcase value="Apache Derby">
<cfset type = "Derby">
</cfcase>
<cfdefaultcase>
<cfif ListFirst(db,"/") EQ "DB2">
<cfset type = "DB2">
<cfelse>
<cfset type = "unknown">
<cfset type = db>
</cfif>
</cfdefaultcase>
</cfswitch>
<cfelse>
<cfset type = "Sim">
</cfif>
<cfreturn type>
</cffunction>
<cffunction name="getDatabaseProperties" access="public" returntype="struct" output="no" hint="I return some properties about this database">
<cfset var sProps = StructNew()>
<cfreturn sProps>
</cffunction>
<cffunction name="getDatabaseShortString" access="public" returntype="string" output="no" hint="I return the string that can be found in the driver or JDBC URL for the database platform being used.">
<cfreturn "unknown"><!--- This method will get overridden in database-specific DataMgr components --->
</cffunction>
<cffunction name="getDatabaseDriver" access="public" returntype="string" output="no" hint="I return the string that can be found in the driver or JDBC URL for the database platform being used.">
<cfreturn "">
</cffunction>
<cffunction name="getDatasource" access="public" returntype="string" output="no" hint="I return the datasource used by this Data Manager.">
<cfreturn variables.datasource>
</cffunction>
<cffunction name="getDBFieldList" access="public" returntype="string" output="no" hint="I return a list of fields in the database for the given table.">
<cfargument name="tablename" type="string" required="yes">
<cfset var qFields = runSQL("SELECT #getMaxRowsPrefix(1)# * FROM #escape(arguments.tablename)# #getMaxRowsSuffix(1)#")>
<cfreturn qFields.ColumnList>
</cffunction>
<cffunction name="getDefaultValues" access="public" returntype="struct" output="false" hint="">
<cfargument name="tablename" type="string" required="yes">
<cfset var sFields = 0>
<cfset var aFields = 0>
<cfset var ii = 0>
<!--- If fields data if stored --->
<cfif StructKeyExists(variables.tableprops,arguments.tablename) AND StructKeyExists(variables.tableprops[arguments.tablename],"fielddefaults")>
<cfset sFields = variables.tableprops[arguments.tablename]["fielddefaults"]>
<cfelse>
<cfset aFields = getFields(arguments.tablename)>
<cfset sFields = StructNew()>
<!--- Get fields with length and set key appropriately --->
<cfloop index="ii" from="1" to="#ArrayLen(aFields)#" step="1">
<cfif StructKeyExists(aFields[ii],"Default") AND Len(aFields[ii].Default)>
<cfset sFields[aFields[ii].ColumnName] = aFields[ii].Default>
<cfelse>
<cfset sFields[aFields[ii].ColumnName] = "">
</cfif>
</cfloop>
<cfset variables.tableprops[arguments.tablename]["fielddefaults"] = sFields>
</cfif>
<cfreturn sFields>
</cffunction>
<cffunction name="getDeletionConflicts" access="public" returntype="string" output="no">
<cfargument name="tablename" type="string" required="yes" hint="The name of the table from which to delete a record.">
<cfargument name="data" type="struct" required="yes" hint="A structure indicating the record to delete. A key indicates a field. The structure should have a key for each primary key in the table.">
<cfset var rfields = getRelationFields(arguments.tablename)><!--- relation fields in table --->
<cfset var ii = 0>
<cfset var subdatum = 0>
<cfset var sArgs = 0>
<cfset var qRelationList = 0>
<cfset var result = "">
<cfif NOT StructKeyExists(arguments,"qRecord")>
<cfset arguments.qRecord = getRecord(tablename=arguments.tablename,data=arguments.data)>
</cfif>
<cfloop index="ii" from="1" to="#ArrayLen(rfields)#" step="1">
<cfif
(
StructKeyExists(rfields[ii].Relation,"onDelete")
AND rfields[ii].Relation["onDelete"] EQ "Error"
)
AND (
StructKeyExists(rfields[ii].Relation,"table")
AND NOT ListFindNoCase(result,rfields[ii].Relation["table"])
)
AND (
rfields[ii].Relation["type"] EQ "list"
OR ListFindNoCase(variables.aggregates,rfields[ii].Relation["type"])
)
>
<cfset sArgs = StructNew()>
<cfset subdatum = StructNew()>
<cfset subdatum.data = StructNew()>
<cfset subdatum.advsql = StructNew()>
<cfif StructKeyExists(rfields[ii].Relation,"join-table")>
<cfset subdatum.subadvsql = StructNew()>
<cfset subdatum.subadvsql.WHERE = "#escape( rfields[ii].Relation['join-table'] & '.' & rfields[ii].Relation['join-table-field-remote'] )# = #escape( rfields[ii].Relation['table'] & '.' & rfields[ii].Relation['remote-table-join-field'] )#">
<cfset subdatum.data[rfields[ii].Relation["local-table-join-field"]] = arguments.qRecord[rfields[ii].Relation["join-table-field-local"]][1]>
<cfset subdatum.advsql.WHERE = ArrayNew(1)>
<cfset ArrayAppend(subdatum.advsql.WHERE,"EXISTS (")>
<cfset ArrayAppend(subdatum.advsql.WHERE,getRecordsSQL(tablename=rfields[ii].Relation["join-table"],data=subdatum.data,advsql=subdatum.subadvsql,isInExists=true))>
<cfset ArrayAppend(subdatum.advsql.WHERE,")")>
<cfelse>
<cfset subdatum.data[rfields[ii].Relation["join-field-remote"]] = arguments.qRecord[rfields[ii].Relation["join-field-local"]][1]>
</cfif>
<cfset sArgs["tablename"] = rfields[ii].Relation["table"]>
<cfset sArgs["data"] = subdatum.data>
<cfset sArgs["fieldlist"] = rfields[ii].Relation["field"]>
<cfset sArgs["advsql"] = subdatum.advsql>
<cfif StructKeyExists(rfields[ii].Relation,"filters") AND isArray(rfields[ii].Relation.filters)>
<cfset sArgs["filters"] = rfields[ii].Relation.filters>
</cfif>
<cfset qRelationList = getRecords(argumentCollection=sArgs)>
<cfif qRelationList.RecordCount>
<cfset result = ListAppend(result,rfields[ii].Relation.table)>
</cfif>
</cfif>
</cfloop>
<cfreturn result>
</cffunction>
<cffunction name="getIsDeletableSQL" access="public" returntype="array" output="no">
<cfargument name="tablename" type="string" required="yes" hint="The name of the table from which to delete a record.">
<cfset var rfields = getRelationFields(arguments.tablename)><!--- relation fields in table --->
<cfset var ii = 0>
<cfset var sArgs = 0>
<cfset var aSQL = ArrayNew(1)>
<cfset var tables = "">
<cfset var hasNestedSQL = false>
<cfif NOT StructKeyExists(arguments,"tablealias")>
<cfset arguments.tablealias = arguments.tablename>
</cfif>
<cfif StructKeyExists(arguments,"ignore")>
<cfset tables = arguments.ignore>
</cfif>
<cfset ArrayAppend(
aSQL,
"
(
CASE
WHEN (
1 = 1
"
)>
<cfloop index="ii" from="1" to="#ArrayLen(rfields)#" step="1">
<cfif
(
StructKeyExists(rfields[ii].Relation,"table")
AND NOT ListFindNoCase(tables,rfields[ii].Relation["table"])
)
AND (
rfields[ii].Relation["type"] EQ "list"
OR ListFindNoCase(variables.aggregates,rfields[ii].Relation["type"])
)
AND (
StructKeyExists(rfields[ii].Relation,"onDelete")
AND (
rfields[ii].Relation["onDelete"] EQ "Error"
OR rfields[ii].Relation["onDelete"] EQ "Cascade"
)
)
>
<cfset tables = ListAppend(tables,rfields[ii].Relation["table"])>
<cfset sArgs = StructNew()>
<cfset sArgs["tablename"] = rfields[ii].Relation["table"]>
<cfset sArgs["tablealias"] = sArgs["tablename"]>
<cfif sArgs["tablealias"] EQ arguments.tablealias>
<cfset sArgs["tablealias"] = sArgs["tablealias"] & "_DataMgr_inner">
</cfif>
<cfif rfields[ii].Relation["onDelete"] EQ "Error"><!--- OR ( StructKeyExists(variables.tableprops[sArgs["tablename"]],"deletable") ) --->
<cfscript>
sArgs["isInExists"] = true;
sArgs["fieldlist"] = rfields[ii].Relation["field"];
sArgs["ignore"] = arguments.tablename;
if ( StructKeyExists(rfields[ii].Relation,"filters") AND isArray(rfields[ii].Relation.filters) ) {
sArgs["filters"] = rfields[ii].Relation.filters;
}
sArgs["advsql"] = StructNew();
sArgs["advsql"]["WHERE"] = ArrayNew(1);
if ( StructKeyExists(rfields[ii].Relation,"join-table") ) {
sArgs["tablename"] = rfields[ii].Relation["join-table"];
StructDelete(sArgs,"tablealias");
sArgs["join"] = StructNew();
sArgs["join"]["table"] = rfields[ii].Relation["table"];
sArgs["join"]["type"] = "INNER";
sArgs["join"]["onright"] = rfields[ii].Relation["remote-table-join-field"];
sArgs["join"]["onleft"] = rfields[ii].Relation["join-table-field-remote"];
ArrayAppend(sArgs["advsql"]["WHERE"],getFieldSelectSQL(tablename=rfields[ii].Relation["join-table"],field=rfields[ii].Relation["join-table-field-local"],tablealias=rfields[ii].Relation["join-table"],useFieldAlias=false));
ArrayAppend(sArgs["advsql"]["WHERE"]," = ");
ArrayAppend(sArgs["advsql"]["WHERE"],getFieldSelectSQL(tablename=arguments.tablename,field=rfields[ii].Relation['local-table-join-field'],tablealias=arguments.tablealias,useFieldAlias=false));
} else {
ArrayAppend(sArgs["advsql"]["WHERE"],getFieldSelectSQL(tablename=sArgs.tablename,field=rfields[ii].Relation['join-field-remote'],tablealias=sArgs.tablealias,useFieldAlias=false));
ArrayAppend(sArgs["advsql"]["WHERE"]," = ");
ArrayAppend(sArgs["advsql"]["WHERE"],getFieldSelectSQL(tablename=arguments.tablename,field=rfields[ii].Relation['join-field-local'],tablealias=arguments.tablealias,useFieldAlias=false));
}
ArrayAppend(aSQL,"AND NOT EXISTS (");
ArrayAppend(aSQL,getRecordsSQL(argumentCollection=sArgs));
ArrayAppend(aSQL,")");
</cfscript>
<cfelseif rfields[ii].Relation["onDelete"] NEQ "Ignore">
<cfscript>
sArgs["ignore"] = arguments.tablename;
ArrayAppend(aSQL," AND (");
ArrayAppend(aSQL," NOT EXISTS (");
ArrayAppend(aSQL," SELECT 1");
if ( StructKeyExists(rfields[ii].Relation,"join-table") ) {
sArgs["tablename"] = rfields[ii].Relation["join-table"];
StructDelete(sArgs,"tablealias");
ArrayAppend(aSQL," FROM #escape(rfields[ii].Relation['join-table'])#");
ArrayAppend(aSQL," INNER JOIN #escape(rfields[ii].Relation["table"])#");
ArrayAppend(aSQL," ON #escape(rfields[ii].Relation["join-table"])#.#escape(rfields[ii].Relation["join-table-field-remote"])# = #escape(rfields[ii].Relation['table'])#.#escape(rfields[ii].Relation["remote-table-join-field"])#");
} else {
ArrayAppend(aSQL," FROM #escape(rfields[ii].Relation['table'])#");
}
ArrayAppend(aSQL," WHERE 1 = 1");
ArrayAppend(aSQL," AND (");
if ( StructKeyExists(rfields[ii].Relation,"join-table") ) {
ArrayAppend(aSQL,getFieldSelectSQL(tablename=arguments.tablename,field=rfields[ii].Relation['local-table-join-field'],tablealias=arguments.tablealias,useFieldAlias=false));
ArrayAppend(aSQL," = ");
ArrayAppend(aSQL,getFieldSelectSQL(tablename=rfields[ii].Relation["join-table"],field=rfields[ii].Relation["join-table-field-local"],tablealias=rfields[ii].Relation["join-table"],useFieldAlias=false));
} else {
ArrayAppend(aSQL,getFieldSelectSQL(tablename=sArgs.tablename,field=rfields[ii].Relation['join-field-remote'],tablealias=sArgs.tablealias,useFieldAlias=false));
ArrayAppend(aSQL," = ");
ArrayAppend(aSQL,getFieldSelectSQL(tablename=arguments.tablename,field=rfields[ii].Relation['join-field-local'],tablealias=arguments.tablealias,useFieldAlias=false));
}
ArrayAppend(aSQL," )");
ArrayAppend(aSQL," AND (");
ArrayAppend(aSQL," 1 = 0");
ArrayAppend(aSQL," OR (");
ArrayAppend(aSQL,getIsDeletableSQL(argumentCollection=sArgs));
ArrayAppend(aSQL," ) = 0");
ArrayAppend(aSQL," )");
ArrayAppend(aSQL," )");
ArrayAppend(aSQL," )");
</cfscript>
</cfif>
<cfset hasNestedSQL = true>
</cfif>
</cfloop>
<cfset ArrayAppend(
aSQL,
"
)
THEN #getBooleanSqlValue(true)#
ELSE #getBooleanSqlValue(false)#
END
)
"
)>
<cfif NOT hasNestedSQL>
<cfset aSQL = ArrayNew(1)>
<cfset ArrayAppend(aSQL,getBooleanSqlValue(true))>
</cfif>
<cfreturn aSQL>
</cffunction>