vona-module-a-orm 5.1.40 → 5.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import BigNumber from 'bignumber.js';
2
- import { BeanInfo, BeanBase, BeanAopMethodBase, deepExtend, appResource, assertIsolatedTestDatabaseClient, assertTestClaimDatabaseClient, beanFullNameFromOnionName, cast, useApp, $makeLocaleMagic, Virtual, registerTestClaimDatabaseCreation, BeanSimple, combineConfigDefault, BeanScopeBase, createBeanDecorator, PickClassInner, $Class, disposeInstance } from 'vona';
2
+ import { BeanInfo, BeanBase, BeanAopMethodBase, deepExtend, appResource, assertIsolatedTestDatabaseClient, assertTestClaimDatabaseClient, beanFullNameFromOnionName, cast, useApp, $makeLocaleMagic, Virtual, registerTestClaimDatabaseCreation, BeanSimple, combineConfigDefault, BeanScopeBase, createBeanDecorator, PickClassInner, $Class, registerMappedClassMetadataKey, appMetadata, disposeInstance } from 'vona';
3
3
  import { __decorate, __metadata } from 'tslib';
4
4
  import { Schedule } from 'vona-module-a-schedule';
5
5
  import { AopMethod } from 'vona-module-a-aspect';
@@ -1153,6 +1153,8 @@ function _safeColumn(column) {
1153
1153
  return column.replace(/[\\.#%'"`;,() ]/g, '');
1154
1154
  }
1155
1155
 
1156
+ const SymbolDtoMutateRelations = Symbol('SymbolDtoMutateRelations');
1157
+
1156
1158
  const app$1 = useApp();
1157
1159
  const ormConfig$1 = app$1.util.getModuleConfigRaw('a-orm');
1158
1160
  const ordersDefault = ormConfig$1?.rest?.query?.orders?.default ?? 'createdAt,desc';
@@ -3702,10 +3704,25 @@ function _DtoGet_raw(modelLike, params) {
3702
3704
  return entityClass;
3703
3705
  }
3704
3706
  function _DtoGet_relations(modelClass, entityClass, includeWrapper, mutateTypeTopLevel) {
3705
- // relations
3706
3707
  const relations = _DtoGet_relations_collection(modelClass, includeWrapper);
3707
- if (!relations) return;
3708
+ // Mapped-class metadata follows the dtoClass field projection, including pick/omit.
3709
+ registerMappedClassMetadataKey(entityClass.prototype, SymbolDtoMutateRelations, {});
3710
+ const retained = appMetadata.getOwnMetadataMap(true, SymbolDtoMutateRelations, entityClass.prototype);
3711
+ if (mutateTypeTopLevel) {
3712
+ const overridden = new Set(relations.map(relation => relation[0]));
3713
+ for (const name in retained) {
3714
+ if (!overridden.has(name)) {
3715
+ _DtoGet_relation_handle(entityClass, retained[name], mutateTypeTopLevel);
3716
+ }
3717
+ }
3718
+ }
3708
3719
  for (const relation of relations) {
3720
+ const [name, definition] = relation;
3721
+ if (mutateTypeTopLevel && definition !== false && (definition.type === 'hasOne' || definition.type === 'hasMany')) {
3722
+ retained[name] = relation;
3723
+ } else {
3724
+ delete retained[name];
3725
+ }
3709
3726
  _DtoGet_relation_handle(entityClass, relation, mutateTypeTopLevel);
3710
3727
  }
3711
3728
  }
@@ -4067,7 +4084,7 @@ class BeanModelCache extends BeanModelCrud {
4067
4084
  }
4068
4085
  // insert/update
4069
4086
  const itemsInsertNew = await this.__insertBulk_raw(table, itemsInsert, options);
4070
- await this.__updateBulk_raw(table, itemsUpdate, options);
4087
+ const idsUpdate = await this.__updateBulk_raw(table, itemsUpdate, options);
4071
4088
  const itemsMutate = itemsInsert.map((item, index) => {
4072
4089
  return Object.assign({}, item, {
4073
4090
  id: cast(itemsInsertNew[index]).id
@@ -4075,7 +4092,7 @@ class BeanModelCache extends BeanModelCrud {
4075
4092
  }).concat(itemsUpdate);
4076
4093
  let itemsMutateResult = itemsInsertNew.concat(itemsUpdate);
4077
4094
  const indexesMutate = indexesInsert.concat(indexesUpdate);
4078
- itemsMutateResult = await this.relations.handleRelationsMutate(itemsMutateResult, itemsMutate, options, options);
4095
+ itemsMutateResult = await this.__handleRelationsMutateAdmitted(itemsMutateResult, itemsMutate, [...itemsInsertNew.map(item => [cast(item).id]), ...idsUpdate], options);
4079
4096
  let result = [];
4080
4097
  for (let index = 0; index < indexesMutate.length; index++) {
4081
4098
  result[indexesMutate[index]] = itemsMutateResult[index];
@@ -4416,19 +4433,80 @@ class BeanModelCache extends BeanModelCrud {
4416
4433
  return items[0];
4417
4434
  }
4418
4435
  async updateBulk(items, options) {
4419
- await this.__updateBulk_raw(undefined, items, options);
4420
- return await this.relations.handleRelationsMutate(items, items, options, options);
4436
+ const ids = await this.__updateBulk_raw(undefined, items, options);
4437
+ return await this.__handleRelationsMutateAdmitted(items, items, ids, options);
4421
4438
  }
4422
4439
  async __updateBulk_raw(table, items, options) {
4423
- if (items.length === 0) return;
4440
+ const ids = [];
4424
4441
  for (const item of items) {
4425
- await this.__update_raw(table, item, options);
4442
+ ids.push(await this.__update_raw(table, item, options));
4443
+ }
4444
+ return ids;
4445
+ }
4446
+ async __handleRelationsMutateAdmitted(results, items, ids, options) {
4447
+ const indexes = [];
4448
+ const itemsAdmitted = [];
4449
+ const resultsAdmitted = [];
4450
+ for (let index = 0; index < items.length; index++) {
4451
+ const idsItem = ids[index];
4452
+ if (!idsItem || idsItem.length !== 1) continue;
4453
+ indexes.push(index);
4454
+ itemsAdmitted.push(Object.assign({}, items[index], {
4455
+ id: idsItem[0]
4456
+ }));
4457
+ resultsAdmitted.push(results[index]);
4458
+ }
4459
+ const resultsMutated = await this.relations.handleRelationsMutate(resultsAdmitted, itemsAdmitted, options, options);
4460
+ const result = results.concat();
4461
+ for (let index = 0; index < indexes.length; index++) {
4462
+ result[indexes[index]] = resultsMutated[index];
4426
4463
  }
4464
+ return result;
4465
+ }
4466
+ __hasWritableRelations(options) {
4467
+ return this.relations.handleRelationsCollection(options).some(([, relation]) => {
4468
+ return relation !== false && relation.type !== 'belongsTo';
4469
+ });
4470
+ }
4471
+ async __selectMutationIds(table, where, options) {
4472
+ // Admission must use current scoped rows, not cached entities or changed-row counts.
4473
+ const items = await super._select(table, {
4474
+ where,
4475
+ columns: ['id']
4476
+ }, options);
4477
+ return items.map(item => cast(item).id);
4427
4478
  }
4428
4479
  async __update_raw(table, data, options) {
4429
4480
  // table
4430
4481
  table = table || this.getTable(data);
4431
4482
  if (!table) return this.scopeOrm.error.ShouldSpecifyTable.throw();
4483
+ if (this.__hasWritableRelations(options)) {
4484
+ const where = Object.assign({}, options?.where);
4485
+ const dataNew = Object.assign({}, data);
4486
+ let hasId = false;
4487
+ for (const key of ['id', `${table}.id`]) {
4488
+ if (!isNil(dataNew[key])) {
4489
+ cast(where).id = dataNew[key];
4490
+ delete dataNew[key];
4491
+ hasId = true;
4492
+ }
4493
+ }
4494
+ if (!hasId && !options?.where) {
4495
+ throw new Error('id should be specified for update method');
4496
+ }
4497
+ const ids = await this.__selectMutationIds(table, where, options);
4498
+ if (ids.length === 0) return [];
4499
+ await super._update(table, dataNew, {
4500
+ ...options,
4501
+ where: Object.assign({}, where, {
4502
+ id: ids
4503
+ })
4504
+ });
4505
+ if (!this._checkDisableCacheEntityByOptions(options)) {
4506
+ await this.cacheEntityDel(ids, table);
4507
+ }
4508
+ return ids;
4509
+ }
4432
4510
  // check if cache
4433
4511
  if (this._checkDisableCacheEntityByOptions(options)) {
4434
4512
  await super._update(table, data, options);
@@ -4495,15 +4573,28 @@ class BeanModelCache extends BeanModelCrud {
4495
4573
  }
4496
4574
  async __deleteBulk_raw_with_relations(table, ids, options) {
4497
4575
  if (ids.length === 0) return;
4498
- await this.__delete_raw(table, {
4576
+ const idsDeleted = await this.__delete_raw(table, {
4499
4577
  id: ids
4500
4578
  }, options);
4501
- await this.relations.handleRelationsDelete(ids, options, options);
4579
+ if (idsDeleted) {
4580
+ await this.relations.handleRelationsDelete(idsDeleted, options, options);
4581
+ }
4502
4582
  }
4503
4583
  async __delete_raw(table, where, options) {
4504
4584
  // table
4505
4585
  table = table || this.getTable(where);
4506
4586
  if (!table) return this.scopeOrm.error.ShouldSpecifyTable.throw();
4587
+ if (this.__hasWritableRelations(options)) {
4588
+ const ids = await this.__selectMutationIds(table, where, options);
4589
+ if (ids.length === 0) return [];
4590
+ await super._delete(table, Object.assign({}, where, {
4591
+ id: ids
4592
+ }), options);
4593
+ if (!this._checkDisableCacheEntityByOptions(options)) {
4594
+ await this.cacheEntityDel(ids, table);
4595
+ }
4596
+ return ids;
4597
+ }
4507
4598
  // check if cache
4508
4599
  if (this._checkDisableCacheEntityByOptions(options)) {
4509
4600
  return await super._delete(table, where, options);
@@ -4933,5 +5024,5 @@ const $relationMutate = {
4933
5024
  belongsToMany
4934
5025
  };
4935
5026
 
4936
- export { $Dto, $defineAnalysis, $executeAnalysisAggregate, $executeAnalysisGroup, $locale, $relation, $relationDynamic, $relationMutate, AnalysisError, AopMethodTransaction, BeanDatabase, BeanModel, BeanModelBase, BeanModelMeta, BroadcastColumnsClear, DatabaseDialect, DtoQueryBase, DtoQueryPageBase, Entity, EntityBase, EntityBaseEmpty, EntityBaseInner, EntityBaseSimple, EventClientNameReal, EventColumnsClear, ExtendKnex, ExtendSchemaBuilder, ExtendTableBuilder, HmrEntity, HmrModel, Main, Model, Op, OpAggrs, OpJoint, OpJointValues, OpNormal, OpNormalValues, OpValues, QueueDoubleDelete, ScheduleSoftDeletionPrune, ScopeModuleAOrm, ServiceCacheEntity, ServiceCacheQuery, ServiceColumns, ServiceColumnsCache, ServiceDatabase, ServiceDatabaseAsyncLocalStorage, ServiceDatabaseClient, ServiceDatabaseDialectBase, ServiceDb, ServiceEntityResolver, ServiceModelResolver, ServiceRelations, ServiceTransaction, ServiceTransactionAsyncLocalStorage, ServiceTransactionConsistency‌, ServiceTransactionFiber, ServiceTransactionState, SymbolCacheModelCacheInstances, SymbolCacheModelsClear, SymbolKeyEntity, SymbolKeyEntityMeta, SymbolKeyFieldsMore, SymbolKeyModelOptions, TransactionIsolationLevelsMap, analysisCapabilities, analysisControlSchemas, analysisFailure, analysisFunctions, analysisReservedFields, buildWhere, clearAllCacheModelsClear, clearCacheModelCacheInstance, config, configDefault, errors, getCacheModelCacheInstances, getCacheModelsClear, getClassEntityFromClassModel, getTableOrTableAlias, getTargetColumnName, isRaw, isRef, locales, prepareClassModel, prepareColumns, resolveAnalysis };
5027
+ export { $Dto, $defineAnalysis, $executeAnalysisAggregate, $executeAnalysisGroup, $locale, $relation, $relationDynamic, $relationMutate, AnalysisError, AopMethodTransaction, BeanDatabase, BeanModel, BeanModelBase, BeanModelMeta, BroadcastColumnsClear, DatabaseDialect, DtoQueryBase, DtoQueryPageBase, Entity, EntityBase, EntityBaseEmpty, EntityBaseInner, EntityBaseSimple, EventClientNameReal, EventColumnsClear, ExtendKnex, ExtendSchemaBuilder, ExtendTableBuilder, HmrEntity, HmrModel, Main, Model, Op, OpAggrs, OpJoint, OpJointValues, OpNormal, OpNormalValues, OpValues, QueueDoubleDelete, ScheduleSoftDeletionPrune, ScopeModuleAOrm, ServiceCacheEntity, ServiceCacheQuery, ServiceColumns, ServiceColumnsCache, ServiceDatabase, ServiceDatabaseAsyncLocalStorage, ServiceDatabaseClient, ServiceDatabaseDialectBase, ServiceDb, ServiceEntityResolver, ServiceModelResolver, ServiceRelations, ServiceTransaction, ServiceTransactionAsyncLocalStorage, ServiceTransactionConsistency‌, ServiceTransactionFiber, ServiceTransactionState, SymbolCacheModelCacheInstances, SymbolCacheModelsClear, SymbolDtoMutateRelations, SymbolKeyEntity, SymbolKeyEntityMeta, SymbolKeyFieldsMore, SymbolKeyModelOptions, TransactionIsolationLevelsMap, analysisCapabilities, analysisControlSchemas, analysisFailure, analysisFunctions, analysisReservedFields, buildWhere, clearAllCacheModelsClear, clearCacheModelCacheInstance, config, configDefault, errors, getCacheModelCacheInstances, getCacheModelsClear, getClassEntityFromClassModel, getTableOrTableAlias, getTargetColumnName, isRaw, isRef, locales, prepareClassModel, prepareColumns, resolveAnalysis };
4937
5028
  //# sourceMappingURL=index.js.map