This repository was archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatter.js
More file actions
1086 lines (1023 loc) · 35.4 KB
/
formatter.js
File metadata and controls
1086 lines (1023 loc) · 35.4 KB
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
/**
* MOST Web Framework
* A JavaScript Web Framework
* http://themost.io
*
* Copyright (c) 2014, Kyriakos Barbounakis k.barbounakis@gmail.com, Anthi Oikonomou anthioikonomou@gmail.com
*
* Released under the BSD3-Clause license
* Date: 2014-07-16
*/
var sqlutils = require('./sql-utils'),
util = require('util'),
_ = require('lodash'),
query = require('./query'),
QueryExpression = query.QueryExpression,
QueryField = query.QueryField;
if (typeof Object.key !== 'function') {
/**
* Gets a string that represents the name of the very first property of an object. This operation may be used in anonymous object types.
* @param obj {*}
* @returns {string}
*/
Object.key = function(obj) {
if (typeof obj === 'undefined' || obj === null)
return null;
for(var prop in obj) {
if (obj.hasOwnProperty(prop))
return prop;
}
return null;
}
}
/**
* Initializes an SQL formatter class.
* @class SqlFormatter
* @constructor
*/
function SqlFormatter() {
//
this.provider = null;
/**
* Gets or sets formatter settings
* @type {{nameFormat: string}|*}
*/
this.settings = {
/**
* Gets or sets a format that is going to be applied in field expression e.g. AS [$1] or AS '$1'.
* @type {string}
*/
nameFormat : '$1',
/**
* Gets or sets a boolean that indicates whether field aliases will forcibly be used even if field expression does not have any alias
* (e.g. SELECT Person.name as name or SELECT Person.name).
* @type {boolean}
*/
forceAlias: false
}
}
/**
* Formats a JSON comparison object to the equivalent sql expression eg. { $gt: 100} as >100, or { $in:[5, 8] } as IN {5,8} etc
* @param {*} comparison
* @returns {string}
*/
SqlFormatter.prototype.formatComparison = function(comparison)
{
var key;
if (_.isNil(comparison))
return '(%s IS NULL)';
if (typeof comparison === 'object')
{
if (comparison instanceof Date) {
return '(%s'.concat(util.format('=%s)',this.escape(comparison)));
}
var compares = [];
for(key in comparison) {
if (comparison.hasOwnProperty(key))
compares.push(key);
}
if (compares.length===0)
return '(%s IS NULL)';
else {
var arr = [];
for (var i = 0; i < compares.length; i++) {
key = compares[i];
if (QueryExpression.ComparisonOperators[key]===undefined)
throw new Error(util.format('Unknown operator %s.', key));
var escapedValue = this.escape(comparison[key]);
switch (key) {
case '$eq': arr.push('(%s'.concat('=',escapedValue,')'));break;
case '$lt': arr.push('(%s'.concat('<',escapedValue,')'));break;
case '$lte': arr.push('(%s'.concat('<=',escapedValue,')'));break;
case '$gt': arr.push('(%s'.concat('>',escapedValue,')'));break;
case '$gte': arr.push('(%s'.concat('>=',escapedValue,')'));break;
case '$ne': arr.push('(NOT %s'.concat('=',escapedValue,')'));break;
case '$in': arr.push('(%s'.concat('(',escapedValue,'))'));break;
case '$nin':arr.push('(NOT %s'.concat('(',escapedValue,'))'));break;
}
}
//join expression
if (arr.length===1)
return arr[0];
else if (arr.length>1) {
return '('.concat(arr.join(' AND '),')');
}
else
return '(%s IS NULL)';
}
}
else
{
return '(%s'.concat(util.format('=%s)',this.escape(comparison)));
}
};
SqlFormatter.prototype.isComparison = function(obj) {
var key = Object.key(obj);
return (/^\$(eq|ne|lt|lte|gt|gte|in|nin|text|regex)$/g.test(key));
};
/**
* Escapes an object or a value and returns the equivalent sql value.
* @param {*} value - A value that is going to be escaped for SQL statements
* @param {boolean=} unquoted - An optional value that indicates whether the resulted string will be quoted or not.
* @returns {string} - The equivalent SQL string value
*/
SqlFormatter.prototype.escape = function(value,unquoted)
{
if (_.isNil(value))
return sqlutils.escape(null);
if (typeof value === 'object')
{
//add an exception for Date object
if (value instanceof Date)
return sqlutils.escape(value);
if (value.hasOwnProperty('$name'))
return this.escapeName(value.$name);
else {
//check if value is a known expression e.g. { $length:"name" }
var keys = _.keys(value),
key0 = keys[0];
if (_.isString(key0) && /^\$/.test(key0) && _.isFunction(this[key0])) {
var exprFunc = this[key0];
//get arguments
var args = _.map(keys, function(x) {
return value[x];
});
return exprFunc.apply(this, args);
}
}
}
if (unquoted)
return value.valueOf();
else
return sqlutils.escape(value);
};
/**
* Escapes an object or a value and returns the equivalent sql value.
* @param {*} value - A value that is going to be escaped for SQL statements
* @param {boolean=} unquoted - An optional value that indicates whether the resulted string will be quoted or not.
* returns {string} - The equivalent SQL string value
*/
SqlFormatter.prototype.escapeConstant = function(value,unquoted)
{
return this.escape(value,unquoted);
};
/**
* Formats a where expression object and returns the equivalen SQL string expression.
* @param {*} where - An object that represents the where expression object to be formatted.
* @returns {string|*}
*/
SqlFormatter.prototype.formatWhere = function(where)
{
var self = this;
//get expression (the first property of the object)
var keys = Object.keys(where), property = keys[0];
if (typeof property === 'undefined')
return '';
//get property value
var propertyValue = where[property];
switch (property) {
case '$not':
return '(NOT ' + self.formatWhere(propertyValue) + ')';
case '$and':
case '$or':
var separator = property==='$or' ? ' OR ' : ' AND ';
//property value must be an array
if (!util.isArray(propertyValue))
throw new Error('Invalid query argument. A logical expression must contain one or more comparison expressions.');
if (propertyValue.length===0)
return '';
return '(' + _.map(propertyValue, function(x) {
return self.formatWhere(x);
}).join(separator) + ')';
default:
var comparison = propertyValue;
var op = null, sql = null;
if (isQueryField_(comparison)) {
op = '$eq';
comparison = {$eq:propertyValue};
}
else if (typeof comparison === 'object' && comparison !== null) {
//get comparison operator
op = Object.keys(comparison)[0];
}
else {
//set default comparison operator to equal
op = '$eq';
comparison = {$eq:propertyValue};
}
//escape property name
var escapedProperty = this.escapeName(property);
switch (op) {
case '$text':
return self.$text({ $name:property}, comparison.$text.$search);
case '$eq':
if (_.isNil(comparison.$eq))
return util.format('(%s IS NULL)', escapedProperty);
return util.format('(%s=%s)', escapedProperty, self.escape(comparison.$eq));
case '$gt':
return util.format('(%s>%s)', escapedProperty, self.escape(comparison.$gt));
case '$gte':
return util.format('(%s>=%s)', escapedProperty, self.escape(comparison.$gte));
case '$lt':
return util.format('(%s<%s)', escapedProperty, self.escape(comparison.$lt));
case '$lte':
return util.format('(%s<=%s)', escapedProperty, self.escape(comparison.$lte));
case '$ne':
if (_.isNil(comparison.$ne))
return util.format('(NOT %s IS NULL)', escapedProperty);
if (comparison!==null)
return util.format('(NOT %s=%s)', escapedProperty, self.escape(comparison.$ne));
else
return util.format('(NOT %s IS NULL)', escapedProperty);
case '$regex':
return this.$regex({ $name:property} , comparison.$regex);
case '$in':
if (util.isArray(comparison.$in)) {
if (comparison.$in.length===0)
return util.format('(%s IN (NULL))', escapedProperty);
sql = '('.concat(escapedProperty,' IN (',_.map(comparison.$in, function (x) {
return self.escape(x!==null ? x: null)
}).join(', '),'))');
return sql;
}
else if (typeof comparison.$in === 'object') {
//try to validate if comparison.$in is a select query expression (sub-query support)
var sq = util._extend(new QueryExpression(), comparison.$in);
if (sq.$select) {
//if sub query is a select expression
return util.format('(%s IN (%s))', escapedProperty, self.format(sq));
}
}
//otherwise throw error
throw new Error('Invalid query argument. An in statement must contain one or more values.');
case '$nin':
if (util.isArray(comparison.$nin)) {
if (comparison.$nin.length===0)
return util.format('(NOT %s IN (NULL))', escapedProperty);
sql = '(NOT '.concat(escapedProperty,' IN (',_.map(comparison.$nin, function (x) {
return self.escape(x!==null ? x: null)
}).join(', '),'))');
return sql;
}
else if (typeof comparison.$in === 'object') {
//try to validate if comparison.$nin is a select query expression (sub-query support)
var sq = util._extend(new QueryExpression(), comparison.$in);
if (sq.$select) {
//if sub query is a select expression
return util.format('(NOT %s IN (%s))', escapedProperty, self.format(sq));
}
}
//otherwise throw error
throw new Error('Invalid query argument. An in statement must contain one or more values.');
default :
//search if current operator (arithmetic, evaluation etc) exists as a formatter function (e.g. function $add(p1,p2) { ... } )
//in this case the first parameter is the defined property e.g. Price
// and the property value contains an array of all others parameters (if any) and the comparison operator
// e.g. { Price: { $add: [5, { $gt:100} ]} } where we are trying to find elements that meet the following query expression: (Price+5)>100
// The identifier <Price> is the first parameter, the constant 5 is the second
var fn = this[op], p0 = property, p1 = comparison[op];
if (typeof fn === 'function')
{
var args = [];
var argn = null;
//push identifier
args.push({ $name:property });
if (util.isArray(p1)) {
//push other parameters
for (var j = 0; j < p1.length-1; j++) {
args.push(p1[j]);
}
//get comparison argument (last item of the arguments' array)
argn = p1[p1.length-1];
}
else {
if (self.isComparison(p1)) {
argn = p1;
}
else {
//get comparison argument (equal)
argn = { $eq: p1.valueOf() };
}
}
//call formatter function
var f0 = fn.apply(this, args);
return self.formatComparison(argn).replace(/%s/g, f0.replace('$','\$'));
}
else {
//equal expression
if (typeof p1 !== 'undefined' && p1!==null)
return util.format('(%s=%s)', property, self.escape(p1));
else
return util.format('(%s IS NULL)', property);
}
}
}
};
// noinspection JSUnusedGlobalSymbols
/**
* Implements startsWith(a,b) expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$startswith = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '';
return util.format('(%s REGEXP \'^%s\')', this.escape(p0), this.escape(p1, true));
};
// noinspection JSUnusedGlobalSymbols
/**
* Implements endsWith(a,b) expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$endswith = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '';
return util.format('(%s REGEXP \'%s$$\')', this.escape(p0), this.escape(p1, true));
};
/**
* Implements regular expression formatting.
* @param {*} p0
* @param {string|*} p1
* @returns {string}
*/
SqlFormatter.prototype.$regex = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '';
return util.format('(%s REGEXP \'%s\')', this.escape(p0), this.escape(p1, true));
};
/**
* Implements length(a) expression formatter.
* @param {*} p0
* @returns {string}
*/
SqlFormatter.prototype.$length = function(p0)
{
return util.format('LENGTH(%s)', this.escape(p0));
};
/**
* Implements length(a) expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$ifnull = function(p0,p1)
{
return util.format('COALESCE(%s,%s)', this.escape(p0), this.escape(p1));
};
/**
* Implements trim(a) expression formatter.
* @param {*} p0
* @returns {string}
*/
SqlFormatter.prototype.$trim = function(p0)
{
return util.format('TRIM(%s)', this.escape(p0));
};
/**
* Implements concat(a,b) expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$concat = function(p0, p1)
{
return util.format('CONCAT(%s,%s)', this.escape(p0), this.escape(p1));
};
/**
* Implements indexOf(str,substr) expression formatter.
* @param {string} p0 The source string
* @param {string} p1 The string to search for
* @returns {string}
*/
SqlFormatter.prototype.$indexof = function(p0, p1)
{
return util.format('(LOCATE(%s,%s)-1)', this.escape(p1), this.escape(p0));
};
SqlFormatter.prototype.$indexOf = SqlFormatter.prototype.$indexof;
/**
* Implements substring(str,pos) expression formatter.
* @param {String} p0 The source string
* @param {Number} pos The starting position
* @param {Number=} length The length of the resulted string
* @returns {string}
*/
SqlFormatter.prototype.$substring = function(p0, pos, length)
{
if (length)
return util.format('SUBSTRING(%s,%s,%s)', this.escape(p0), pos.valueOf()+1, length.valueOf());
else
return util.format('SUBSTRING(%s,%s)', this.escape(p0), pos.valueOf()+1);
};
SqlFormatter.prototype.$substr = SqlFormatter.prototype.$substring;
/**
* Implements lower(str) expression formatter.
* @param {String} p0
* @returns {string}
*/
SqlFormatter.prototype.$tolower = function(p0)
{
return util.format('LOWER(%s)', this.escape(p0));
};
SqlFormatter.prototype.$toLower = SqlFormatter.prototype.$tolower;
/**
* Implements upper(str) expression formatter.
* @param {String} p0
* @returns {string}
*/
SqlFormatter.prototype.$toupper = function(p0)
{
return util.format('UPPER(%s)', this.escape(p0));
};
SqlFormatter.prototype.$toUpper = SqlFormatter.prototype.$toupper;
/**
* Implements contains(a,b) expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$contains = function(p0, p1)
{
return this.$text(p0, p1);
};
/**
* Implements contains(a,b) expression formatter.
* @param {string|*} p0
* @param {string|*} p1
* @returns {string}
*/
SqlFormatter.prototype.$text = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '';
if (p1.valueOf().toString().length==0)
return '';
return util.format('(%s REGEXP \'%s\')', this.escape(p0), this.escape(p1, true));
};
SqlFormatter.prototype.$day = function(p0) { return util.format('DAY(%s)', this.escape(p0)); };
SqlFormatter.prototype.$dayOfMonth = SqlFormatter.prototype.$day;
SqlFormatter.prototype.$month = function(p0) { return util.format('MONTH(%s)', this.escape(p0)); };
SqlFormatter.prototype.$year = function(p0) { return util.format('YEAR(%s)', this.escape(p0)); };
SqlFormatter.prototype.$hour = function(p0) { return util.format('HOUR(%s)', this.escape(p0)); };
SqlFormatter.prototype.$minute = function(p0) { return util.format('MINUTE(%s)', this.escape(p0)); };
SqlFormatter.prototype.$minutes = SqlFormatter.prototype.$minute;
SqlFormatter.prototype.$second = function(p0) { return util.format('SECOND(%s)', this.escape(p0)); };
SqlFormatter.prototype.$seconds = SqlFormatter.prototype.$second;
SqlFormatter.prototype.$date = function(p0) {
return util.format('DATE(%s)', this.escape(p0));
};
SqlFormatter.prototype.$floor = function(p0) { return util.format('FLOOR(%s)', this.escape(p0)); };
SqlFormatter.prototype.$ceiling = function(p0) { return util.format('CEILING(%s)', this.escape(p0)); };
/**
* Implements round(a) expression formatter.
* @param {*} p0
* @param {*=} p1
* @returns {string}
*/
SqlFormatter.prototype.$round = function(p0,p1) {
if (_.isNil(p1))
p1 = 0;
return util.format('ROUND(%s,%s)', this.escape(p0), this.escape(p1));
};
/**
* Implements a + b expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$add = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s + %s)', this.escape(p0), this.escape(p1));
};
/**
* Validates whether the given parameter is a field object or not.
* @param obj
* @returns {boolean}
*/
SqlFormatter.prototype.isField = function(obj) {
if (_.isNil(obj))
return false;
if (typeof obj === 'object')
if (obj.hasOwnProperty('$name'))
return true;
return false;
};
/**
* Implements a - b expression formatter.
* @param {*} p0
* @param {*} p1
* @returns {string}
*/
SqlFormatter.prototype.$sub = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s - %s)', this.escape(p0), this.escape(p1));
};
SqlFormatter.prototype.$subtract = SqlFormatter.prototype.$sub;
/**
* Implements a * b expression formatter.
* @param p0 {*}
* @param p1 {*}
*/
SqlFormatter.prototype.$mul = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s * %s)', this.escape(p0), this.escape(p1));
};
SqlFormatter.prototype.$multiply = SqlFormatter.prototype.$mul;
/**
* Implements a mod b expression formatter.
* @param p0 {*}
* @param p1 {*}
*/
SqlFormatter.prototype.$mod = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s % %s)', this.escape(p0), this.escape(p1));
};
/**
* Implements [a / b] expression formatter.
* @param p0 {*}
* @param p1 {*}
*/
SqlFormatter.prototype.$div = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s / %s)', this.escape(p0), this.escape(p1));
};
SqlFormatter.prototype.$divide = SqlFormatter.prototype.$div;
/**
* Implements [a mod b] expression formatter.
* @param p0 {*}
* @param p1 {*}
*/
SqlFormatter.prototype.$mod = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s % %s)', this.escape(p0), this.escape(p1));
};
/**
* Implements [a & b] bitwise and expression formatter.
* @param p0 {*}
* @param p1 {*}
*/
SqlFormatter.prototype.$bit = function(p0, p1)
{
//validate params
if (_.isNil(p0) || _.isNil(p1))
return '0';
return util.format('(%s & %s)', this.escape(p0), this.escape(p1));
};
/**
*
* @param obj {QueryExpression|*}
* @returns {string}
*/
SqlFormatter.prototype.formatSelect = function(obj)
{
var $this = this, sql = '', escapedEntity;
if (_.isNil(obj.$select))
throw new Error('Select expression cannot be empty at this context.');
//get entity name
var entity = Object.key(obj.$select);
var joins = [];
if (!_.isNil(obj.$expand))
{
if (util.isArray(obj.$expand))
joins=obj.$expand;
else
joins.push(obj.$expand);
}
//get entity fields
var fields = obj.fields();
//if fields is not an array
if (!util.isArray(fields))
throw new Error('Select expression does not contain any fields or the collection of fields is of the wrong type.');
//validate entity reference (if any)
if (obj.$ref && obj.$ref[entity]) {
var entityRef = obj.$ref[entity];
//escape entity ref
escapedEntity = entityRef.$as ? $this.escapeName(entityRef.name) + ' AS ' + $this.escapeName(entityRef.$as) : $this.escapeName(entityRef.name);
}
else {
//escape entity name
escapedEntity = $this.escapeName(entity)
}
//add basic SELECT statement
if (obj.$fixed) {
sql = sql.concat('SELECT * FROM (SELECT ', _.map(fields, function(x) {
return $this.format(x,'%f');
}).join(', '), ') ', escapedEntity);
}
else {
sql = sql.concat(obj.$distinct ? 'SELECT DISTINCT ' : 'SELECT ', _.map(fields, function(x) {
return $this.format(x,'%f');
}).join(', '), ' FROM ', escapedEntity);
}
//add join if any
if (obj.$expand!==null)
{
//enumerate joins
_.forEach(joins, function(x) {
if (x.$entity instanceof QueryExpression) {
//get on statement (the join comparison)
sql = sql.concat(util.format(' INNER JOIN (%s)', $this.format(x.$entity)));
//add alias
if (x.$entity.$alias)
sql = sql.concat(' AS ').concat($this.escapeName(x.$entity.$alias));
}
else {
//get join table name
var table = Object.key(x.$entity);
//get on statement (the join comparison)
var joinType = (x.$entity.$join || 'inner').toUpperCase();
sql = sql.concat(' '+ joinType + ' JOIN ').concat($this.escapeName(table));
//add alias
if (x.$entity.$as)
sql = sql.concat(' AS ').concat($this.escapeName(x.$entity.$as));
}
if (util.isArray(x.$with))
{
if (x.$with.length!==2)
throw new Error('Invalid join comparison expression.');
//get left and right expression
var left = x.$with[0],
right = x.$with[1],
//the default left table is the query entity
leftTable = entity,
//the default right table is the join entity
rightTable = table;
if (typeof left === 'object') {
leftTable = Object.key(left);
}
if (typeof right === 'object') {
rightTable = Object.key(right);
}
var leftFields = left[leftTable], rightFields = right[rightTable] ;
for (var i = 0; i < leftFields.length; i++)
{
var leftExpr = null, rightExpr = null;
if (typeof leftFields[i] === 'object')
leftExpr = leftFields[i];
else {
leftExpr = {};
leftExpr[leftTable] = leftFields[i];
}
if (typeof rightFields[i] === 'object')
rightExpr = rightFields[i];
else {
rightExpr = {};
rightExpr[rightTable] = rightFields[i];
}
sql = sql.concat((i===0) ? ' ON ' : ' AND ', $this.formatField(leftExpr), '=', $this.formatField(rightExpr));
}
}
else {
sql = sql.concat(' ON ', $this.formatWhere(x.$with));
}
});
}
//add WHERE statement if any
if (_.isObject(obj.$where))
{
if (_.isObject(obj.$prepared)) {
var where1 = { $and: [obj.$where, obj.$prepared] };
sql = sql.concat(' WHERE ',this.formatWhere(where1));
}
else {
sql = sql.concat(' WHERE ',this.formatWhere(obj.$where));
}
}
else {
if (_.isObject(obj.$prepared))
sql = sql.concat(' WHERE ',this.formatWhere(obj.$prepared));
}
if (_.isObject(obj.$group))
sql = sql.concat(this.formatGroupBy(obj.$group));
if (_.isObject(obj.$order))
sql = sql.concat(this.formatOrder(obj.$order));
//finally return statement
return sql;
};
/**
*
* @param {QueryExpression} obj
* @returns {string}
*/
SqlFormatter.prototype.formatLimitSelect = function(obj) {
var sql=this.formatSelect(obj);
if (obj.$take) {
if (obj.$skip)
//add limit and skip records
sql= sql.concat(' LIMIT ', obj.$skip.toString() ,', ',obj.$take.toString());
else
//add only limit
sql= sql.concat(' LIMIT ', obj.$take.toString());
}
return sql;
};
SqlFormatter.prototype.formatField = function(obj)
{
var self = this;
if (_.isNil(obj))
return '';
if (typeof obj === 'string')
return obj;
if (util.isArray(obj)) {
return _.map(obj, function(x) {
return x.valueOf();
}).join(', ');
}
if (typeof obj === 'object') {
//if field is a constant e.g. { $value:1000 }
if (obj.hasOwnProperty('$value'))
return this.escapeConstant(obj['$value']);
//get table name
var tableName = Object.key(obj);
var fields = [];
if (!util.isArray(obj[tableName])) {
fields.push(obj[tableName])
}
else {
fields = obj[tableName];
}
return _.map(fields, function(x) {
if (QueryField.fieldNameExpression.test(x.valueOf()))
return self.escapeName(tableName.concat('.').concat(x.valueOf()));
else
return self.escapeName(x.valueOf());
}).join(', ');
}
};
/**
* Formats a order object to the equivalent SQL statement
* @param obj
* @returns {string}
*/
SqlFormatter.prototype.formatOrder = function(obj)
{
var self = this;
if (!util.isArray(obj))
return '';
var sql = _.map(obj, function(x)
{
var f = x.$desc ? x.$desc : x.$asc;
if (_.isNil(f))
throw new Error('An order by object must have either ascending or descending property.');
if (util.isArray(f)) {
return _.map(f, function(a) {
return self.format(a,'%ff').concat(x.$desc ? ' DESC': ' ASC');
}).join(', ');
}
return self.format(f,'%ff').concat(x.$desc ? ' DESC': ' ASC');
}).join(', ');
if (sql.length>0)
return ' ORDER BY '.concat(sql);
return sql;
};
/**
* Formats a group by object to the equivalent SQL statement
* @param obj {Array}
* @returns {string}
*/
SqlFormatter.prototype.formatGroupBy = function(obj)
{
var self = this;
if (!util.isArray(obj))
return '';
var arr = [];
_.forEach(obj, function(x) {
arr.push(self.format(x, '%ff'));
});
var sql = arr.join(', ');
if (sql.length>0)
return ' GROUP BY '.concat(sql);
return sql;
};
/**
* Formats an insert query to the equivalent SQL statement
* @param obj {QueryExpression|*}
* @returns {string}
*/
SqlFormatter.prototype.formatInsert = function(obj)
{
var self= this, sql = '';
if (_.isNil(obj.$insert))
throw new Error('Insert expression cannot be empty at this context.');
//get entity name
var entity = Object.key(obj.$insert);
//get entity fields
var obj1 = obj.$insert[entity];
var props = [];
for(var prop in obj1)
if (obj1.hasOwnProperty(prop))
props.push(prop);
sql = sql.concat('INSERT INTO ', self.escapeName(entity), '(' , _.map(props, function(x) { return self.escapeName(x); }).join(', '), ') VALUES (',
_.map(props, function(x)
{
var value = obj1[x];
return self.escape(value!==null ? value: null);
}).join(', ') ,')');
return sql;
};
/**
* Formats an update query to the equivalent SQL statement
* @param obj {QueryExpression|*}
* @returns {string}
*/
SqlFormatter.prototype.formatUpdate = function(obj)
{
var self= this, sql = '';
if (!_.isObject(obj.$update))
throw new Error('Update expression cannot be empty at this context.');
//get entity name
var entity = Object.key(obj.$update);
//get entity fields
var obj1 = obj.$update[entity];
var props = [];
for(var prop in obj1)
if (obj1.hasOwnProperty(prop))
props.push(prop);
//add basic INSERT statement
sql = sql.concat('UPDATE ', self.escapeName(entity), ' SET ',
_.map(props, function(x)
{
var value = obj1[x];
return self.escapeName(x).concat('=', self.escape(value!==null ? value: null));
}).join(', '));
if (_.isObject(obj.$where))
sql = sql.concat(' WHERE ',this.formatWhere(obj.$where));
return sql;
};
/**
* Formats a delete query to the equivalent SQL statement
* @param obj {QueryExpression|*}
* @returns {string}
*/
SqlFormatter.prototype.formatDelete = function(obj)
{
var sql = '';
if (_.isNil(obj.$delete))
throw new Error('Delete expression cannot be empty at this context.');
//get entity name
var entity = obj.$delete;
//add basic INSERT statement
sql = sql.concat('DELETE FROM ', this.escapeName(entity));
if (_.isObject(obj.$where))
sql = sql.concat(' WHERE ',this.formatWhere(obj.$where));
return sql;
};
SqlFormatter.prototype.escapeName = function(name) {
if (typeof name === 'string')
return name.replace(/(\w+)$|^(\w+)$/g, this.settings.nameFormat);
return name;
};
function isQueryField_(obj) {
if (_.isNil(obj))
return false;
return (obj.constructor) && (obj.constructor.name === 'QueryField');
}
/**
* @param obj {QueryField}
* @param format {string}
* @returns {string|*}
*/
SqlFormatter.prototype.formatFieldEx = function(obj, format)
{
if (_.isNil(obj))
return null;
if (!isQueryField_(obj))
throw new Error('Invalid argument. An instance of QueryField class is expected.');
//get property
var prop = Object.key(obj);
if (_.isNil(prop))
return null;
var useAlias = (format==='%f');
if (prop==='$name') {
return (this.settings.forceAlias && useAlias) ? this.escapeName(obj.$name).concat(' AS ', this.escapeName(obj.name())) : this.escapeName(obj.$name);
}
else {
var expr = obj[prop];
if (_.isNil(expr))
throw new Error('Field definition cannot be empty while formatting.');
if (typeof expr === 'string') {
return useAlias ? this.escapeName(expr).concat(' AS ', this.escapeName(prop)) : expr;
}
//get aggregate expression
var alias = prop;
prop = Object.key(expr);
var name = expr[prop], s;
switch (prop) {
case '$count':
s= util.format('COUNT(%s)',this.escapeName(name));
break;
case '$min':
s= util.format('MIN(%s)',this.escapeName(name));
break;
case '$max':
s= util.format('MAX(%s)',this.escapeName(name));