-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1274 lines (1119 loc) · 38.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Database operations module.
*
* @module x2node-dbos
* @requires module:x2node-common
* @requires module:x2node-records
* @requires module:x2node-pointers
* @requires module:x2node-patches
* @requires module:x2node-validators
* @requires module:x2node-rsparser
* @implements {module:x2node-records.Extension}
*/
'use strict';
const common = require('x2node-common');
const validators = require('x2node-validators');
const rsparser = require('x2node-rsparser');
const DBOFactory = require('./lib/dbo-factory.js');
const placeholders = require('./lib/placeholders.js');
const ValueExpressionContext = require('./lib/value-expression-context.js');
const ValueExpression = require('./lib/value-expression.js');
const filterBuilder = require('./lib/filter-builder.js');
const orderBuilder = require('./lib/order-builder.js');
/////////////////////////////////////////////////////////////////////////////////
// Module
/////////////////////////////////////////////////////////////////////////////////
/**
* Built-in database drivers.
*
* @private
* @constant {Object.<string,function>}
*/
const DRIVERS = {
'mysql': require('./lib/driver/mysql-driver.js'),
'pg': require('./lib/driver/pg-driver.js')
};
/**
* Create new database operations (DBO) factory using the specified database
* driver and the record types library. Once created, the factory instance can be
* used by the application throughout its life cycle.
*
* @param {module:x2node-records~RecordTypesLibrary} recordTypes Record types
* library. The factory builds operations against this library. The library must
* be extended with the <code>x2node-dbos</code> module.
* @param {(string|module:x2node-dbos.DBDriver)} dbDriver Either a built-in
* database driver name, or a custom database driver implementation. Available
* built-in drivers include: "mysql" (for
* {@link https://www.npmjs.com/package/mysql} and compatible others) and "pg"
* (for {@link https://www.npmjs.com/package/pg}).
* @param {Object.<string,*>} [options] Options. If provided, the options are
* passed to the DB driver constructor.
* @returns {module:x2node-dbos~DBOFactory} DBO factory instance.
* @throws {module:x2node-common.X2UsageError} If the provided driver name is
* invalid.
*/
exports.createDBOFactory = function(recordTypes, dbDriver, options) {
// make sure that the record types library is compatible
if (!placeholders.isTagged(recordTypes))
throw new common.X2UsageError(
'Record types library does not have the DBOs extension.');
// get driver instance
let dbDriverInst;
if ((typeof dbDriver) === 'string') {
if (!DRIVERS[dbDriver])
throw new common.X2UsageError(
`Invalid built-in database driver "${dbDriver}".`);
dbDriverInst = new DRIVERS[dbDriver](options);
} else { // custom driver
dbDriverInst = dbDriver;
}
// create and return the factory
return new DBOFactory(dbDriverInst, recordTypes);
};
// export basic DB driver to allow extending
exports.BasicDBDriver = require('./lib/driver/basic-driver.js');
// export placeholders functions
exports.param = placeholders.param;
exports.isParam = placeholders.isParam;
exports.expr = placeholders.expr;
exports.isExpr = placeholders.isExpr;
/**
* Tell if the provided object is supported by the module. Currently, only a
* record types library instance can be tested using this function and it tells
* if the library was constructed with the DBOs extension.
*
* @param {*} obj Object to test.
* @returns {boolean} <code>true</code> if supported by the DBOs module.
*/
exports.isSupported = function(obj) {
return placeholders.isTagged(obj);
};
/////////////////////////////////////////////////////////////////////////////////
// Record Types Library Extension
/////////////////////////////////////////////////////////////////////////////////
/**
* Default id generator property on the library construction context.
*
* @private
* @constant {Symbol}
*/
const DEFAULT_IDGEN = Symbol('DEFAULT_IDGEN');
// requires rsparser extension
exports.requiredExtensions = [ validators, rsparser ];
// extend record types library
exports.extendRecordTypesLibrary = function(ctx, recordTypes) {
// check if extended by the result set parser
if (!rsparser.isSupported(recordTypes))
throw new common.X2UsageError(
'The library must be extended by the RSParser module first.');
// tag the library
if (placeholders.isTagged(recordTypes))
throw new common.X2UsageError(
'The library is already extended by the DBOs module.');
placeholders.tag(recordTypes);
// save default id generator on the context
ctx[DEFAULT_IDGEN] = (recordTypes.definition.defaultIdGenerator || 'auto');
// return it
return recordTypes;
};
/**
* DBOs module specific
* [RecordTypeDescriptor]{@link module:x2node-records~RecordTypeDescriptor}
* extension.
*
* @mixin RecordTypeDescriptorWithDBOs
* @static
*/
/**
* DBOs module specific
* [RecordTypeDescriptor]{@link module:x2node-records~PropertiesContainer}
* extension.
*
* @mixin PropertiesContainerWithDBOs
* @static
*/
/**
* Implicit dependent reference marker on a property definition.
*
* @private
* @constant {Symbol}
*/
const IMPLICIT_DEP_REF = Symbol('IMPLICIT_DEP_REF');
/**
* Super record type definition marker.
*
* @private
* @constant {Symbol}
*/
const SUPER_RECORD_TYPE = Symbol('SUPER_RECORD_TYPE');
// extend record type descriptors and property containers
exports.extendPropertiesContainer = function(ctx, container) {
// process record type descriptor
if ((container.nestedPath.length === 0) &&
!container.definition[SUPER_RECORD_TYPE]) {
// find record meta-info properties
container._recordMetaInfoPropNames = {};
ctx.onContainerComplete(container => {
container.allPropertyNames.forEach(propName => {
const propDesc = container.getPropertyDesc(propName);
if (propDesc.isRecordMetaInfo()) {
const role = propDesc.recordMetaInfoRole;
if (container._recordMetaInfoPropNames[role] !== undefined)
throw new common.X2UsageError(
'Record type ' + String(container.recordTypeName) +
' has more than one ' + role +
' record meta-info property.');
container._recordMetaInfoPropNames[role] = propName;
}
});
});
// set the super type name symbol on the descriptor
const recordTypeName = container.recordTypeName;
const superTypeName = Symbol('$' + recordTypeName);
container._superRecordTypeName = superTypeName;
// create the super type after the library is complete
ctx.onLibraryComplete(recordTypes => {
// base supertype definition
const superTypeDef = {
[SUPER_RECORD_TYPE]: true,
properties: {
'recordTypeName': {
valueType: 'string',
role: 'id',
generator: null
},
'records': {
valueType: 'ref(' + recordTypeName + ')[]',
optional: false,
[IMPLICIT_DEP_REF]: true
},
'count': {
valueType: 'number',
aggregate: {
collection: 'records',
valueExpr: container.idPropertyName + ' => count'
}
}
}
};
// complete the supertype definition with super-properties
const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName);
const recordTypeDef = recordTypeDesc.definition;
for (let superPropName in recordTypeDef.superProperties) {
const superPropDef = recordTypeDef.superProperties[
superPropName];
if (superTypeDef.properties[superPropName])
throw new common.X2UsageError(
'Invalid record type ' + recordTypeName +
' definition: super property name "' +
superPropName + '" is reserved.');
const superTypePropDef = Object.create(superPropDef);
superTypeDef.properties[superPropName] = superTypePropDef;
// TODO: validate: must be aggregate of records or nested, or
// view of records
}
// add the type
ctx.addRecordType(superTypeName, superTypeDef);
});
// get the record type storage table
container._table = (
container.definition.table || container.recordTypeName);
// add properties and methods to the descriptor:
/**
* Super record type name.
*
* @member {Symbol} module:x2node-dbos.RecordTypeDescriptorWithDBOs#superRecordTypeName
* @readonly
*/
Object.defineProperty(container, 'superRecordTypeName', {
get() { return this._superRecordTypeName; }
});
/**
* Top table used to store the record type's records.
*
* @member {string} module:x2node-dbos.RecordTypeDescriptorWithDBOs#table
* @readonly
*/
Object.defineProperty(container, 'table', {
get() { return this._table; }
});
/**
* Get name of the property for the specified record meta-info role.
*
* @function module:x2node-dbos.RecordTypeDescriptorWithDBOs#getRecordMetaInfoPropName
* @param {string} role Record meta-info role: "version",
* "creationTimestamp", "creationActor", "modificationTimestamp" or
* "modificationActor".
* @returns {string} The property name, or <code>undefined</code> if
* none.
*/
container.getRecordMetaInfoPropName = function(role) {
return this._recordMetaInfoPropNames[role];
};
}
// complete polymorphic object container descriptor
ctx.onContainerComplete(container => {
if (container.isPolymorphObject() &&
container.hasProperty(container.typePropertyName) &&
((typeof container.definition.typeColumn) === 'string')) {
container.getPropertyDesc(container.typePropertyName)._column =
container.definition.typeColumn;
}
});
// return the container
return container;
};
/**
* DBOs module specific
* [PropertyDescriptor]{@link module:x2node-records~PropertyDescriptor}
* extension.
*
* @mixin PropertyDescriptorWithDBOs
* @static
*/
/**
* Get invalid property definition error.
*
* @private
* @param {module:x2node-records~PropertyDescriptor} propDesc Property
* descriptor.
* @param {string} msg Error message.
* @returns {module:x2node-common.X2UsageError} Error to throw.
*/
function invalidPropDef(propDesc, msg) {
return new common.X2UsageError(
'Property ' + propDesc.container.nestedPath + propDesc.name +
' of record type ' + String(propDesc.container.recordTypeName) +
' has invalid definition: ' + msg);
}
/* JUST AN IDEA FOR THE FUTURE:
const PROPDESC_VALIDATORS = [
{
description: 'implicit dependent reference property',
selector: {
implicitDependentRef: true
},
requirements: [
{
description: 'must be a reference',
test: {
isRef: true
}
},
{
description: 'may not be stored in table/column',
test: {
column: undefined,
table: undefined
}
}
]
},
{
selector: {
isCalculated: false,
reverseRefPropertyName: undefined,
implicitDependentRef: false
},
requirements: [
{
descriptior: 'must be stored in a column',
test: {
column: not(undefined)
}
}
]
}
];*/
/**
* Record meta-info property roles.
*
* @private
* @type {Set.<string>}
*/
const RECORD_METAINFO_ROLES = new Set([
'version',
'creationTimestamp', 'creationActor',
'modificationTimestamp', 'modificationActor'
]);
// extend property descriptors
exports.extendPropertyDescriptor = function(ctx, propDesc) {
// restrict property name
if (!(/^[a-z_$][a-z_$0-9]*$/i).test(propDesc.name))
throw invalidPropDef(
propDesc, 'illegal characters in the property name.');
// add value expression context
ctx.onLibraryComplete(() => {
propDesc._valueExprContext = new ValueExpressionContext(
propDesc.container.nestedPath + propDesc.name,
propDesc.containerChain.concat(propDesc.nestedProperties));
});
// process property definition:
// get property definition
const propDef = propDesc.definition;
// implicit dependent reference flag
propDesc._implicitDependentRef = false;
if (propDef[IMPLICIT_DEP_REF]) {
// validate the definition
if (!propDesc.isRef() || propDef.reverseRefProperty)
throw invalidPropDef(
propDesc, 'only a reference may be marked as'+
' implicit dependent ref and it may not combine with' +
' reverseRefProperty attribute.');
// store the flag on the descriptor
propDesc._implicitDependentRef = true;
}
// get generator
if (propDef.generator !== undefined) {
// store the generator on the descriptor
propDesc._generator = propDef.generator;
} else if (propDesc.isId()) { // default generator for id property
propDesc._generator = ctx[DEFAULT_IDGEN];
}
// set generated flag
propDesc._isGenerated = (
(propDesc._generator !== undefined) && (propDesc._generator !== null));
// set id table-wide uniqueness
if (propDesc.isId())
propDesc._tableUnique = (
(propDef.tableUnique === undefined) ||
(propDef.tableUnique ? true : false));
// check if record meta-info property
if (RECORD_METAINFO_ROLES.has(propDef.role)) {
propDesc._isRecordMetaInfo = true;
propDesc._recordMetaInfoRole = propDef.role;
}
// get stored property parameters
if (!propDef.valueExpr && !propDef.aggregate &&
!propDef.reverseRefProperty && !propDef[IMPLICIT_DEP_REF] &&
!propDesc.isPolymorphObjectType()) {
// check if nested object
if (propDesc.scalarValueType === 'object') {
// may not have column attribute
if (propDef.column)
throw invalidPropDef(
propDesc, 'nested object property may not have a column' +
' attribute.');
} else { // not a nested object
// get the storage column
propDesc._column = (propDef.column || propDesc.name);
}
// get table and parent id column
propDesc._table = propDef.table;
propDesc._parentIdColumn = propDef.parentIdColumn;
// update default optionality for some meta-info properties
if (propDesc._isRecordMetaInfo &&
propDesc._recordMetaInfoRole.startsWith('modification') &&
(propDef.optional === undefined))
propDesc._optional = true;
// update default modifiability for meta-info properties
if (propDesc._isRecordMetaInfo && (propDef.modifiable === undefined))
propDesc._modifiable = false;
} else {
// may not have explicit modifiability
if (propDef.modifiable)
throw invalidPropDef(propDesc, 'may not be modifiable.');
// set default modifiability
propDesc._modifiable = false;
}
// check if dependent reference
if ((typeof propDef.reverseRefProperty) === 'string') {
// validate the definition
if (!propDesc.isRef())
throw invalidPropDef(
propDesc, 'non-reference property may not have' +
' reverseRefProperty attribute.');
// save reverse reference info on the descriptor
propDesc._reverseRefPropertyName = propDef.reverseRefProperty;
propDesc._weakDependency = (propDef.weakDependency ? true : false);
if (!propDesc._weakDependency) {
if (!propDesc.container._dependentRecordTypes)
propDesc.container._dependentRecordTypes = new Set();
propDesc.container._dependentRecordTypes.add(propDesc.refTarget);
}
}
// check if calculated value property
if ((typeof propDef.valueExpr) === 'string') {
// validate property definition
if (propDef.aggregate || !propDesc.isScalar())
throw invalidPropDef(
propDesc, 'calculated property may not be aggregate or' +
' non-scalar.');
// compile the property value expression
propDesc._isCalculated = true; // mark as calculated right away
ctx.onLibraryComplete(() => {
try {
propDesc._valueExpr = new ValueExpression(
new ValueExpressionContext(
propDesc.container.nestedPath, propDesc.containerChain),
propDef.valueExpr
);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid property value expression: ' +
err.message);
throw err;
}
});
}
// check if aggregate property
if (propDef.aggregate) {
// validate property definition
if (propDesc.isArray())
throw invalidPropDef(
propDesc, 'aggregate property may not be an array.');
// check if has needed attributes
const aggColPath = propDef.aggregate.collection;
const valueExprSpec = propDef.aggregate.valueExpr;
if (!aggColPath || !valueExprSpec)
throw invalidPropDef(
propDesc, 'aggregate definition attribute must have collection' +
' and valueExpr properties.');
if (propDesc.isMap() && !propDesc.keyPropertyName)
throw invalidPropDef(
propDesc, 'missing keyPropertyName attribute.');
// parse value expression
const valueExprSpecParts = valueExprSpec.match(
/^\s*([^=\s].*?)\s*=>\s*(count|sum|min|max|avg)\s*$/i);
if (valueExprSpecParts === null)
throw invalidPropDef(
propDesc, 'invalid aggregated value expression syntax.');
propDesc._isCalculated = true; // mark as calculated right away
propDesc._aggregateFunc = valueExprSpecParts[2].toUpperCase();
ctx.onLibraryComplete(recordTypes => {
// build value expression context based on the aggregated collection
const valueExprCtx = (
new ValueExpressionContext(
propDesc.container.nestedPath, propDesc.containerChain)
).getRelativeContext(aggColPath);
// save the aggregated property path
propDesc._aggregatedPropPath = valueExprCtx.basePath;
// compile value expression and add it to the descriptor
try {
propDesc._valueExpr = new ValueExpression(
valueExprCtx, valueExprSpecParts[1]);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid aggregation expression: ' +
err.message);
throw err;
}
// add aggregated collection filter if any
const aggColFilterSpec = propDef.aggregate.filter;
if (aggColFilterSpec) {
try {
propDesc._filter = filterBuilder.buildFilter(
recordTypes, valueExprCtx, [ ':and', aggColFilterSpec ]);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid aggregated collection filter: ' +
err.message);
throw err;
}
}
// set up aggregate map key
if (propDesc.isMap()) {
if (!propDesc.keyPropertyName)
throw invalidPropDef(
propDesc, 'missing keyPropertyName attribute.');
const keyPropNameParts = propDesc.keyPropertyName.split('.');
let container = valueExprCtx.baseContainer;
let keyPropDesc;
for (let propName of keyPropNameParts) {
if (!container)
throw invalidPropDef(
propDesc, 'key property path ' +
propDesc.keyPropertyName +
' includes elements without nested properties.');
if (!container.hasProperty(propName))
throw invalidPropDef(
propDesc, 'invalid keyPropertyName attribute:' +
' no such property.');
keyPropDesc = container.getPropertyDesc(propName);
if (!keyPropDesc.isScalar() || keyPropDesc.isCalculated() ||
keyPropDesc.reverseRefPropertyName)
throw invalidPropDef(
propDesc, 'key property ' +
propDesc.keyPropertyName +
' is not scalar, calculated or dependent.');
container = keyPropDesc.nestedProperties;
}
if (keyPropDesc.table ||
(keyPropDesc.scalarValueType === 'object'))
throw invalidPropDef(
propDesc, 'key property ' + propDesc.keyPropertyName +
' is not suitable to be a map key.');
propDesc._keyValueType = keyPropDesc.scalarValueType;
if (keyPropDesc.isRef())
propDesc._keyRefTarget = keyPropDesc.refTarget;
}
});
}
// check if array
if (propDesc.isArray()) {
// get index column
if ((typeof propDef.indexColumn) === 'string')
propDesc._indexColumn = propDef.indexColumn;
}
// check if non-aggregate map
if (propDesc.isMap() && !propDef.aggregate) {
// get the key column
if ((typeof propDef.keyColumn) === 'string') {
if (propDesc.keyPropertyName)
throw invalidPropDef(
propDesc, 'may not have both keyPropertyName and' +
' keyColumn attriutes.');
propDesc._keyColumn = propDef.keyColumn;
}
}
// add default presence test for polymorphic object subtype
let presenceTest = propDef.presenceTest;
if (propDesc.isSubtype() && (propDesc.scalarValueType === 'object') &&
!propDef.table && !presenceTest) {
if (!propDesc.container.definition.typeColumn)
throw invalidPropDef(
propDesc, 'no presence test and no typeColumn attribute on the' +
' polymorphic container.');
presenceTest = [
[
'^.' + propDesc.container.typePropertyName + ' => is',
propDesc.name
]
];
}
// check if has a presense test
if (presenceTest) {
// validate property definition
if (!propDesc.isScalar() || (propDesc.scalarValueType !== 'object') ||
!propDesc.optional || propDef.table)
throw invalidPropDef(
propDesc, 'presence test may only be specified on an optional' +
' scalar object property stored in the parent record\'s' +
' table.');
// parse the test specification
ctx.onLibraryComplete(recordTypes => {
try {
propDesc._presenceTest = filterBuilder.buildFilter(
recordTypes, propDesc.valueExprContext,
[ ':and', presenceTest ]);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid presence test: ' + err.message);
throw err;
}
});
}
// check if has scoped filter
if (propDef.filter) {
// validate property definition
if (propDesc.isScalar() || !propDesc.isView() || !propDesc.optional)
throw invalidPropDef(
propDesc, 'scoped filters are only allowed on non-scalar,' +
' optional view properties.');
// parse the filter
ctx.onLibraryComplete(recordTypes => {
try {
propDesc._filter = filterBuilder.buildFilter(
recordTypes, propDesc.valueExprContext,
[ ':and', propDef.filter ]);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid scoped filter: ' + err.message);
throw err;
}
});
}
// check if has scoped order
if (propDef.order) {
// validate property definition
if (propDesc.isScalar())
throw invalidPropDef(
propDesc, 'scoped orders are only allowed on non-scalar' +
' properties.');
// parse the order
ctx.onLibraryComplete(() => {
try {
propDesc._order = orderBuilder.buildOrder(
propDesc.valueExprContext, propDef.order);
} catch (err) {
if (err instanceof common.X2UsageError)
throw invalidPropDef(
propDesc, 'invalid scoped order: ' + err.message);
throw err;
}
});
}
// final touches
ctx.onLibraryComplete(() => {
// determine fetch by default flag
propDesc._fetchByDefault = ((
(propDef.fetchByDefault === undefined) &&
!propDesc.isView() &&
!propDesc.isCalculated() &&
!propDesc.reverseRefPropertyName
) || propDef.fetchByDefault);
// determine if entangled reference property
if (propDesc.isRef() && propDesc.table) {
propDesc._entangled = false;
const targetRecordTypeDesc = propDesc.nestedProperties;
for (let targetPropName of targetRecordTypeDesc.allPropertyNames) {
const targetPropDesc = targetRecordTypeDesc.getPropertyDesc(
targetPropName);
if (targetPropDesc.isRef() &&
(targetPropDesc.table === propDesc.table) &&
(targetPropDesc.column === propDesc.parentIdColumn) &&
(targetPropDesc.parentIdColumn === propDesc.column)) {
propDesc._entangled = true;
break;
}
}
}
});
// setup validation for non-stored and special role properties
if (!propDesc.isView()) {
if (propDesc._isRecordMetaInfo || propDesc._isGenerated ||
propDesc._isCalculated || propDesc._reverseRefPropertyName)
validators.replaceDefaultValidators(propDesc, {
'onCreate': [ 'empty' ]
});
}
// overall property descriptor validation:
// final property descriptor validation
ctx.onLibraryValidation(recordTypes => {
// validate stored property
if (!propDesc.isCalculated() && !propDesc.reverseRefPropertyName &&
!propDesc.implicitDependentRef &&
(propDesc.name !== propDesc.container.typePropertyName)) {
// must have a table if collection
if (!propDesc.isScalar() && !propDesc.table)
throw invalidPropDef(
propDesc, 'must be stored in a separate table.');
// must have parent id column if has table
if (propDesc.table && !propDesc.parentIdColumn)
throw invalidPropDef(
propDesc, 'missing parentIdColumn attribute.');
// validate column
if (propDesc.scalarValueType === 'object') {
if (propDesc.column)
throw invalidPropDef(
propDesc, 'nested object property may not be stored in' +
' a column.');
} else {
if (!propDesc.column)
throw invalidPropDef(
propDesc, 'stored property must have a column.');
}
}
// validate generated property
if (propDesc.isGenerated()) {
// validate property type
if (!propDesc.isScalar() || propDesc.isCalculated() ||
(propDesc.scalarValueType === 'object') || propDesc.isRef())
throw invalidPropDef(
propDesc, 'generated property may not be calculated,' +
' non-scalar, nested object or reference.');
// validate generator
const generator = propDesc.generator;
if ((generator !== 'auto') && ((typeof generator) !== 'function'))
throw invalidPropDef(
propDesc, 'generator may only be "auto" or a function.');
}
// validate id property
if (propDesc.isId()) {
// validate property type
if (propDesc.isCalculated() || propDesc.table)
throw invalidPropDef(
propDesc, 'id property may not be calculated or stored in' +
' its own table.');
// validate top record id uniqueness
if (propDesc.container.isRecordType() && !propDesc.tableUnique)
throw invalidPropDef(
propDesc, 'top record id must be table-wide unique.');
}
// validate meta-info property
if (propDesc.isRecordMetaInfo()) {
// validate property type
if (propDesc.isCalculated() || propDesc.table ||
!propDesc.container.isRecordType() || !propDesc.isScalar() ||
propDesc.isGenerated() || propDesc.modifiable)
throw invalidPropDef(
propDesc, 'record meta-info property may not be' +
' calculated, generated, non-scalar, modifiable,' +
' stored in its own table or belong to a nested' +
' object.');
// validate property value type
/* eslint-disable no-fallthrough */
switch (propDesc.recordMetaInfoRole) {
case 'version':
if (propDesc.scalarValueType !== 'number')
throw invalidPropDef(
propDesc, 'record version may only be a number.');
if (!propDesc.fetchByDefault)
throw invalidPropDef(
propDesc, 'record version must be fetched by default.');
break;
case 'modificationTimestamp':
if (!propDesc.fetchByDefault)
throw invalidPropDef(
propDesc, 'record modification timestamp must be' +
' fetched by default.');
case 'creationTimestamp':
if (propDesc.scalarValueType !== 'datetime')
throw invalidPropDef(
propDesc, 'record creation/modification timestamp may' +
' only be a datetime.');
break;
case 'modificationActor':
case 'creationActor':
if ((propDesc.scalarValueType !== 'string') &&
(propDesc.scalarValueType !== 'number'))
throw invalidPropDef(
propDesc, 'record creation/modification actor may only' +
' be a string or a number.');
}
/* eslint-enable no-fallthrough */
}
// validate calculated property
if (propDesc.isCalculated()) {
// validate property type
if (propDesc.table || propDesc.column || propDesc.modifiable ||
(propDesc.scalarValueType === 'object') ||
propDesc.presenceTest ||
(!propDesc.isAggregate() && propDesc.isFiltered()) ||
propDesc.isOrdered())
throw invalidPropDef(
propDesc, 'calculated property may not be modifiable,' +
' stored in a table/column, be a nested object, have a' +
' presence test or be filtered or ordered.');
}
// validate dependent reference property
if (propDesc.reverseRefPropertyName) {
// validate property type
if (propDesc.table || propDesc.column || propDesc.modifiable ||
propDesc.isCalculated() || !propDesc.container.isRecordType())
throw invalidPropDef(
propDesc, 'dependent reference property may not be' +
' modifiable, calculated, stored in a table/column' +
' or belong to a nested object.');
// index column not allowed on dependent record references
if (propDesc.isArray() && propDesc.indexColumn)
throw invalidPropDef(
propDesc, 'dependent reference array property may not have' +
' index column.');
// validate reverse reference property in the referred record type
const refTarget = recordTypes.getRecordTypeDesc(propDesc.refTarget);
if (!refTarget.hasProperty(propDesc.reverseRefPropertyName))
throw invalidPropDef(
propDesc, 'reverse reference property ' +
propDesc.reverseRefPropertyName +
' does not exist in the reference target record type ' +
propDesc.refTarget + '.');
const revRefPropDesc = refTarget.getPropertyDesc(
propDesc.reverseRefPropertyName);
if (!revRefPropDesc.isRef() || !revRefPropDesc.isScalar() ||
revRefPropDesc.isCalculated() ||
revRefPropDesc.reverseRefPropertyName ||
(revRefPropDesc.refTarget !== propDesc.container.recordTypeName))
throw invalidPropDef(
propDesc, 'reverse reference property does not match the' +
' property definition.');
// detect any cyclical strong dependencies
const seenRecordTypes = new Set();
const checkForCycles = (dependentRecordType) => {
seenRecordTypes.add(dependentRecordType.name);
const drt = dependentRecordType._dependentRecordTypes;
if (drt) for (let recordTypeName of drt) {
if (seenRecordTypes.has(recordTypeName))
throw invalidPropDef(
propDesc, 'cyclical strong dependency between' +
' record types ' +
dependentRecordType.name + ' and ' +
recordTypeName + '.');
checkForCycles(
recordTypes.getRecordTypeDesc(recordTypeName));
}
};
checkForCycles(propDesc.container);
}
// validate non-aggregate map property key
if (propDesc.isMap() && !propDesc.isAggregate()) {
// must have key column or property
if (!propDesc.keyPropertyName && !propDesc.keyColumn)
throw invalidPropDef(propDesc, 'missing keyColumn attribute.');
// validate key property
if (propDesc.keyPropertyName) {
const keyPropDesc = propDesc.nestedProperties.getPropertyDesc(
propDesc.keyPropertyName);
if (keyPropDesc.isCalculated() || keyPropDesc.table ||
keyPropDesc.reverseRefPropertyName)
throw invalidPropDef(
propDesc, 'key property may not be calculated, stored' +
' in its own table or have a reverse reference.');
}
}
// check if presence test is required
if (propDesc.isScalar() && (propDesc.scalarValueType === 'object') &&
propDesc.optional && !propDef.table) {
// validate presence test
if (!propDesc.presenceTest)
throw invalidPropDef(
propDesc, 'optional scalar object property stored in the' +
' parent record\'s table must have a presence test.');
}
});
// add properties and methods to the descriptor: