-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata-queryable.js
More file actions
3064 lines (2965 loc) · 99.4 KB
/
data-queryable.js
File metadata and controls
3064 lines (2965 loc) · 99.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 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2022, THEMOST LP All rights reserved
var async = require('async');
var {sprintf} = require('sprintf-js');
var _ = require('lodash');
var {TextUtils} = require('@themost/common');
var {DataMappingExtender} = require('./data-mapping-extensions');
var {DataAssociationMapping} = require('./types');
var {DataError, Args} = require('@themost/common');
var {QueryField, Expression, MethodCallExpression} = require('@themost/query');
var {QueryEntity} = require('@themost/query');
var {QueryUtils} = require('@themost/query');
var Q = require('q');
var {hasOwnProperty} = require('./has-own-property');
var { DataAttributeResolver } = require('./data-attribute-resolver');
var { DataExpandResolver } = require('./data-expand-resolver');
var {instanceOf} = require('./instance-of');
var { DataValueResolver } = require('./data-value-resolver');
/**
* @param {DataQueryable} target
*/
function resolveJoinMember(target) {
return function onResolvingJoinMember(event) {
/**
* @type {Array}
*/
var fullyQualifiedMember = event.fullyQualifiedMember.split('.');
// validate first member
const attribute = target.model.getAttribute(fullyQualifiedMember[0]);
var expr = DataAttributeResolver.prototype.resolveNestedAttribute.call(target, fullyQualifiedMember.join('/'));
if (attribute && attribute.type === 'Json') {
Args.check(expr.$value != null, 'Invalid expression. Expected a JSON expression.');
var [method] = Object.keys(expr.$value); // get method name
var methodWithoutSign = method.replace(/\$/g, '');
var { [method]: args } = expr.$value;
Object.assign(event, {
member: new MethodCallExpression(methodWithoutSign, args)
});
return;
}
if (instanceOf(expr, QueryField)) {
var member = expr.$name.split('.');
Object.assign(event, {
object: member[0],
member: member[1]
})
}
if (expr instanceof Expression) {
Object.assign(event, {
member: expr
})
}
}
}
// eslint-disable-next-line no-unused-vars
function resolveZeroOrOneJoinMember(target) {
/**
* This method tries to resolve a join member e.g. product.productDimensions
* when this member defines a zero-or-one association
*/
return function onResolvingZeroOrOneJoinMember(event) {
/**
* @type {Array<string>}
*/
// eslint-disable-next-line no-unused-vars
var fullyQualifiedMember = event.fullyQualifiedMember.split('.');
}
}
/**
* @param {DataQueryable} target
*/
function resolveMember(target) {
/**
* @param {member:string} event
*/
return function onResolvingMember(event) {
var collection = target.model.viewAdapter;
var member = event.member.replace(new RegExp('^' + collection + '.'), '');
/**
* @type {import('./types').DataAssociationMapping}
*/
var mapping = target.model.inferMapping(member);
if (mapping == null) {
return;
}
/**
* @type {import('./types').DataField}
*/
var attribute = target.model.getAttribute(member);
if (attribute.multiplicity === 'ZeroOrOne') {
var resolveMember = null;
if (mapping.associationType === 'junction' && mapping.parentModel === self.name) {
// expand child field
resolveMember = attribute.name.concat('/', mapping.childField);
} else if (mapping.associationType === 'junction' && mapping.childModel === self.name) {
// expand parent field
resolveMember = attribute.name.concat('/', mapping.parentField);
} else if (mapping.associationType === 'association' && mapping.parentModel === target.model.name) {
var associatedModel = target.model.context.model(mapping.childModel);
resolveMember = attribute.name.concat('/', associatedModel.primaryKey);
}
if (resolveMember) {
// resolve attribute
var expr = DataAttributeResolver.prototype.resolveNestedAttribute.call(target, resolveMember);
if (instanceOf(expr, QueryField)) {
event.member = expr.$name;
}
}
}
}
}
/**
* @classdesc Represents a dynamic query helper for filtering, paging, grouping and sorting data associated with an instance of DataModel class.
* @class
* @property {DataModel|*} model - Gets or sets the underlying data model
* @constructor
* @param model {DataModel|*}
* @augments DataContextEmitter
*/
function DataQueryable(model) {
/**
* @property DataQueryable#query
* @type {import('@themost/query').QueryExpression}
*/
/**
* @type {QueryExpression}
* @private
*/
var q = null;
/**
* Gets or sets an array of expandable models
* @type {Array}
* @private
*/
this.$expand = undefined;
/**
* @type {Boolean}
* @private
*/
this.$flatten = undefined;
/**
* @type {DataModel}
* @private
*/
var m = model;
Object.defineProperty(this, 'query', { get: function() {
if (!q) {
if (!m) {
return null;
}
q = QueryUtils.query(m.viewAdapter);
}
return q;
}, configurable:false, enumerable:false});
this.query
Object.defineProperty(this, 'model', { get: function() {
return m;
}, configurable:false, enumerable:false});
//get silent property
if (m)
this.silent(m.$silent);
}
/**
* Clones the current DataQueryable instance.
* @returns {DataQueryable|*} - The cloned object.
*/
DataQueryable.prototype.clone = function() {
var result = new DataQueryable(this.model);
//set view if any
result.$view = this.$view;
//set silent property
result.$silent = this.$silent;
//set silent property
result.$levels = this.$levels;
//set flatten property
result.$flatten = this.$flatten;
//set expand property
result.$expand = this.$expand;
//set query
_.assign(result.query, this.query);
return result;
};
/**
* Ensures data queryable context and returns the current data context. This function may be overriden.
* @returns {DataContext}
* @ignore
*/
DataQueryable.prototype.ensureContext = function() {
if (this.model!==null)
if (this.model.context!==null)
return this.model.context;
return null;
};
/**
* Serializes the underlying query and clears current filter expression for further filter processing. This operation may be used in complex filtering.
* @param {Boolean=} useOr - Indicates whether an or statement will be used in the resulted statement.
* @returns {DataQueryable}
* @example
//retrieve a list of order
context.model('Order')
.where('orderStatus').equal(1).and('paymentMethod').equal(2)
.prepare().where('orderStatus').equal(2).and('paymentMethod').equal(2)
.prepare(true)
//(((OrderData.orderStatus=1) AND (OrderData.paymentMethod=2)) OR ((OrderData.orderStatus=2) AND (OrderData.paymentMethod=2)))
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.prepare = function(useOr) {
this.query.prepare(useOr);
return this;
};
/**
* Initializes a where expression
* @param attr {string|*} - A string which represents the field name that is going to be used as the left operand of this expression
* @returns this
*/
DataQueryable.prototype.where = function(attr) {
// get arguments as array
var args = Array.from(arguments);
if (typeof args[0] === 'function') {
/**
* @type {import("@themost/query").QueryExpression}
*/
var query = this.query;
var onResolvingJoinMember = resolveJoinMember(this);
query.resolvingJoinMember.subscribe(onResolvingJoinMember);
try {
query.where.apply(query, args);
} finally {
query.resolvingJoinMember.unsubscribe(onResolvingJoinMember);
}
return this;
}
if (typeof attr === 'string' && /\//.test(attr)) {
this.query.where(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attr));
return this;
}
// check if attribute defines a many-to-many association
var mapping = this.model.inferMapping(attr);
if (mapping && mapping.associationType === 'junction') {
// append mapping id e.g. groups -> groups/id or members -> members/id etc
let attrId = attr + '/' + mapping.parentField;
if (mapping.parentModel === this.model.name) {
attrId = attr + '/' + mapping.childField;
}
this.query.where(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attrId));
return this;
}
this.query.where(this.fieldOf(attr));
return this;
};
/**
* Initializes a full-text search expression
* @param {string} text - A string which represents the text we want to search for
* @returns {DataQueryable}
* @example
context.model('Person')
.search('Peter')
.select('description')
.take(25).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.search = function(text) {
var self = this;
// eslint-disable-next-line no-unused-vars
var options = { multiword:true };
var terms = [];
if (typeof text !== 'string') { return self; }
var re = /("(.*?)")|([^\s]+)/g;
var match = re.exec(text);
while(match) {
if (match[2]) {
terms.push(match[2]);
}
else {
terms.push(match[0]);
}
match = re.exec(text);
}
if (terms.length===0) {
return self;
}
self.prepare();
var stringTypes = [ 'Text', 'URL', 'Note' ];
self.model.attributes.forEach(function(x) {
if (x.many) { return; }
var mapping = self.model.inferMapping(x.name);
if (mapping) {
if ((mapping.associationType === 'association') && (mapping.childModel===self.model.name)) {
var parentModel = self.model.context.model(mapping.parentModel);
if (parentModel) {
parentModel.attributes.forEach(function(z) {
if (stringTypes.indexOf(z.type)>=0) {
terms.forEach(function (w) {
if (!/^\s+$/.test(w))
self.or(x.name + '/' + z.name).contains(w);
});
}
});
}
}
}
if (stringTypes.indexOf(x.type)>=0) {
terms.forEach(function (y) {
if (!/^\s+$/.test(y))
self.or(x.name).contains(y);
});
}
});
self.prepare();
return self;
};
DataQueryable.prototype.join = function(model)
{
var self = this;
if (_.isNil(model))
return this;
/**
* @type {DataModel}
*/
var joinModel = self.model.context.model(model);
//validate joined model
if (_.isNil(joinModel))
throw new Error(sprintf('The %s model cannot be found', model));
var arr = self.model.attributes.filter(function(x) { return x.type===joinModel.name; });
if (arr.length===0)
throw new Error(sprintf('An internal error occurred. The association between %s and %s cannot be found', this.model.name ,model));
var mapping = self.model.inferMapping(arr[0].name);
var expr = QueryUtils.query();
expr.where(self.fieldOf(mapping.childField)).equal(joinModel.fieldOf(mapping.parentField));
/**
* @type DataAssociationMapping
*/
var entity = new QueryEntity(joinModel.viewAdapter).left();
//set join entity (without alias and join type)
self.select().query.join(entity).with(expr);
return self;
};
/**
* Prepares a logical AND expression
* @param attr {string} - The name of field that is going to be used in this expression
* @returns {DataQueryable}
* @example
context.model('Order').where('customer').equal(298)
.and('orderStatus').equal(1)
.list().then(function(result) {
//SQL: WHERE ((OrderData.customer=298) AND (OrderData.orderStatus=1)
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.and = function(attr) {
if (typeof attr === 'string' && /\//.test(attr)) {
this.query.and(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attr));
return this;
}
// check if attribute defines a many-to-many association
var mapping = this.model.inferMapping(attr);
if (mapping && mapping.associationType === 'junction') {
// append mapping id e.g. groups -> groups/id or members -> members/id etc
let attrId = attr + '/' + mapping.parentField;
if (mapping.parentModel === this.model.name) {
attrId = attr + '/' + mapping.childField;
}
this.query.where(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attrId));
return this;
}
this.query.and(this.fieldOf(attr));
return this;
};
/**
* Prepares a logical OR expression
* @param attr {string} - The name of field that is going to be used in this expression
* @returns {DataQueryable}
* @example
//((OrderData.orderStatus=1) OR (OrderData.orderStatus=2)
context.model('Order').where('orderStatus').equal(1)
.or('orderStatus').equal(2)
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.or = function(attr) {
if (typeof attr === 'string' && /\//.test(attr)) {
this.query.or(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attr));
return this;
}
// check if attribute defines a many-to-many association
var mapping = this.model.inferMapping(attr);
if (mapping && mapping.associationType === 'junction') {
// append mapping id e.g. groups -> groups/id or members -> members/id etc
let attrId = attr + '/' + mapping.parentField;
if (mapping.parentModel === this.model.name) {
attrId = attr + '/' + mapping.childField;
}
this.query.where(DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attrId));
return this;
}
this.query.or(this.fieldOf(attr));
return this;
};
/**
* @private
* @this DataQueryable
* @memberof DataQueryable#
* @param {*} obj
* @returns {*}
*/
function resolveValue(obj) {
var self = this;
if (typeof obj === 'string' && /^\$it\//.test(obj)) {
var attr = obj.replace(/^\$it\//,'');
if (DataAttributeResolver.prototype.testNestedAttribute(attr)) {
return DataAttributeResolver.prototype.resolveNestedAttribute.call(self, attr);
}
else {
attr = DataAttributeResolver.prototype.testAttribute(attr);
if (attr) {
return self.fieldOf(attr.name);
}
}
}
return obj;
}
/**
* Performs an equality comparison.
* @param obj {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve a list of orders with order status equal to 1
context.model('Order').where('orderStatus').equal(1)
.list().then(function(result) {
//WHERE (OrderData.orderStatus=1)
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.equal = function(obj) {
// check if the given object is an array
if (Array.isArray(obj)) {
var resolver = new DataValueResolver(this);
// and resolve each value separately
this.query.equal(obj.map(function(value) {
return resolver.resolve(value);
}));
return this;
}
this.query.equal(new DataValueResolver(this).resolve(obj));
return this;
};
/**
* Performs an equality comparison.
* @param obj {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve a person with id equal to 299
context.model('Person').where('id').is(299)
.first().then(function(result) {
//WHERE (PersonData.id=299)
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.is = function(obj) {
return this.equal(obj);
};
// noinspection JSUnusedGlobalSymbols
/**
* Prepares a not equal comparison.
* @param obj {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve a list of orders with order status different than 1
context.model('Order')
.where('orderStatus').notEqual(1)
.orderByDescending('orderDate')
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.notEqual = function(obj) {
// check if the given object is an array
if (Array.isArray(obj)) {
var resolver = new DataValueResolver(this);
// and resolve each value separately
this.query.notEqual(obj.map(function(value) {
return resolver.resolve(value);
}));
return this;
}
// otherwise resolve the value
this.query.notEqual(new DataValueResolver(this).resolve(obj));
return this;
};
// noinspection JSUnusedGlobalSymbols
/**
* Prepares a greater than comparison.
* @param obj {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve a list of orders where product price is greater than 800
context.model('Order')
.where('orderedItem/price').greaterThan(800)
.orderByDescending('orderDate')
.select('id','orderedItem/name as productName', 'orderedItem/price as productPrice', 'orderDate')
.take(5)
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //Results:
id productName productPrice orderDate
--- -------------------------------------------- ------------ -----------------------------
304 Apple iMac (27-Inch, 2013 Version) 1336.27 2015-11-27 23:49:17.000+02:00
322 Dell B1163w Mono Laser Multifunction Printer 842.86 2015-11-27 20:16:52.000+02:00
167 Razer Blade (2013) 1553.43 2015-11-27 04:17:08.000+02:00
336 Apple iMac (27-Inch, 2013 Version) 1336.27 2015-11-26 07:25:35.000+02:00
89 Nvidia GeForce GTX 650 Ti Boost 1625.49 2015-11-21 17:29:21.000+02:00
*/
DataQueryable.prototype.greaterThan = function(obj) {
this.query.greaterThan(new DataValueResolver(this).resolve(obj));
return this;
};
/**
* Prepares a greater than or equal comparison.
* @param obj {*} The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve a list of orders where product price is greater than or equal to 800
context.model('Order')
.where('orderedItem/price').greaterOrEqual(800)
.orderByDescending('orderDate')
.take(5)
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.greaterOrEqual = function(obj) {
this.query.greaterOrEqual(new DataValueResolver(this).resolve(obj));
return this;
};
/**
* Prepares a bitwise and comparison.
* @param {*} value - The right operand of the express
* @param {Number=} result - The result of a bitwise and expression
* @returns {DataQueryable}
* @example
//retrieve a list of permissions for model Person and insert permission mask (2)
context.model('Permission')
//prepare bitwise AND (((PermissionData.mask & 2)=2)
.where('mask').bit(2)
.and('privilege').equal('Person')
.and('parentPrivilege').equal(null)
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*
*/
DataQueryable.prototype.bit = function(value, result) {
if (_.isNil(result))
this.query.bit(value, value);
else
this.query.bit(value, result);
return this;
};
/**
* Prepares a lower than comparison
* @param obj {*}
* @returns {DataQueryable}
*/
DataQueryable.prototype.lowerThan = function(obj) {
this.query.lowerThan(new DataValueResolver(this).resolve(obj));
return this;
};
/**
* Prepares a lower than or equal comparison.
* @param obj {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve orders based on payment due date
context.model('Order')
.orderBy('paymentDue')
.where('paymentDue').lowerOrEqual(moment().subtract('days',-7).toDate())
.and('paymentDue').greaterThan(new Date())
.take(10).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.lowerOrEqual = function(obj) {
this.query.lowerOrEqual(new DataValueResolver(this).resolve(obj));
return this;
};
// noinspection JSUnusedGlobalSymbols
/**
* Prepares an ends with comparison
* @param obj {*} - The string to be searched for at the end of a field.
* @returns {DataQueryable}
* @example
//retrieve people whose given name starts with 'D'
context.model('Person')
.where('givenName').startsWith('D')
.take(5).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //Results:
id givenName familyName
--- --------- ----------
257 Daisy Lambert
275 Dustin Brooks
333 Dakota Gallagher
*/
DataQueryable.prototype.startsWith = function(obj) {
this.query.startsWith(obj);
return this;
};
// noinspection JSUnusedGlobalSymbols
/**
* Prepares an ends with comparison
* @param obj {*} - The string to be searched for at the end of a field.
* @returns {DataQueryable}
* @example
//retrieve people whose given name ends with 'y'
context.model('Person')
.where('givenName').endsWith('y')
.take(5).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //Results
id givenName familyName
--- --------- ----------
257 Daisy Lambert
287 Zachary Field
295 Anthony Berry
339 Brittney Hunt
341 Kimberly Wheeler
*/
DataQueryable.prototype.endsWith = function(obj) {
this.query.endsWith(obj);
return this;
};
/**
* Prepares a typical IN comparison.
* @param objs {Array} - An array of values which represents the values to be used in expression
* @returns {DataQueryable}
* @example
//retrieve orders with order status 1 or 2
context.model('Order').where('orderStatus').in([1,2])
.list().then(function(result) {
//WHERE (OrderData.orderStatus IN (1, 2))
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.in = function(objs) {
this.query.in(objs);
return this;
};
/**
* Prepares a typical NOT IN comparison.
* @param objs {Array} - An array of values which represents the values to be used in expression
* @returns {DataQueryable}
* @example
//retrieve orders with order status 1 or 2
context.model('Order').where('orderStatus').notIn([1,2])
.list().then(function(result) {
//WHERE (NOT OrderData.orderStatus IN (1, 2))
done(null, result);
}).catch(function(err) {
done(err);
});
*/
DataQueryable.prototype.notIn = function(objs) {
this.query.notIn(objs);
return this;
};
/**
* Prepares a modular arithmetic operation
* @param {*} obj The value to be compared
* @param {Number} result The result of modular expression
* @returns {DataQueryable}
*/
DataQueryable.prototype.mod = function(obj, result) {
this.query.mod(obj, result);
return this;
};
/**
* Prepares a contains comparison (e.g. a string contains another string).
* @param value {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve person where the given name contains
context.model('Person').select(['id','givenName','familyName'])
.where('givenName').contains('ex')
.list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //The result set of this example may be:
id givenName familyName
--- --------- ----------
297 Alex Miles
353 Alexis Rees
*/
DataQueryable.prototype.contains = function(value) {
this.query.contains(value);
return this;
};
/**
* Prepares a not contains comparison (e.g. a string contains another string).
* @param value {*} - The right operand of the expression
* @returns {DataQueryable}
* @example
//retrieve persons where the given name not contains 'ar'
context.model('Person').select(['id','givenName','familyName'])
.where('givenName').notContains('ar')
.take(5).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //The result set of this example may be:
id givenName familyName
--- --------- ----------
257 Daisy Lambert
259 Peter French
261 Kylie Jordan
263 Maxwell Hall
265 Christian Marshall
*/
DataQueryable.prototype.notContains = function(value) {
this.query.notContains(value);
return this;
};
/**
* Prepares a comparison where the left operand is between two values
* @param {*} value1 - The minimum value
* @param {*} value2 - The maximum value
* @returns {DataQueryable}
* @example
//retrieve products where price is between 150 and 250
context.model('Product')
.where('price').between(150,250)
.take(5).list().then(function(result) {
done(null, result);
}).catch(function(err) {
done(err);
});
@example //The result set of this example may be:
id name model price
--- ------------------------------------------ ------ ------
367 Asus Transformer Book T100 HD2895 224.52
380 Zotac Zbox Nano XS AD13 Plus WC5547 228.05
384 Apple iPad Air ZE6015 177.44
401 Intel Core i7-4960X Extreme Edition SM5853 194.61
440 Bose SoundLink Bluetooth Mobile Speaker II HS5288 155.27
*/
DataQueryable.prototype.between = function(value1, value2) {
const resolver = new DataValueResolver(this);
this.query.between(resolver.resolve(value1), resolver.resolve(value2));
return this;
};
/**
* @this DataQueryable
* @memberOf DataQueryable#
* @param arg
* @returns {*}
* @private
*/
function select_(arg) {
var self = this;
if (typeof arg === 'string' && arg.length===0) {
return;
}
var a = DataAttributeResolver.prototype.testAggregatedNestedAttribute.call(self,arg);
if (a) {
return DataAttributeResolver.prototype.selectAggregatedAttribute.call(self, a.aggr , a.name, a.property);
}
else {
a = DataAttributeResolver.prototype.testNestedAttribute.call(self,arg);
if (a) {
return DataAttributeResolver.prototype.selectNestedAttribute.call(self, a.name, a.property);
}
else {
a = DataAttributeResolver.prototype.testAttribute.call(self,arg);
if (a) {
return self.fieldOf(a.name, a.property);
}
else {
return self.fieldOf(arg);
}
}
}
}
/**
* Selects a field or a collection of fields of the current model.
* @param {...*} attr An array of fields, a field or a view name
* @returns {DataQueryable}
*/
DataQueryable.prototype.select = function(attr) {
var self = this;
var arr;
var expr;
var arg = (arguments.length>1) ? Array.prototype.slice.call(arguments): attr;
// get arguments as array
var args = Array.from(arguments);
if (typeof args[0] === 'function') {
/**
* @type {import("@themost/query").QueryExpression}
*/
var query = this.query;
var onResolvingJoinMember = resolveJoinMember(this);
query.resolvingJoinMember.subscribe(onResolvingJoinMember);
var onResolvingMember = resolveMember(this);
query.resolvingMember.subscribe(onResolvingMember);
try {
query.select.apply(query, args);
} finally {
query.resolvingJoinMember.unsubscribe(onResolvingJoinMember);
query.resolvingMember.unsubscribe(onResolvingMember);
}
return this;
}
if (typeof arg === 'string') {
if (arg==='*') {
//delete select
delete self.query.$select;
return this;
}
//validate field or model view
var field = self.model.field(arg);
if (field) {
//validate field
if (field.many || (field.mapping && field.mapping.associationType === 'junction')) {
self.expand(field.name);
}
else {
arr = [];
arr.push(self.fieldOf(field.name));
}
}
else {
//get data view
self.$view = self.model.dataviews(arg);
//if data view was found
if (self.$view) {
arr = [];
var name;
self.$view.fields.forEach(function(x) {
name = x.name;
field = self.model.field(name);
//if a field with the given name exists in target model
if (field) {
//check if this field has an association mapping
if (field.many || (field.mapping && field.mapping.associationType === 'junction'))
self.expand(field.name);
else
arr.push(self.fieldOf(field.name, x.property));
}
else {
var b = DataAttributeResolver.prototype.testAggregatedNestedAttribute.call(self,name);
if (b) {
expr = DataAttributeResolver.prototype.selectAggregatedAttribute.call(self, b.aggr , b.name);
if (expr) { arr.push(expr); }
}
else {
b = DataAttributeResolver.prototype.testNestedAttribute.call(self,name);
if (b) {
expr = DataAttributeResolver.prototype.selectNestedAttribute.call(self, b.name, x.property);
if (expr) { arr.push(expr); }
}
else {
b = DataAttributeResolver.prototype.testAttribute.call(self,name);
if (b) {
arr.push(self.fieldOf(b.name, x.property));
}
else if (/\./g.test(name)) {
name = name.split('.')[0];
arr.push(self.fieldOf(name));
}
else
{
arr.push(self.fieldOf(name));
}
}
}
}
});
}
//select a field from a joined entity
else {
expr = select_.call(self, arg);
if (expr) {
arr = arr || [];
arr.push(expr);
}
}
}
if (_.isArray(arr)) {
if (arr.length===0)
arr = null;
}
}
else {
//get array of attributes
if (_.isArray(arg)) {
arr = [];
//check if field is a data view
if (arg.length === 1 && typeof arg[0] === 'string') {
if (self.model.dataviews(arg[0])) {
return self.select(arg[0]);
}
}
arg.forEach(function(x) {
if (typeof x === 'string') {
field = self.model.field(x);
if (field) {
if (field.many || (field.mapping && field.mapping.associationType === 'junction')) {
self.expand({
'name':field.name,
'options':field.options
});
}
else {
arr.push(self.fieldOf(field.name));
}
}
//test nested attribute and simple attribute expression
else {
expr = select_.call(self, x);
if (expr) {
arr = arr || [];
arr.push(expr);
}
}
}
else {
//validate if x is an object (QueryField)
arr.push(x);
}
});
}