forked from hiddentao/squel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
squel.js
3608 lines (2853 loc) · 111 KB
/
squel.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
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.squel = factory();
}
}(this, function() {
'use strict';
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// append to string if non-empty
function _pad(str, pad) {
return str.length ? str + pad : str;
}
// Extend given object's with other objects' properties, overriding existing ones if necessary
function _extend(dst) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
if (dst && sources) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function _loop() {
var src = _step.value;
if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) === 'object') {
Object.getOwnPropertyNames(src).forEach(function (key) {
if (typeof src[key] !== 'function') {
dst[key] = src[key];
}
});
}
};
for (var _iterator = sources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_loop();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return dst;
};
// get whether object is a plain object
function _isPlainObject(obj) {
return obj && obj.constructor.prototype === Object.prototype;
};
// get whether object is an array
function _isArray(obj) {
return obj && obj.constructor.prototype === Array.prototype;
};
// get class name of given object
function _getObjectClassName(obj) {
if (obj && obj.constructor && obj.constructor.toString) {
var arr = obj.constructor.toString().match(/function\s*(\w+)/);
if (arr && 2 === arr.length) {
return arr[1];
}
}
}
// clone given item
function _clone(src) {
if (!src) {
return src;
}
if (typeof src.clone === 'function') {
return src.clone();
} else if (_isPlainObject(src) || _isArray(src)) {
var _ret2 = function () {
var ret = new src.constructor();
Object.getOwnPropertyNames(src).forEach(function (key) {
if (typeof src[key] !== 'function') {
ret[key] = _clone(src[key]);
}
});
return {
v: ret
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
} else {
return JSON.parse(JSON.stringify(src));
}
};
/**
* Register a value type handler
*
* Note: this will override any existing handler registered for this value type.
*/
function _registerValueHandler(handlers, type, handler) {
var typeofType = typeof type === 'undefined' ? 'undefined' : _typeof(type);
if (typeofType !== 'function' && typeofType !== 'string') {
throw new Error("type must be a class constructor or string");
}
if (typeof handler !== 'function') {
throw new Error("handler must be a function");
}
for (var idx in handlers) {
var typeHandler = handlers[idx];
if (typeHandler.type === type) {
typeHandler.handler = handler;
return;
}
}
handlers.push({
type: type,
handler: handler
});
};
/**
* Get value type handler for given type
*/
function getValueHandler(value) {
for (var _len2 = arguments.length, handlerLists = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
handlerLists[_key2 - 1] = arguments[_key2];
}
for (var listIdx in handlerLists) {
var handlers = handlerLists[listIdx];
for (var handlerIdx in handlers) {
var typeHandler = handlers[handlerIdx];
// if type is a string then use `typeof` or else use `instanceof`
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === typeHandler.type || typeof typeHandler.type !== 'string' && value instanceof typeHandler.type) {
return typeHandler.handler;
}
}
}
};
/**
* Build base squel classes and methods
*/
function _buildSquel() {
var flavour = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
var cls = {
_getObjectClassName: _getObjectClassName
};
// default query builder options
cls.DefaultQueryBuilderOptions = {
// If true then table names will be rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
autoQuoteTableNames: false,
// If true then field names will rendered inside quotes. The quote character used is configurable via the nameQuoteCharacter option.
autoQuoteFieldNames: false,
// If true then alias names will rendered inside quotes. The quote character used is configurable via the `tableAliasQuoteCharacter` and `fieldAliasQuoteCharacter` options.
autoQuoteAliasNames: true,
// If true then table alias names will rendered after AS keyword.
useAsForTableAliasNames: false,
// The quote character used for when quoting table and field names
nameQuoteCharacter: '`',
// The quote character used for when quoting table alias names
tableAliasQuoteCharacter: '`',
// The quote character used for when quoting table alias names
fieldAliasQuoteCharacter: '"',
// Custom value handlers where key is the value type and the value is the handler function
valueHandlers: [],
// Character used to represent a parameter value
parameterCharacter: '?',
// Numbered parameters returned from toParam() as $1, $2, etc.
numberedParameters: false,
// Numbered parameters prefix character(s)
numberedParametersPrefix: '$',
// Numbered parameters start at this number.
numberedParametersStartAt: 1,
// If true then replaces all single quotes within strings. The replacement string used is configurable via the `singleQuoteReplacement` option.
replaceSingleQuotes: false,
// The string to replace single quotes with in query strings
singleQuoteReplacement: '\'\'',
// String used to join individual blocks in a query when it's stringified
separator: ' '
};
// Global custom value handlers for all instances of builder
cls.globalValueHandlers = [];
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Custom value types
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
// Register a new value handler
cls.registerValueHandler = function (type, handler) {
_registerValueHandler(cls.globalValueHandlers, type, handler);
};
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# Base classes
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
// Base class for cloneable builders
cls.Cloneable = function () {
function _class() {
_classCallCheck(this, _class);
}
_createClass(_class, [{
key: 'clone',
/**
* Clone this builder
*/
value: function clone() {
var newInstance = new this.constructor();
return _extend(newInstance, _clone(_extend({}, this)));
}
}]);
return _class;
}();
// Base class for all builders
cls.BaseBuilder = function (_cls$Cloneable) {
_inherits(_class2, _cls$Cloneable);
/**
* Constructor.
* this.param {Object} options Overriding one or more of `cls.DefaultQueryBuilderOptions`.
*/
function _class2(options) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class2).call(this));
var defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions));
_this.options = _extend({}, defaults, options);
return _this;
}
/**
* Register a custom value handler for this builder instance.
*
* Note: this will override any globally registered handler for this value type.
*/
_createClass(_class2, [{
key: 'registerValueHandler',
value: function registerValueHandler(type, handler) {
_registerValueHandler(this.options.valueHandlers, type, handler);
return this;
}
/**
* Sanitize given expression.
*/
}, {
key: '_sanitizeExpression',
value: function _sanitizeExpression(expr) {
// If it's not an Expression builder instance
if (!(expr instanceof cls.Expression)) {
// It must then be a string
if (typeof expr !== "string") {
throw new Error("expression must be a string or Expression instance");
}
}
return expr;
}
/**
* Sanitize the given name.
*
* The 'type' parameter is used to construct a meaningful error message in case validation fails.
*/
}, {
key: '_sanitizeName',
value: function _sanitizeName(value, type) {
if (typeof value !== "string") {
throw new Error(type + ' must be a string');
}
return value;
}
}, {
key: '_sanitizeField',
value: function _sanitizeField(item) {
if (!(item instanceof cls.BaseBuilder)) {
item = this._sanitizeName(item, "field name");
}
return item;
}
}, {
key: '_sanitizeQueryBuilder',
value: function _sanitizeQueryBuilder(item) {
if (item instanceof cls.QueryBuilder) {
return item;
}
throw new Error("must be a QueryBuilder instance");
}
}, {
key: '_sanitizeTable',
value: function _sanitizeTable(item) {
if (typeof item !== "string") {
try {
item = this._sanitizeQueryBuilder(item);
} catch (e) {
throw new Error("table name must be a string or a query builder");
}
} else {
item = this._sanitizeName(item, 'table');
}
return item;
}
}, {
key: '_sanitizeTableAlias',
value: function _sanitizeTableAlias(item) {
return this._sanitizeName(item, "table alias");
}
}, {
key: '_sanitizeFieldAlias',
value: function _sanitizeFieldAlias(item) {
return this._sanitizeName(item, "field alias");
}
// Sanitize the given limit/offset value.
}, {
key: '_sanitizeLimitOffset',
value: function _sanitizeLimitOffset(value) {
value = parseInt(value);
if (0 > value || isNaN(value)) {
throw new Error("limit/offset must be >= 0");
}
return value;
}
// Santize the given field value
}, {
key: '_sanitizeValue',
value: function _sanitizeValue(item) {
var itemType = typeof item === 'undefined' ? 'undefined' : _typeof(item);
if (null === item) {
// null is allowed
} else if ("string" === itemType || "number" === itemType || "boolean" === itemType) {
// primitives are allowed
} else if (item instanceof cls.BaseBuilder) {
// Builders allowed
} else {
var typeIsValid = !!getValueHandler(item, this.options.valueHandlers, cls.globalValueHandlers);
if (!typeIsValid) {
throw new Error("field value must be a string, number, boolean, null or one of the registered custom value types");
}
}
return item;
}
// Escape a string value, e.g. escape quotes and other characters within it.
}, {
key: '_escapeValue',
value: function _escapeValue(value) {
return !this.options.replaceSingleQuotes ? value : value.replace(/\'/g, this.options.singleQuoteReplacement);
}
}, {
key: '_formatTableName',
value: function _formatTableName(item) {
if (this.options.autoQuoteTableNames) {
var quoteChar = this.options.nameQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return item;
}
}, {
key: '_formatFieldAlias',
value: function _formatFieldAlias(item) {
if (this.options.autoQuoteAliasNames) {
var quoteChar = this.options.fieldAliasQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return item;
}
}, {
key: '_formatTableAlias',
value: function _formatTableAlias(item) {
if (this.options.autoQuoteAliasNames) {
var quoteChar = this.options.tableAliasQuoteCharacter;
item = '' + quoteChar + item + quoteChar;
}
return this.options.useAsForTableAliasNames ? 'AS ' + item : item;
}
}, {
key: '_formatFieldName',
value: function _formatFieldName(item) {
var _this2 = this;
var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (this.options.autoQuoteFieldNames) {
(function () {
var quoteChar = _this2.options.nameQuoteCharacter;
if (formattingOptions.ignorePeriodsForFieldNameQuotes) {
// a.b.c -> `a.b.c`
item = '' + quoteChar + item + quoteChar;
} else {
// a.b.c -> `a`.`b`.`c`
item = item.split('.').map(function (v) {
// treat '*' as special case (#79)
return '*' === v ? v : '' + quoteChar + v + quoteChar;
}).join('.');
}
})();
}
return item;
}
// Format the given custom value
}, {
key: '_formatCustomValue',
value: function _formatCustomValue(value) {
var asParam = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
// user defined custom handlers takes precedence
var customHandler = getValueHandler(value, this.options.valueHandlers, cls.globalValueHandlers);
// use the custom handler if available
if (customHandler) {
value = customHandler(value, asParam);
}
return value;
}
/**
* Format given value for inclusion into parameter values array.
*/
}, {
key: '_formatValueForParamArray',
value: function _formatValueForParamArray(value) {
var _this3 = this;
if (_isArray(value)) {
return value.map(function (v) {
return _this3._formatValueForParamArray(v);
});
} else {
return this._formatCustomValue(value, true);
}
}
/**
* Format the given field value for inclusion into the query string
*/
}, {
key: '_formatValueForQueryString',
value: function _formatValueForQueryString(value) {
var _this4 = this;
var formattingOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var customFormattedValue = this._formatCustomValue(value);
// if formatting took place then return it directly
if (customFormattedValue !== value) {
return this._applyNestingFormatting(customFormattedValue);
}
// if it's an array then format each element separately
if (_isArray(value)) {
value = value.map(function (v) {
return _this4._formatValueForQueryString(v);
});
value = this._applyNestingFormatting(value.join(', '));
} else {
var typeofValue = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (null === value) {
value = "NULL";
} else if (typeofValue === "boolean") {
value = value ? "TRUE" : "FALSE";
} else if (value instanceof cls.BaseBuilder) {
value = this._applyNestingFormatting(value.toString());
} else if (typeofValue !== "number") {
if (formattingOptions.dontQuote) {
value = '' + value;
} else {
var escapedValue = this._escapeValue(value);
value = '\'' + escapedValue + '\'';
}
}
}
return value;
}
}, {
key: '_applyNestingFormatting',
value: function _applyNestingFormatting(str) {
var nesting = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (str && typeof str === 'string' && nesting) {
// don't want to apply twice
if ('(' !== str.charAt(0) || ')' !== str.charAt(str.length - 1)) {
return '(' + str + ')';
}
}
return str;
}
/**
* Build given string and its corresponding parameter values into
* output.
*
* @param {String} str
* @param {Array} values
* @param {Object} [options] Additional options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @param {Boolean} [options.formattingOptions] Formatting options for values in query string.
* @return {Object}
*/
}, {
key: '_buildString',
value: function _buildString(str, values) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var nested = options.nested;
var buildParameterized = options.buildParameterized;
var formattingOptions = options.formattingOptions;
values = values || [];
str = str || '';
var formattedStr = '',
curValue = -1,
formattedValues = [];
var paramChar = this.options.parameterCharacter;
var idx = 0;
while (str.length > idx) {
// param char?
if (str.substr(idx, paramChar.length) === paramChar) {
var value = values[++curValue];
if (buildParameterized) {
if (value instanceof cls.BaseBuilder) {
var ret = value._toParamString({
buildParameterized: buildParameterized,
nested: true
});
formattedStr += ret.text;
formattedValues.push.apply(formattedValues, _toConsumableArray(ret.values));
} else {
value = this._formatValueForParamArray(value);
if (_isArray(value)) {
// Array(6) -> "(??, ??, ??, ??, ??, ??)"
var tmpStr = value.map(function () {
return paramChar;
}).join(', ');
formattedStr += '(' + tmpStr + ')';
formattedValues.push.apply(formattedValues, _toConsumableArray(value));
} else {
formattedStr += paramChar;
formattedValues.push(value);
}
}
} else {
formattedStr += this._formatValueForQueryString(value, formattingOptions);
}
idx += paramChar.length;
} else {
formattedStr += str.charAt(idx);
idx++;
}
}
return {
text: this._applyNestingFormatting(formattedStr, !!nested),
values: formattedValues
};
}
/**
* Build all given strings and their corresponding parameter values into
* output.
*
* @param {Array} strings
* @param {Array} strValues array of value arrays corresponding to each string.
* @param {Object} [options] Additional options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @return {Object}
*/
}, {
key: '_buildManyStrings',
value: function _buildManyStrings(strings, strValues) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var totalStr = [],
totalValues = [];
for (var idx in strings) {
var inputString = strings[idx],
inputValues = strValues[idx];
var _buildString2 = this._buildString(inputString, inputValues, {
buildParameterized: options.buildParameterized,
nested: false
});
var text = _buildString2.text;
var values = _buildString2.values;
totalStr.push(text);
totalValues.push.apply(totalValues, _toConsumableArray(values));
}
totalStr = totalStr.join(this.options.separator);
return {
text: totalStr.length ? this._applyNestingFormatting(totalStr, !!options.nested) : '',
values: totalValues
};
}
/**
* Get parameterized representation of this instance.
*
* @param {Object} [options] Options.
* @param {Boolean} [options.buildParameterized] Whether to build paramterized string. Default is false.
* @param {Boolean} [options.nested] Whether this expression is nested within another.
* @return {Object}
*/
}, {
key: '_toParamString',
value: function _toParamString(options) {
throw new Error('Not yet implemented');
}
/**
* Get the expression string.
* @return {String}
*/
}, {
key: 'toString',
value: function toString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return this._toParamString(options).text;
}
/**
* Get the parameterized expression string.
* @return {Object}
*/
}, {
key: 'toParam',
value: function toParam() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return this._toParamString(_extend({}, options, {
buildParameterized: true
}));
}
}]);
return _class2;
}(cls.Cloneable);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Expressions
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/**
* An SQL expression builder.
*
* SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
*
* Expressions can be nested. Nested expression contains can themselves
* contain nested expressions. When rendered a nested expression will be
* fully contained within brackets.
*
* All the build methods in this object return the object instance for chained method calling purposes.
*/
cls.Expression = function (_cls$BaseBuilder) {
_inherits(_class3, _cls$BaseBuilder);
// Initialise the expression.
function _class3(options) {
_classCallCheck(this, _class3);
var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class3).call(this, options));
_this5._nodes = [];
return _this5;
}
// Combine the current expression with the given expression using the intersection operator (AND).
_createClass(_class3, [{
key: 'and',
value: function and(field, operator) {
for (var _len3 = arguments.length, params = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
params[_key3 - 2] = arguments[_key3];
}
return this._add('AND', field, operator, params);
}
// Combine the current expression with the given expression using the union operator (OR).
}, {
key: 'or',
value: function or(field, operator) {
for (var _len4 = arguments.length, params = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
params[_key4 - 2] = arguments[_key4];
}
return this._add('OR', field, operator, params);
}
}, {
key: '_add',
value: function _add(type, field, operator, params) {
var validOperators = ['=', '<', '>', '<=', '>=', '<>', '!=', 'in', 'not in', 'like', 'not like', 'is', 'is not'];
var expr = void 0;
if (typeof field === 'string' && typeof operator === 'string' && -1 != validOperators.indexOf(operator.toLowerCase())) {
expr = this._buildExpression(field, operator);
} else {
expr = field;
params.unshift(operator);
}
expr = this._sanitizeExpression(expr);
this._nodes.push({
type: type,
expr: expr,
para: params
});
return this;
}
}, {
key: '_buildExpression',
value: function _buildExpression(field, operator) {
var escapedKey = this._formatFieldName(field);
var paramChar = this.options.parameterCharacter;
var condition = escapedKey + ' ' + operator + ' ' + paramChar;
return condition;
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = [],
totalValues = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this._nodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var node = _step2.value;
var type = node.type;
var expr = node.expr;
var para = node.para;
var _ref = expr instanceof cls.Expression ? expr._toParamString({
buildParameterized: options.buildParameterized,
nested: true
}) : this._buildString(expr, para, {
buildParameterized: options.buildParameterized
});
var text = _ref.text;
var values = _ref.values;
if (totalStr.length) {
totalStr.push(type);
}
totalStr.push(text);
totalValues.push.apply(totalValues, _toConsumableArray(values));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
totalStr = totalStr.join(' ');
return {
text: this._applyNestingFormatting(totalStr, !!options.nested),
values: totalValues
};
}
}]);
return _class3;
}(cls.BaseBuilder);
/*
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
# cls.Case
# ---------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------
*/
/**
* An SQL CASE expression builder.
*
* SQL cases are used to select proper values based on specific criteria.
*/
cls.Case = function (_cls$BaseBuilder2) {
_inherits(_class4, _cls$BaseBuilder2);
function _class4(fieldName) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, _class4);
var _this6 = _possibleConstructorReturn(this, Object.getPrototypeOf(_class4).call(this, options));
if (_isPlainObject(fieldName)) {
options = fieldName;
fieldName = null;
}
if (fieldName) {
_this6._fieldName = _this6._sanitizeField(fieldName);
}
_this6.options = _extend({}, cls.DefaultQueryBuilderOptions, options);
_this6._cases = [];
_this6._elseValue = null;
return _this6;
}
_createClass(_class4, [{
key: 'when',
value: function when(expression) {
for (var _len5 = arguments.length, values = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
values[_key5 - 1] = arguments[_key5];
}
this._cases.unshift({
expression: expression,
values: values
});
return this;
}
}, {
key: 'then',
value: function then(result) {
if (this._cases.length == 0) {
throw new Error("when() needs to be called first");
}
this._cases[0].result = result;
return this;
}
}, {
key: 'else',
value: function _else(elseValue) {
this._elseValue = elseValue;
return this;
}
}, {
key: '_toParamString',
value: function _toParamString() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var totalStr = '',
totalValues = [];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this._cases[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var _step3$value = _step3.value;
var expression = _step3$value.expression;
var values = _step3$value.values;