-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata-queryable.js
More file actions
3670 lines (3554 loc) · 126 KB
/
data-queryable.js
File metadata and controls
3670 lines (3554 loc) · 126 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 Symbol = require('symbol');
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, MethodCallExpression, MemberExpression, ObjectNameValidator} = require('@themost/query');
var {QueryEntity, Expression} = require('@themost/query');
var {QueryUtils} = require('@themost/query');
var Q = require('q');
var aliasProperty = Symbol('alias');
var {hasOwnProperty} = require('./has-own-property');
var {isObjectDeep} = require('./is-object');
var { UnknownAttributeError } = require('./data-errors');
var { DataExpandResolver } = require('./data-expand-resolver');
var {instanceOf} = require('./instance-of');
/**
* @param {DataQueryable} target
*/
function resolveJoinMember(target) {
return function onResolvingJoinMember(event) {
/**
* @type {Array}
*/
var fullyQualifiedMember = event.fullyQualifiedMember.split('.');
var 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;
}
}
}
}
}
/**
* @param {DataQueryable} target
* @constructor
*/
function DataValueResolver(target) {
Object.defineProperty(this, 'target', { get: function() {
return target;
}, configurable:false, enumerable:false});
}
DataValueResolver.prototype.resolve = function(value) {
/**
* @type {DataQueryable}
*/
var target = this.target;
if (typeof value === 'string' && /^\$it\//.test(value)) {
var attr = value.replace(/^\$it\//,'');
if (DataAttributeResolver.prototype.testNestedAttribute(attr)) {
return DataAttributeResolver.prototype.resolveNestedAttribute.call(target, attr);
}
else {
attr = DataAttributeResolver.prototype.testAttribute(attr);
if (attr) {
return target.fieldOf(attr.name);
}
}
}
// if value is an instance of Expression e.g. an instance if MemberExpression
if (value instanceof Expression) {
// return the expression
return value;
}
if (isObjectDeep(value)) {
// try to get in-process left operand
// noinspection JSUnresolvedReference
var left = target.query.privates && target.query.privates.property;
if (typeof left === 'string' && /\./.test(left)) {
var members = left.split('.');
if (Array.isArray(members)) {
// try to find member mapping
/**
* @type {import('./data-model').DataModel}
*/
var model = target.model;
var mapping;
var attribute;
var index = 0;
var context = target.model.context;
// if the first segment contains the view adapter name
if (members[0] === target.model.viewAdapter) {
// move next
index++;
} else if (target.query.$expand != null) {
// try to find if the first segment is contained in the collection of joined entities
var joins = Array.isArray(target.query.$expand) ? target.query.$expand : [ target.query.$expand ];
if (joins.length) {
var found = joins.find(function(x) {
return x.$entity && x.$entity.$as === members[0];
});
if (found) {
var mapping1 = model.inferMapping(found.$entity.$as);
if (mapping1 && mapping1.associationType === 'junction') {
// get next segment of members
var nextMember = members[index + 1];
if (nextMember === mapping1.associationObjectField) {
// the next segment is the association object field
// e.g. groups/group
model = context.model(mapping1.parentModel);
members[index + 1] = mapping1.parentField;
} else if (nextMember === mapping1.associationValueField) {
// the next segment is the association value field
// e.g. groups/user
model = context.model(mapping1.childModel);
members[index + 1] = mapping1.childField;
} else if (model.name === mapping1.parentModel) {
model = context.model(mapping1.childModel);
} else {
model = context.model(mapping1.parentModel);
}
} else if (found.$entity.model != null) {
model = context.model(found.$entity.model);
} else {
throw new Error(sprintf('Expected a valid mapping for property "%s"', found.$entity.$as));
}
index++;
}
}
}
var mapValue = function(x) {
if (Object.hasOwnProperty.call(x, name)) {
return x[name];
}
throw new Error(sprintf('Invalid value for property "%s"', members[members.length - 1]));
}
while (index < members.length) {
mapping = model.inferMapping(members[index]);
if (mapping) {
if (mapping.associationType === 'association' && mapping.childModel === model.name) {
model = context.model(mapping.parentModel);
if (model) {
attribute = model.getAttribute(mapping.parentField);
}
} else if (mapping.associationType === 'association' && mapping.parentModel === model.name) {
model = context.model(mapping.childModel);
if (model) {
attribute = model.getAttribute(mapping.childField);
}
} else if (mapping.associationType === 'junction' && mapping.childModel === model.name) {
model = context.model(mapping.parentModel);
if (model) {
attribute = model.getAttribute(mapping.parentField);
}
} else if (mapping.associationType === 'junction' && mapping.parentModel === model.name) {
model = context.model(mapping.childModel);
if (model) {
attribute = model.getAttribute(mapping.childField);
}
}
} else {
// if mapping is not found, and we are in the last segment
// try to find if this last segment is a field of the current model
if (index === members.length - 1) {
attribute = model.getAttribute(members[index]);
break;
}
attribute = null;
model = null;
break;
}
index++;
}
if (attribute) {
var name = attribute.property || attribute.name;
if (Array.isArray(value)) {
return value.map(function(x) {
return mapValue(x);
});
} else {
return mapValue(value);
}
}
}
}
}
return value;
}
/**
* @class
* @constructor
* @ignore
*/
function DataAttributeResolver() {
}
DataAttributeResolver.prototype.orderByNestedAttribute = function(attr) {
var nestedAttribute = DataAttributeResolver.prototype.testNestedAttribute(attr);
if (nestedAttribute) {
var matches = /^(\w+)\((\w+)\/(\w+)\)$/i.exec(nestedAttribute.name);
if (matches) {
return DataAttributeResolver.prototype.selectAggregatedAttribute.call(this, matches[1], matches[2] + '/' + matches[3]);
}
matches = /^(\w+)\((\w+)\/(\w+)\/(\w+)\)$/i.exec(nestedAttribute.name);
if (matches) {
return DataAttributeResolver.prototype.selectAggregatedAttribute.call(this, matches[1], matches[2] + '/' + matches[3] + '/' + matches[4]);
}
}
return DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attr);
};
DataAttributeResolver.prototype.selectNestedAttribute = function(attr, alias) {
var expr = DataAttributeResolver.prototype.resolveNestedAttribute.call(this, attr);
if (expr) {
if (_.isNil(alias))
expr.as(attr.replace(/\//g,'_'));
else
expr.as(alias)
}
return expr;
};
/**
* @param {string} aggregation
* @param {string} attribute
* @param {string=} alias
* @returns {*}
*/
DataAttributeResolver.prototype.selectAggregatedAttribute = function(aggregation, attribute, alias) {
var self=this, result;
if (DataAttributeResolver.prototype.testNestedAttribute(attribute)) {
result = DataAttributeResolver.prototype.selectNestedAttribute.call(self,attribute, alias);
}
else {
result = self.fieldOf(attribute);
}
var sAlias = result.as(), name = result.getName(), expr;
if (sAlias) {
expr = result[sAlias];
result[sAlias] = { };
result[sAlias]['$' + aggregation ] = expr;
}
else {
expr = result.$name;
result[name] = { };
result[name]['$' + aggregation ] = expr;
}
return result;
};
DataAttributeResolver.prototype.resolveNestedAttribute = function(attr) {
var self = this;
if (typeof attr === 'string' && /\//.test(attr)) {
var member = attr.split('/'), expr, arr, obj, select;
//change: 18-Feb 2016
//description: Support many to many (junction) resolving
var mapping = self.model.inferMapping(member[0]);
if (mapping && mapping.associationType === 'junction') {
var expr1 = DataAttributeResolver.prototype.resolveJunctionAttributeJoin.call(self.model, attr);
//select field
select = expr1.$select;
//get expand
expr = expr1.$expand;
}
else {
// create member expression
var memberExpr = {
name: attr
};
// and pass member expression
expr = DataAttributeResolver.prototype.resolveNestedAttributeJoin.call(self.model, memberExpr);
// if the returned expression is an instance of query expression
if (expr && expr.$select instanceof Expression) {
// use it as select expression after converting it to query field
select = new QueryField({
// important note: use $value query property to set the expression
$value: expr.$select.exprOf()
});
} else {
// select field
if (member.length > 2) {
if (memberExpr.name !== attr) {
// get member segments again because they have been modified
member = memberExpr.name.split('/');
}
select = QueryField.select(member[member.length - 1]).from(member[member.length - 2]);
} else {
if (memberExpr.name !== attr) {
// get member segments again because they have been modified
member = memberExpr.name.split('/');
}
// and create query field expression
select = QueryField.select(member[1]).from(member[0]);
}
}
}
if (expr) {
// if expand expression is an empty array
if (Array.isArray(expr.$expand) && expr.$expand.length === 0) {
// do nothing and return select expression
return select;
}
if (_.isNil(self.query.$expand)) {
self.query.$expand = expr;
}
else {
arr = [];
if (!_.isArray(self.query.$expand)) {
arr.push(self.query.$expand);
this.query.$expand = arr;
}
arr = [];
if (_.isArray(expr))
arr.push.apply(arr, expr);
else
arr.push(expr);
arr.forEach(function(y) {
obj = self.query.$expand.find(function(x) {
if (x.$entity && x.$entity.$as) {
return (x.$entity.$as === y.$entity.$as);
}
return false;
});
if (typeof obj === 'undefined') {
self.query.$expand.push(y);
}
});
}
return select;
}
else {
throw new Error('Member join expression cannot be empty at this context');
}
}
};
/**
*
* @param {*} memberExpr - A string that represents a member expression e.g. user/id or article/published etc.
* @returns {*} - An object that represents a query join expression
*/
DataAttributeResolver.prototype.resolveNestedAttributeJoin = function(memberExpr) {
var self = this, childField, parentField, res, expr, entity;
var memberExprString;
if (typeof memberExpr === 'string') {
memberExprString = memberExpr;
}
else if (typeof memberExpr === 'object' && hasOwnProperty(memberExpr, 'name')) {
memberExprString = memberExpr.name
}
if (/\//.test(memberExprString)) {
//if the specified member contains '/' e.g. user/name then prepare join
var arrMember = memberExprString.split('/');
var attrMember = self.field(arrMember[0]);
if (attrMember == null) {
throw new UnknownAttributeError(self.name, arrMember[0]);
}
//search for field mapping
var mapping = self.inferMapping(arrMember[0]);
if (_.isNil(mapping)) {
// add support for json objects
if (attrMember.type === 'Json') {
var collection = self[aliasProperty] || self.viewAdapter;
var objectPath = arrMember.join('.');
var objectGet = new MethodCallExpression('jsonGet', [
new MemberExpression(collection + '.' + objectPath)
]);
return {
$select: objectGet,
$expand: []
}
}
throw new Error(sprintf('The target model does not have an association defined for attribute named %s',arrMember[0]));
}
if (mapping.childModel===self.name && mapping.associationType==='association') {
/**
* @type {import('./data-model').DataModel}
*/
var parentModel = self.context.model(mapping.parentModel);
if (_.isNil(parentModel)) {
throw new Error(sprintf('Association parent model (%s) cannot be found.', mapping.parentModel));
}
childField = self.field(mapping.childField);
if (_.isNil(childField)) {
throw new Error(sprintf('Association field (%s) cannot be found.', mapping.childField));
}
parentField = parentModel.field(mapping.parentField);
if (_.isNil(parentField)) {
throw new Error(sprintf('Referenced field (%s) cannot be found.', mapping.parentField));
}
// get childField.name or childField.property
var childFieldName = childField.property || childField.name;
/**
* store temp query expression
* @type {import('@themost/query').QueryExpression}
*/
res =QueryUtils.query(self.viewAdapter).select(['*']);
expr = QueryUtils.query().where(QueryField.select(childField.name)
.from(self[aliasProperty] || self.viewAdapter))
.equal(QueryField.select(mapping.parentField).from(childFieldName));
entity = new QueryEntity(parentModel.viewAdapter).as(childFieldName).left();
res.join(entity).with(expr);
Object.defineProperty(entity, 'model', {
configurable: true,
enumerable: false,
writable: true,
value: parentModel.name
});
if (arrMember.length>2) {
parentModel[aliasProperty] = mapping.childField;
expr = DataAttributeResolver.prototype.resolveNestedAttributeJoin.call(parentModel, arrMember.slice(1).join('/'));
return [].concat(res.$expand).concat(expr);
} else {
// validate attribute name
var attribute = parentModel.getAttribute(arrMember[1]);
Args.check(attribute != null, new UnknownAttributeError(parentModel.name, arrMember[1]));
}
//--set active field
return res.$expand;
}
else if (mapping.parentModel===self.name && mapping.associationType==='association') {
var childModel = self.context.model(mapping.childModel);
if (_.isNil(childModel)) {
throw new Error(sprintf('Association child model (%s) cannot be found.', mapping.childModel));
}
childField = childModel.field(mapping.childField);
if (_.isNil(childField)) {
throw new Error(sprintf('Association field (%s) cannot be found.', mapping.childField));
}
parentField = self.field(mapping.parentField);
if (_.isNil(parentField)) {
throw new Error(sprintf('Referenced field (%s) cannot be found.', mapping.parentField));
}
// get parent entity name for this expression
var parentEntity = self[aliasProperty] || self.viewAdapter;
// get child entity name for this expression
var childEntity = arrMember[0];
res =QueryUtils.query('Unknown').select(['*']);
expr = QueryUtils.query().where(QueryField.select(parentField.name).from(parentEntity)).equal(QueryField.select(childField.name).from(childEntity));
entity = new QueryEntity(childModel.viewAdapter).as(childEntity).left();
res.join(entity).with(expr);
Object.defineProperty(entity, 'model', {
configurable: true,
enumerable: false,
writable: true,
value: childModel.name
});
if (arrMember.length>2) {
// set joined entity alias
childModel[aliasProperty] = childEntity;
// resolve additional joins
expr = DataAttributeResolver.prototype.resolveNestedAttributeJoin.call(childModel, arrMember.slice(1).join('/'));
// concat and return joins
return [].concat(res.$expand).concat(expr);
} else {
// get child model member
var childMember = childModel.field(arrMember[1]);
if (childMember) {
// try to validate if child member has an alias or not
if (childMember.name !== arrMember[1]) {
arrMember[1] = childMember.name;
// set memberExpr
if (typeof memberExpr === 'object' && Object.prototype.hasOwnProperty.call(memberExpr, 'name')) {
memberExpr.name = arrMember.join('/');
}
}
} else {
throw new UnknownAttributeError(childModel.name, arrMember[1]);
}
}
return res.$expand;
}
else {
throw new Error(sprintf('The association type between %s and %s model is not supported for filtering, grouping or sorting data.', mapping.parentModel , mapping.childModel));
}
}
};
/**
* @param {string} s
* @returns {*}
*/
DataAttributeResolver.prototype.testAttribute = function(s) {
if (typeof s !== 'string')
return;
/**
* @private
*/
var matches;
/**
* attribute aggregate function with alias e.g. f(x) as a
* @ignore
*/
matches = /^(\w+)\((\w+)\)\sas\s([\u0020-\u007F\u0080-\uFFFF]+)$/i.exec(s);
if (matches) {
return { name: matches[1] + '(' + matches[2] + ')' , property:matches[3] };
}
/**
* attribute aggregate function with alias e.g. x as a
* @ignore
*/
matches = /^(\w+)\sas\s([\u0020-\u007F\u0080-\uFFFF]+)$/i.exec(s);
if (matches) {
return { name: matches[1] , property:matches[2] };
}
/**
* attribute aggregate function with alias e.g. f(x)
* @ignore
*/
matches = /^(\w+)\((\w+)\)$/i.exec(s);
if (matches) {
return { name: matches[1] + '(' + matches[2] + ')' };
}
// only attribute e.g. x
if (/^(\w+)$/.test(s)) {
return { name: s};
}
};
/**
* @param {string} s
* @returns {*}
*/
DataAttributeResolver.prototype.testAggregatedNestedAttribute = function(s) {
if (typeof s !== 'string')
return null;
var matches;
var pattern = (ObjectNameValidator.validator && ObjectNameValidator.validator.pattern) || new RegExp(ObjectNameValidator.Patterns.Default);
var exprFuncWithAlias = new RegExp('^(\\w+)\\((\\w+(?:\\/\\w+)+)\\)(?:\\s+as\\s+' + pattern.source + ')?$');
matches = exprFuncWithAlias.exec(s);
if (matches) {
// matches[1]: the function name
// matches[2]: the nested attribute
// matches[3]: the alias (optional)
return { aggr: matches[1], name: matches[2], property: matches[3] };
}
};
/**
* @param {string} s
* @returns {*}
*/
DataAttributeResolver.prototype.testNestedAttribute = function(s) {
if (typeof s !== 'string')
return null;
var matches;
var pattern = (ObjectNameValidator.validator && ObjectNameValidator.validator.pattern) || new RegExp(ObjectNameValidator.Patterns.Default);
var exprFuncWithAlias = new RegExp('^(\\w+)\\((\\w+(?:\\/\\w+)+)\\)(?:\\s+as\\s+' + pattern.source + ')?$');
matches = exprFuncWithAlias.exec(s);
if (matches) {
// matches[1]: the function name
// matches[2]: the nested attribute
// matches[3]: the alias (optional)
return { name: matches[2], property: matches[3] };
}
var exprWithAlias = new RegExp('^(\\w+(?:\\/\\w+)+)(\\s+as\\s+' + pattern.source + ')?$')
/**
* nested attribute with alias e.g. a/b/../c as a
*/
matches = exprWithAlias.exec(s);
if (matches) {
// matches[2]: the nested attribute
// matches[3]: the alias (optional)
return { name: matches[1], property: matches[3] };
}
};
/**
* @param {string} attr
* @returns {*}
*/
DataAttributeResolver.prototype.resolveJunctionAttributeJoin = function(attr) {
var self = this, member = attr.split('/');
//get the data association mapping
var mapping = self.inferMapping(member[0]);
//if mapping defines a junction between two models
if (mapping && mapping.associationType === 'junction') {
//get field
var field = self.field(member[0]), entity, expr, q;
//first approach (default association adapter)
//the underlying model is the parent model e.g. Group > Group Members
if (mapping.parentModel === self.name) {
q =QueryUtils.query(self.viewAdapter).select(['*']);
//init an entity based on association adapter (e.g. GroupMembers as members)
entity = new QueryEntity(mapping.associationAdapter).as(field.name);
Object.defineProperty(entity, 'model', {
configurable: true,
enumerable: false,
writable: true,
value: mapping.associationAdapter
});
//init join expression between association adapter and current data model
//e.g. Group.id = GroupMembers.parent
expr = QueryUtils.query().where(QueryField.select(mapping.parentField).from(self.viewAdapter))
.equal(QueryField.select(mapping.associationObjectField).from(field.name));
//append join
q.join(entity).with(expr);
//data object tagging
if (typeof mapping.childModel === 'undefined') {
if (field.type === 'Json') {
var objectPath = [
field.name,
mapping.associationValueField,
...member.slice(1)
].join('.');
var objectGet = new MethodCallExpression('jsonGet', [
new MemberExpression(objectPath)
]);
return {
$select: Object.assign(new QueryField(), {
$value: objectGet.exprOf()
}),
$expand: [q.$expand]
}
}
return {
$expand:[q.$expand],
$select:QueryField.select(mapping.associationValueField).from(field.name)
}
}
//return the resolved attribute for futher processing e.g. members.id
if (member[1] === mapping.childField) {
return {
$expand:[q.$expand],
$select:QueryField.select(mapping.associationValueField).from(field.name)
}
}
else {
//get child model
var childModel = self.context.model(mapping.childModel);
if (_.isNil(childModel)) {
throw new DataError('EJUNC','The associated model cannot be found.');
}
// validate attribute name
Args.check(childModel.getAttribute(member[1]) != null, new UnknownAttributeError(childModel.name, member[1]));
//create new join
var alias = field.name + '_' + childModel.name;
entity = new QueryEntity(childModel.viewAdapter).as(alias);
Object.defineProperty(entity, 'model', {
configurable: true,
enumerable: false,
writable: true,
value: childModel.name
});
expr = QueryUtils.query().where(QueryField.select(mapping.associationValueField).from(field.name))
.equal(QueryField.select(mapping.childField).from(alias));
//append join
q.join(entity).with(expr);
return {
$expand:q.$expand,
$select:QueryField.select(member[1]).from(alias)
}
}
}
else {
q =QueryUtils.query(self.viewAdapter).select(['*']);
//the underlying model is the child model
//init an entity based on association adapter (e.g. GroupMembers as groups)
entity = new QueryEntity(mapping.associationAdapter).as(field.name);
//init join expression between association adapter and current data model
//e.g. Group.id = GroupMembers.parent
expr = QueryUtils.query().where(QueryField.select(mapping.childField).from(self.viewAdapter))
.equal(QueryField.select(mapping.associationValueField).from(field.name));
//append join
q.join(entity).with(expr);
//return the resolved attribute for further processing e.g. members.id
if (member[1] === mapping.parentField) {
return {
$expand:[q.$expand],
$select:QueryField.select(mapping.associationObjectField).from(field.name)
}
}
else {
//get parent model
var parentModel = self.context.model(mapping.parentModel);
if (_.isNil(parentModel)) {
throw new DataError('EJUNC','The associated model cannot be found.');
}
//create new join
var parentAlias = field.name + '_' + parentModel.name;
entity = new QueryEntity(parentModel.viewAdapter).as(parentAlias);
Object.defineProperty(entity, 'model', {
configurable: true,
enumerable: false,
writable: true,
value: parentModel.name
});
expr = QueryUtils.query().where(QueryField.select(mapping.associationObjectField).from(field.name))
.equal(QueryField.select(mapping.parentField).from(parentAlias));
//append join
q.join(entity).with(expr);
return {
$expand:q.$expand,
$select:QueryField.select(member[1]).from(parentAlias)
}
}
}
}
else {
throw new DataError('EJUNC','The target model does not have a many to many association defined by the given attribute.','', self.name, attr);
}
};
/**
* @classdesc Represents a dynamic query helper for filtering, paging, grouping and sorting data associated with an instance of DataModel class.
* @class
* @property {import('@themost/query').QueryExpression} query - Gets or sets the current query expression
* @property {DataModel|*} model - Gets or sets the underlying data model
* @constructor
* @param model {DataModel|*}
* @augments DataContextEmitter
*/
function DataQueryable(model) {
/**
* @type {import('@themost/query').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});
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}
*/
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 {DataQueryable}
*/
DataQueryable.prototype.where = function(attr) {
Args.check(this.query.$where == null, new Error('The where expression has already been initialized.'));
// 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));