-
Notifications
You must be signed in to change notification settings - Fork 27
/
progress.util.js
1085 lines (939 loc) · 40.4 KB
/
progress.util.js
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
/*eslint no-global-assign: ["error", {"exceptions": ["localStorage"]}]*/
/*global XMLHttpRequest:true, require, console, localStorage:true, sessionStorage:true, $:true, Promise, setTimeout */
/*
Copyright (c) 2014-2019 Progress Software Corporation and/or its subsidiaries or affiliates.
Contains support objects used by the jsdo and/or session object
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*global progress:true, btoa:true*/
/*jslint nomen: true*/
(function () {
// Pre-release code to detect enviroment and load required modules for Node.js and NativeScript
// Requirements:
// - XMLHttpRequest
// - localStorage
// - sessionStorage
// - Promise object (Promises with the same interface as jQuery Promises)
// Notes:
// Required packages should be installed before loading progress-jsdo.
// Node.js:
// - xmlhttprequest
// NativeScript:
// - nativescript-localstorage
var isNativeScript = false,
isNodeJS = false;
var pkg_xmlhttprequest = "xmlhttprequest",
pkg_nativescriptLocalstorage = "nativescript-localstorage",
pkg_fileSystemAccess = "file-system/file-system-access"
;
//In memory localStorage emulation used for node
function LocalStorageEmulation() {
this._data = {};
};
LocalStorageEmulation.prototype.setItem = function(id, val) { return this._data[id] = String(val); },
LocalStorageEmulation.prototype.getItem = function(id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined; },
LocalStorageEmulation.prototype.removeItem = function(id) { return delete this._data[id]; },
LocalStorageEmulation.prototype.clear = function() { return this._data = {}; }
// If XMLHttpRequest is undefined, enviroment would appear to be Node.js
// load xmlhttprequest module
// Web browser and NativeScript clients have a built-in XMLHttpRequest object
if (typeof XMLHttpRequest === "undefined") {
isNodeJS = true;
try {
XMLHttpRequest = require("" + pkg_xmlhttprequest).XMLHttpRequest;
// xhrc = require("xmlhttprequest-cookie");
// XMLHttpRequest = xhrc.XMLHttpRequest;
} catch(e) {
console.error("Error: JSDO library requires XMLHttpRequest object in Node.js.\n"
+ "Please install xmlhttprequest package.");
}
}
// Detect if the environment is NativeScript
if (!isNodeJS
&& (typeof localStorage === "undefined"
|| typeof sessionStorage === "undefined")) {
try {
require("" + pkg_fileSystemAccess);
isNativeScript = true;
} catch(exception1) {
isNativeScript = false;
}
}
// If localStorage or sessionStorage is not defined,
// we need to load the corresponding support module
// If environment is NativeScript, load required modules
if (isNativeScript) {
try {
// load module nativescript-localstorage
if (typeof sessionStorage === "undefined") {
sessionStorage = require("" + pkg_nativescriptLocalstorage);
}
if (typeof localStorage === "undefined") {
localStorage = require("" + pkg_nativescriptLocalstorage);
}
} catch(exception2) {
console.error("Error: JSDO library requires localStorage and sessionStorage objects in NativeScript.\n"
+ "Please install nativescript-localstorage package.");
}
// Polyfill the btoa() function (which we use to encode BASIC authorization)
try {
if (typeof btoa === "undefined") {
btoa = function(str) { return Buffer.from(str).toString('base64'); }
}
} catch(exception3) {
console.error("Error: JSDO library requires toString('base64') function in NativeScript.");
}
}
if (isNodeJS) {
if (typeof localStorage === "undefined") {
localStorage = new LocalStorageEmulation();
}
if (typeof sessionStorage === "undefined") {
sessionStorage = new LocalStorageEmulation();
}
// Polyfill the btoa() function (which we use to encode BASIC authorization)
try {
if (typeof btoa === "undefined") {
btoa = function(str) { return Buffer.from(str).toString('base64'); }
}
} catch(exception3) {
console.error("Error: JSDO library requires toString('base64')function in Node.js.");
}
}
// If we're running in the browser, edit btoa() to properly encode Unicode strings
// taken from https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa#Unicode_strings
if (!isNodeJS && !isNativeScript) {
if (typeof btoa !== "undefined") {
let btoaOriginal = btoa;
// this section of code is functionally identical to the toString('base-64')
// btoa() doesn't exist on node though, which is why we have different styles
// of encoding in NS/node
btoa = function (str) {
return btoaOriginal(unescape(encodeURIComponent(str)));
};
}
}
}());
(function () {
/* Define these if not defined yet - they may already be defined if
* progress.js was included first */
if (typeof progress === "undefined") {
progress = {};
}
if (typeof progress.data === "undefined") {
progress.data = {};
}
progress.util = {};
var STRING_OBJECT_TYPE = "String",
DATE_OBJECT_TYPE = "Date",
CHARACTER_ABL_TYPE = "CHARACTER";
/**
* Deferred class to provide access to ES6 and JQuery Promises.
*
* @class
*/
progress.util.Deferred = /** @class */ (function () {
function Deferred() {
this._deferred = {};
}
/**
* Returns a Promise object.
*/
Deferred.prototype.promise = function () {
var that = this;
if (progress.util.Deferred.useJQueryPromises) {
if (typeof($) !== 'undefined' && typeof($.Deferred) === 'function') {
this._deferred._jQuerydeferred = $.Deferred();
this._promise = this._deferred._jQuerydeferred.promise();
} else {
throw new Error("JQuery Promises not found in environment.");
}
} else {
this._promise = new Promise(function (resolve, reject) {
that._deferred.resolve = resolve;
that._deferred.reject = reject;
});
}
if (this._resolveArguments || this._rejectArguments) {
setTimeout(function () {
if (that._resolveArguments) {
that.resolve.apply(that, that._resolveArguments);
} else if (that._rejectArguments) {
that.reject.apply(that, that._rejectArguments);
}
}, 500);
}
// return null;
return this._promise;
};
/**
* Calls the underlying resolve() method.
*/
Deferred.prototype.resolve = function (arg1, arg2, arg3) {
if (this._promise) {
if (this._deferred._jQuerydeferred) {
this._deferred._jQuerydeferred.resolve.apply(this, arguments);
} else {
var object = progress.util.Deferred.getParamObject1(arg1, arg2, arg3);
this._deferred.resolve(object);
}
} else {
this._resolveArguments = arguments;
}
};
/**
* Calls the underlying reject() method.
*/
Deferred.prototype.reject = function (arg1, arg2, arg3) {
if (this._promise) {
if (this._deferred._jQuerydeferred) {
this._deferred._jQuerydeferred.reject.apply(this, arguments);
} else {
var object = progress.util.Deferred.getParamObject1(arg1, arg2, arg3);
this._deferred.reject(object);
}
} else {
this._rejectArguments = arguments;
}
};
/**
* @property {boolean} useJQueryPromises - Tells the Deferred object to use jQuery Promises.
*/
Deferred.useJQueryPromises = false;
/**
* Returns a deferred object based on a collection.
*/
Deferred.when = function (deferreds) {
if (progress.util.Deferred.useJQueryPromises) {
return $.when.apply($, deferreds);
} else {
return Promise.all(deferreds);
}
}
/**
* Returns an object with the parameters to resolve()/reject().
*/
Deferred.getParamObject1 = function (arg1, arg2, arg3) {
var object = {},
objectName;
try {
if ((typeof(arg1) === "undefined") || (arg1 === null)) {
object.result = arg2;
object.info = arg3;
} else {
// Map some object name to use a particular property name
// We should probably spend some time down the line to truly use
// ES6 promises.
if (arg1 instanceof progress.data.JSDOSession) {
objectName = "jsdosession";
} else if (arg1 instanceof progress.data.AuthenticationProvider) {
objectName = "provider";
} else if (arg1 instanceof progress.data.JSDO) {
objectName = "jsdo";
} else if (typeof(arg1) === "number") {
objectName = "result";
} else {
objectName = typeof(arg1);
}
object[objectName] = arg1;
if (objectName === "jsdo") {
object.success = arg2;
if (arg3 && arg3.xhr) {
object.request = arg3;
} else if (arg3 && arg3.batch) {
object.request = arg3;
} else {
object.info = arg3;
}
} else {
if (objectName === "result") {
object.info = arg2;
if (arg3) {
object.info2 = arg3;
}
} else {
object.result = arg2;
object.info = arg3;
}
}
}
} catch(e) {
console.log("Error: Undetermined argument in getParamObject() call.");
}
return object;
}
/**
* Returns an object with the parameters to resolve()/reject() based on the Promise type.
*/
Deferred.getParamObject = function (arg1, arg2, arg3) {
var object = {};
if (progress.util.Deferred.useJQueryPromises) {
object = progress.util.Deferred.getParamObject1(arg1, arg2, arg3);
} else {
if (typeof(arg1) === "undefined") {
object.result = arg2;
object.info = arg3;
arg1 = object;
}
return arg1;
}
return object;
};
return Deferred;
}());
/**
* Utility class that allows subscribing and unsubscribing from named events.
*
* @returns {progress.util.Observable}
*/
progress.util.Observable = function () {
/*
* Example format of the events object. Some event delegates may only
* have a function setup, others may optionally have scope, and possibly an operation filter
*
* var events = {
* afterfill : [{
* scope : {}, // this is optional
* fn : function () {},
* operation : 'getCustomers' // this is optional
* }, ...]
*
* }
*
*
*
*/
/*
* remove the given function from the array of observers
*/
function _filterObservers(observers, fn, scope, operation) {
return observers.filter(function (el) {
if (el.fn !== fn || el.scope !== scope || el.operation !== operation) {
return el;
}
}, this);
}
/*
* validate the arguments passed to the subscribe function
*/
this.validateSubscribe = function (args, evt, listenerData) {
if (args.length >= 2 && (typeof args[0] === 'string') && (typeof args[1] === 'string')) {
listenerData.operation = args[1];
listenerData.fn = args[2];
listenerData.scope = args[3];
} else if (args.length >= 2 && (typeof args[0] === 'string') && (typeof args[1] === 'function')) {
listenerData.operation = undefined;
listenerData.scope = args[2];
listenerData.fn = args[1];
} else {
throw new Error();
}
};
/*
* bind the specified function so it receives callbacks when the
* specified event name is called. Event name is not case sensitive.
* An optional scope can be provided so that the function is executed
* in the given scope. If no scope is given, then the function will be
* called without scope.
*
* If the same function is registered for the same event a second time with
* the same scope the original subscription is removed and replaced with the new function
* to be called in the new scope.
*
* This method has two signatures.
*
* Signature 1:
* @param evt The name of the event to bind a handler to. String. Not case sensitive.
* @param fn The function callback for the event . Function.
* @param scope The scope the function is to be run in. Object. Optional.
*
* Signature 2:
*
* @param evt The name of the event to bind a handler to. String. Not case sensitive
* @param operation The name of the operation to bind to. String. Case sensitive.
* @param fn The function callback for the event . Function.
* @param scope The scope the function is to be run in. Object. Optional.
*/
this.subscribe = function (evt, operation, fn, scope) {
var listenerData,
observers;
if (!evt) {
throw new Error(progress.data._getMsgText("jsdoMSG037", this.toString(), "subscribe"));
}
if (typeof evt !== 'string') {
throw new Error(progress.data._getMsgText("jsdoMSG033", this.toString(),
"subscribe", progress.data._getMsgText("jsdoMSG039")));
}
this._events = this._events || {};
evt = evt.toLowerCase();
listenerData = {fn: undefined, scope: undefined, operation: undefined};
try {
this.validateSubscribe(arguments, evt, listenerData);
} catch (e) {
throw new Error(progress.data._getMsgText("jsdoMSG033", this.toString(),
"subscribe", e.message));
}
observers = this._events[evt] || [];
// make sure we don't add duplicates
observers = _filterObservers(observers, listenerData.fn,
listenerData.scope, listenerData.operation);
observers.push(listenerData);
this._events[evt] = observers;
return this;
};
/*
* remove the specified function so it no longer receives events from
* the given name. event name is not case sensitive.
*
* This method has two signaturues.
* Signature 1:
* @param evt Required. The name of the event for which to unbind the given function. String.
* @param fn Required. The function to remove from the named event. Function.
* @param scope Optional. The function scope in which to remove the listener. Object.
*
* Signature 2:
*
* @param evt Required. The name of the event for which to unbind the given function.
String. Not case sensitive
* @param operation Required. The name of the operation to receive events. String. Case Sensitive
* @param fn Required. The function to remove from the named event. Function.
* @param scope Optional. The function scope in which to remove the listener. Object.
*
*/
this.unsubscribe = function (evt, operation, fn, scope) {
var listenerData,
observers;
if (!evt) {
throw new Error(progress.data._getMsgText("jsdoMSG037", this.toString(), "unsubscribe"));
}
if (typeof evt !== 'string') {
throw new Error(progress.data._getMsgText("jsdoMSG033", this.toString(),
"unsubscribe", progress.data._getMsgText("jsdoMSG037")));
}
this._events = this._events || {};
evt = evt.toLowerCase();
listenerData = {fn: undefined, scope: undefined, operation: undefined};
try {
this.validateSubscribe(arguments, evt, listenerData);
} catch (e) {
// throw new Error("Invalid signature for unsubscribe. " + e.message);
throw new Error(progress.data._getMsgText("jsdoMSG033", this.toString(),
"unsubscribe", e.message));
}
observers = this._events[evt] || [];
if (observers.length > 0) {
this._events[evt] = _filterObservers(observers, listenerData.fn,
listenerData.scope, listenerData.operation);
}
return this;
};
/*
* trigger an event of the given name, and pass the specified data to
* the subscribers of the event. Event name is not case sensitive.
* A variable numbers of arguments can be passed as arguments to the event handler.
*
* This method has two signatures
* Signature 1:
* @param evt The name of the event to fire. String. Not case sensitive.
* @param operation The name of the operation. String. Case sensitive
* @param args Optional. A variable number of arguments to pass to the event handlers.
*
* Signature 2:
* @param evt The name of the event to fire. String. Not case sensitive
* @param args Optional. A variable number of arguments to pass to the event handlers.
*/
this.trigger = function (evt, operation, args) {
var observers,
op;
if (!evt) {
throw new Error(progress.data._getMsgText("jsdoMSG037", this.toString(), "trigger"));
}
this._events = this._events || {};
evt = evt.toLowerCase();
observers = this._events[evt] || [];
if (observers.length > 0) {
args = Array.prototype.slice.call(arguments);
if ((arguments.length >= 2)
&& (typeof evt === 'string')
&& (typeof operation === 'string')) {
// in alt format the second argument is the event name,
// and the first is the operation name
op = operation;
args = args.length > 2 ? args.slice(2) : [];
} else if (arguments.length >= 1 && (typeof evt === 'string')) {
op = undefined;
args = args.length > 1 ? args.slice(1) : [];
} else {
throw new Error(progress.data._getMsgText("jsdoMSG033", this.toString(), "trigger"));
}
observers.forEach(function (el) {
if (el.operation === op) {
el.fn.apply(el.scope, args);
}
});
}
return this;
};
// unbind all listeners from the given event. If the
// evt is undefined, then all listeners for all events are unbound
// evnt name is not case sensitive
// @param evt Optional. The name of the event to unbind. If not passed, then all events are unbound
this.unsubscribeAll = function (evt, operation) {
var observers;
if (evt) {
this._events = this._events || {};
if (typeof evt === 'string') {
evt = evt.toLowerCase();
observers = this._events[evt] || [];
observers.forEach(function (el) {
if (el.operation) {
this.unsubscribe(evt, el.operation, el.fn, el.scope);
} else {
this.unsubscribe(evt, el.fn, el.scope);
}
}, this);
}
} else {
this._events = {};
}
return this;
};
};
/**
* Utility class that saves/reads data to localStorage
*
* @returns {progress.data.LocalStorage}
*/
progress.data.LocalStorage = function LocalStorage() {
/*global localStorage */
if (typeof localStorage === "undefined") {
// "progress.data.LocalStorage: No support for localStorage."
throw new Error(progress.data._getMsgText("jsdoMSG126", "progress.data.LocalStorage", "localStorage"));
}
// "Methods"
this.saveToLocalStorage = function (name, dataObj) {
localStorage.setItem(name, JSON.stringify(dataObj));
};
this.readFromLocalStorage = function (name) {
var jsonStr = localStorage.getItem(name),
dataObj = null;
if (jsonStr !== null) {
try {
dataObj = JSON.parse(jsonStr);
} catch (e) {
dataObj = null;
}
}
return dataObj;
};
this.clearLocalStorage = function (name) {
localStorage.removeItem(name);
};
}; // End of LocalStorage
/////////////////////////////////////////////////////////////////////////////////////////
// Utility Functions
/*
* Converts the specified filter object to an OpenEdge ABL Where String.
*
* @param tableRef - handle to the table in jsdo, where string is applied to.
* @param filter - the filter object to convert.
*
* @returns - translated OE where string.
*/
progress.util._convertToABLWhereString = function (tableRef, filter) {
var result = [],
logic = filter.logic || "and",
idx,
length,
field,
fieldInfo,
type,
format,
operator,
value,
ablType,
//filters = (filter.filters) ? filter.filters : [filter],
filters = filter.filters || [filter],
whereOperators = {
eq: "=",
neq: "<>",
gt: ">",
gte: ">=",
lt: "<",
lte: "<=",
contains : "INDEX",
doesnotcontain: "INDEX",
endswith: "R-INDEX",
startswith: "BEGINS",
isnull: "ISNULL",
isnotnull: "ISNOTNULL",
isempty: "ISEMPTY",
isnotempty: "ISNOTEMPTY"
};
for (idx = 0, length = filters.length; idx < length; idx += 1) {
filter = filters[idx];
field = filter.field;
value = filter.value;
if (filter.filters) {
filter = progress.util._convertToABLWhereString(tableRef, filter);
} else {
// Use original field name instead of serialized name
if (field && tableRef._name) {
fieldInfo = tableRef._jsdo[tableRef._name]._fields[field.toLowerCase()];
if (fieldInfo && fieldInfo.origName) {
field = fieldInfo.origName;
}
}
operator = whereOperators[filter.operator];
if (operator === undefined) {
throw new Error("The operator " + filter.operator + " is not valid.");
}
switch (filter.operator) {
case "isnull":
case "isnotnull":
case "isempty":
case "isnotempty":
value = undefined;
break;
}
if (operator && value !== undefined) {
type = progress.util._getObjectType(value);
// We need to build a template format string for the where string.
// We'll first add positional info for the value
if (type === STRING_OBJECT_TYPE) {
format = "'{1}'";
value = value.replace(/'/g, "~'");
} else if (type === DATE_OBJECT_TYPE) {
ablType = tableRef._getABLType(filter.field);
if (ablType === "DATE") {
format = "DATE({1:MM, dd, yyyy})";
} else if (ablType === "DATETIME-TZ") {
// zzz here means to translate timezone offset into minutes
format = "DATETIME-TZ({1:MM, dd, yyyy, hh, mm, ss, fff, zzz})";
} else {
format = "DATETIME({1:MM, dd, yyyy, hh, mm, ss, fff})";
}
} else {
format = "{1}";
}
// Most where strings are in the format: field operator value. Ex. custnum < 100
// An exception to this is INDEX() and R-INDEX() which have format: operator field value
// Ex. R-INDEX(name, "LTD")
if (operator === "INDEX" || operator === "R-INDEX") {
if (type !== STRING_OBJECT_TYPE) {
throw new Error("Error parsing filter object. The operator " + filter.operator +
" requires a string value");
}
if (filter.operator === "doesnotcontain") {
format = "{0}(" + "{2}, " + format + ") = 0";
} else if (filter.operator === "contains") {
format = "{0}(" + "{2}, " + format + ") > 0";
} else { // else filter.operator = "endswith"
format = "{2} MATCHES '*{1}'";
}
} else {
format = "{2} {0} " + format;
}
filter = progress.util._format(format, operator, value, field);
} else if (operator && value === undefined) {
if (filter.operator === "isempty" || filter.operator === "isnotempty") {
ablType = tableRef._getABLType(field);
if (ablType !== CHARACTER_ABL_TYPE) {
throw new Error("Error parsing filter object. The operator " + filter.operator +
" requires a CHARACTER field");
}
if (filter.operator === "isempty") {
format = "{2} = ''";
} else if (filter.operator === "isnotempty") {
format = "{2} <> ''";
}
} else {
if (filter.operator === "isnull") {
format = "{2} = ?";
} else if (filter.operator === "isnotnull") {
format = "{2} <> ?";
} else {
format = "{2} {0} ?";
}
}
// format, operator {0}, value {1}, field {2}
filter = progress.util._format(format, operator, value, field);
}
}
result.push(filter);
}
filter = result.join(" " + logic + " ");
if (result.length > 1) {
filter = "(" + filter + ")";
}
return filter;
};
/*
* Converts the specified filter object to an SQL Query String.
*
* @param tableName - tableName of table in jsdo, where clause is applied to.
* @param filter - the filter object to convert.
*
* @returns - translated SQL where clause.
*/
progress.util._convertToSQLQueryString = function (tableRef, filter, addSelect) {
var result = [],
logic = filter.logic || "and",
idx,
length,
field,
type,
format,
operator,
value,
fieldFormat,
filters = filter.filters || [filter],
filterStr,
usingLike = true,
whereOperators = {
eq: "=",
neq: "!=",
gt: ">",
gte: ">=",
lt: "<",
lte: "<=",
contains : "LIKE",
doesnotcontain: "NOT LIKE",
endswith: "LIKE",
startswith: "LIKE",
isnull: "ISNULL",
isnotnull: "ISNOTNULL",
isempty: "ISEMPTY",
isnotempty: "ISNOTEMPTY"
};
if (typeof addSelect === "undefined") {
addSelect = false;
}
for (idx = 0, length = filters.length; idx < length; idx += 1) {
filter = filters[idx];
field = filter.field;
value = filter.value;
if (filter.filters) {
filterStr = progress.util._convertToSQLQueryString(tableRef, filter, false);
} else {
operator = whereOperators[filter.operator];
if (operator === undefined) {
throw new Error("The operator " + filter.operator + " is not valid.");
}
switch (filter.operator) {
case "isnull":
case "isnotnull":
case "isempty":
case "isnotempty":
value = undefined;
break;
}
if (operator && value !== undefined) {
type = progress.util._getObjectType(value);
if (operator === "LIKE" || operator === "NOT LIKE") {
if (type !== STRING_OBJECT_TYPE) {
throw new Error("Error parsing filter object. The operator " + filter.operator +
" requires a string value");
}
}
if (type === STRING_OBJECT_TYPE) {
format = "'{1}'";
value = value.replace(/'/g, "''");
} else if (type === DATE_OBJECT_TYPE) {
fieldFormat = tableRef._getFormat(field);
if (fieldFormat === "date") {
format = "'{1:yyyy-MM-dd}'";
} else if (fieldFormat === "date-time") {
format = "{1:#ISO(iso)}";
} else if (fieldFormat === "time") {
format = "'{1:FFF}'";
}
} else {
format = "{1}";
}
// We need to build a template format string for the where string.
// We'll first add positional info for the value, which is represented by {1}
if (filter.operator === "startswith") {
format = "'{1}%'";
} else if (filter.operator === "endswith") {
format = "'%{1}'";
} else if (filter.operator === "contains" || filter.operator === "doesnotcontain") {
format = "'%{1}%'";
} else {
usingLike = false;
}
if (usingLike) {
value = value.replace(/%/g, '\\%');
value = value.replace(/_/g, '\\_');
}
format = "{2} {0} " + format;
filterStr = progress.util._format(format, operator, value, field);
} else if (operator && value === undefined) {
if (filter.operator === "isempty" || filter.operator === "isnotempty") {
type = tableRef._fields[field.toLowerCase()].type;
if (type !== STRING_OBJECT_TYPE.toLowerCase()) {
throw new Error("Error parsing filter object. The operator " + filter.operator +
" requires a string field");
}
if (filter.operator === "isempty") {
format = "{2} = ''";
} else if (filter.operator === "isnotempty") {
format = "{2} != ''";
}
} else {
if (filter.operator === "isnull") {
format = "{2} IS NULL";
} else if (filter.operator === "isnotnull") {
format = "{2} IS NOT NULL";
} else {
format = "{2} {0} NULL";
}
}
// format, operator {0}, value {1}, field {2}
filterStr = progress.util._format(format, operator, value, field);
}
}
result.push(filterStr);
}
filterStr = result.join(" " + logic + " ");
if (result.length > 1) {
filterStr = "(" + filterStr + ")";
}
if (addSelect === true) {
filterStr = "SELECT * FROM " + tableRef._name + " WHERE " + filterStr;
}
return filterStr;
};
/*
* Returns the object type; Example "String", "Date"
* Constants for object type values are defined above.
*
* @param value - the object whose type is returned
*/
progress.util._getObjectType = function (value) {
// Returns [object xxx]. Removing [object ]
return Object.prototype.toString.call(value).slice(8, -1);
};
/*
* Substitutes in a variable number of arguments into specified format string (with place-holders)
*
* @param fmt - the format string with place-holders, eg. "{0} text {1}".
*
* @returns - formatted string.
*/
progress.util._format = function (fmt) {
/*jslint regexp: true*/
var values = arguments,
formatRegExp = /\{(\d+)(:[^\}]+)?\}/g;
/*jslint regexp: false*/
return fmt.replace(formatRegExp, function (match, index, placeholderFormat) {
var value = values[parseInt(index, 10) + 1];
return progress.util._toString(value, placeholderFormat ? placeholderFormat.substring(1) : "");
});
};
/*
* Converts the specified value param to a string.
*
* @param value - object to convert
* @param fmt - optional format string with place-holders, eg. "MM dd yyyy".
*
* @returns - converted string.
*/
progress.util._toString = function (value, fmt) {
var str;
if (fmt) {
if (progress.util._getObjectType(value) === "Date") {
return progress.util._formatDate(value, fmt);
}
}
if (typeof value === "number") {
str = value.toString();
} else {
str = (value !== undefined ? value : "");
}
return str;
};