@itwin/imodel-transformer 2.0.0-dev.4 → 2.0.0-dev.41

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.
Files changed (88) hide show
  1. package/README.md +12 -26
  2. package/lib/cjs/BranchProvenanceInitializer.d.ts.map +1 -1
  3. package/lib/cjs/BranchProvenanceInitializer.js +35 -30
  4. package/lib/cjs/BranchProvenanceInitializer.js.map +1 -1
  5. package/lib/cjs/ChangesetScanner.d.ts +60 -0
  6. package/lib/cjs/ChangesetScanner.d.ts.map +1 -0
  7. package/lib/cjs/ChangesetScanner.js +101 -0
  8. package/lib/cjs/ChangesetScanner.js.map +1 -0
  9. package/lib/cjs/ECReferenceTypesCache.d.ts +0 -3
  10. package/lib/cjs/ECReferenceTypesCache.d.ts.map +1 -1
  11. package/lib/cjs/ECReferenceTypesCache.js +61 -103
  12. package/lib/cjs/ECReferenceTypesCache.js.map +1 -1
  13. package/lib/cjs/ElementAspectCleanup.d.ts +16 -0
  14. package/lib/cjs/ElementAspectCleanup.d.ts.map +1 -0
  15. package/lib/cjs/ElementAspectCleanup.js +83 -0
  16. package/lib/cjs/ElementAspectCleanup.js.map +1 -0
  17. package/lib/cjs/ElementAspectExportCoordinator.d.ts +44 -0
  18. package/lib/cjs/ElementAspectExportCoordinator.d.ts.map +1 -0
  19. package/lib/cjs/ElementAspectExportCoordinator.js +148 -0
  20. package/lib/cjs/ElementAspectExportCoordinator.js.map +1 -0
  21. package/lib/cjs/ElementAspectExportProcessor.d.ts +55 -0
  22. package/lib/cjs/ElementAspectExportProcessor.d.ts.map +1 -0
  23. package/lib/cjs/ElementAspectExportProcessor.js +186 -0
  24. package/lib/cjs/ElementAspectExportProcessor.js.map +1 -0
  25. package/lib/cjs/ElementCascadingDeleter.d.ts +3 -3
  26. package/lib/cjs/ElementCascadingDeleter.d.ts.map +1 -1
  27. package/lib/cjs/ElementCascadingDeleter.js +12 -12
  28. package/lib/cjs/ElementCascadingDeleter.js.map +1 -1
  29. package/lib/cjs/EntityUnifier.d.ts +4 -8
  30. package/lib/cjs/EntityUnifier.d.ts.map +1 -1
  31. package/lib/cjs/EntityUnifier.js +6 -24
  32. package/lib/cjs/EntityUnifier.js.map +1 -1
  33. package/lib/cjs/IModelCloneContext.d.ts +6 -5
  34. package/lib/cjs/IModelCloneContext.d.ts.map +1 -1
  35. package/lib/cjs/IModelCloneContext.js +74 -57
  36. package/lib/cjs/IModelCloneContext.js.map +1 -1
  37. package/lib/cjs/IModelExporter.d.ts +80 -32
  38. package/lib/cjs/IModelExporter.d.ts.map +1 -1
  39. package/lib/cjs/IModelExporter.js +563 -188
  40. package/lib/cjs/IModelExporter.js.map +1 -1
  41. package/lib/cjs/IModelImporter.d.ts +38 -24
  42. package/lib/cjs/IModelImporter.d.ts.map +1 -1
  43. package/lib/cjs/IModelImporter.js +210 -129
  44. package/lib/cjs/IModelImporter.js.map +1 -1
  45. package/lib/cjs/IModelTransformContext.d.ts +54 -0
  46. package/lib/cjs/IModelTransformContext.d.ts.map +1 -0
  47. package/lib/cjs/IModelTransformContext.js +3 -0
  48. package/lib/cjs/IModelTransformContext.js.map +1 -0
  49. package/lib/cjs/IModelTransformer.d.ts +101 -189
  50. package/lib/cjs/IModelTransformer.d.ts.map +1 -1
  51. package/lib/cjs/IModelTransformer.js +558 -1104
  52. package/lib/cjs/IModelTransformer.js.map +1 -1
  53. package/lib/cjs/IModelTransformerError.d.ts +76 -0
  54. package/lib/cjs/IModelTransformerError.d.ts.map +1 -0
  55. package/lib/cjs/IModelTransformerError.js +85 -0
  56. package/lib/cjs/IModelTransformerError.js.map +1 -0
  57. package/lib/cjs/ProvenanceManager.d.ts +170 -0
  58. package/lib/cjs/ProvenanceManager.d.ts.map +1 -0
  59. package/lib/cjs/ProvenanceManager.js +735 -0
  60. package/lib/cjs/ProvenanceManager.js.map +1 -0
  61. package/lib/cjs/SyncTypeResolver.d.ts +34 -0
  62. package/lib/cjs/SyncTypeResolver.d.ts.map +1 -0
  63. package/lib/cjs/SyncTypeResolver.js +98 -0
  64. package/lib/cjs/SyncTypeResolver.js.map +1 -0
  65. package/lib/cjs/TransformerLoggerCategory.d.ts +1 -1
  66. package/lib/cjs/TransformerLoggerCategory.js +1 -1
  67. package/lib/cjs/TransformerLoggerCategory.js.map +1 -1
  68. package/lib/cjs/TransformerPackageMetadata.d.ts +8 -0
  69. package/lib/cjs/TransformerPackageMetadata.d.ts.map +1 -0
  70. package/lib/cjs/TransformerPackageMetadata.js +14 -0
  71. package/lib/cjs/TransformerPackageMetadata.js.map +1 -0
  72. package/lib/cjs/imodel-transformer.d.ts +18 -0
  73. package/lib/cjs/imodel-transformer.d.ts.map +1 -1
  74. package/lib/cjs/imodel-transformer.js +29 -33
  75. package/lib/cjs/imodel-transformer.js.map +1 -1
  76. package/package.json +27 -39
  77. package/lib/cjs/DetachedExportElementAspectsStrategy.d.ts +0 -16
  78. package/lib/cjs/DetachedExportElementAspectsStrategy.d.ts.map +0 -1
  79. package/lib/cjs/DetachedExportElementAspectsStrategy.js +0 -106
  80. package/lib/cjs/DetachedExportElementAspectsStrategy.js.map +0 -1
  81. package/lib/cjs/ExportElementAspectsStrategy.d.ts +0 -35
  82. package/lib/cjs/ExportElementAspectsStrategy.d.ts.map +0 -1
  83. package/lib/cjs/ExportElementAspectsStrategy.js +0 -52
  84. package/lib/cjs/ExportElementAspectsStrategy.js.map +0 -1
  85. package/lib/cjs/ExportElementAspectsWithElementsStrategy.d.ts +0 -12
  86. package/lib/cjs/ExportElementAspectsWithElementsStrategy.d.ts.map +0 -1
  87. package/lib/cjs/ExportElementAspectsWithElementsStrategy.js +0 -47
  88. package/lib/cjs/ExportElementAspectsWithElementsStrategy.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"EntityUnifier.js","sourceRoot":"","sources":["../../src/EntityUnifier.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;;;GAIG;;;AAEH,iCAAiC;AACjC,oDAI4B;AAC5B,sDA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C,wFAAwF;gBACxF,iCAAmB,CAAC,0BAA0B,CAAC,IAAK,CAAC;YACvD,CAAC,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,UAAU,MAAM,GAAG,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC;QAE7D,IAAI,EAAE,KAAK,SAAS,IAAI,mBAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAAE,OAAO,KAAK,CAAC;QAEzD,gFAAgF;QAChF,OAAO,EAAE,CAAC,qBAAqB,CAC7B,iBAAiB,aAAa,uBAAuB,EACrD,CAAC,IAAI,EAAE,EAAE;YACP,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACnB,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;YAClC,IAAI,aAAa,KAAK,uBAAQ,CAAC,aAAa;gBAAE,OAAO,IAAI,CAAC;YAC1D,IAAI,aAAa,KAAK,uBAAQ,CAAC,cAAc;gBAAE,OAAO,KAAK,CAAC;;gBACvD,MAAM,IAAI,yBAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;QAC5D,CAAC,CACF,CAAC;IACJ,CAAC;IA3Be,oBAAM,SA2BrB,CAAA;AACH,CAAC,EAvDgB,aAAa,6BAAb,aAAa,QAuD7B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Utils\n * utilities that unify operations, especially CRUD operations, on entities\n * for entity-generic operations in the transformer\n */\n\nimport * as assert from \"assert\";\nimport {\n ConcreteEntityTypes,\n EntityReference,\n IModelError,\n} from \"@itwin/core-common\";\nimport {\n ConcreteEntity,\n ConcreteEntityProps,\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n EntityReferences,\n IModelDb,\n Relationship,\n} from \"@itwin/core-backend\";\nimport { DbResult, Id64 } from \"@itwin/core-bentley\";\n\n/** @internal */\nexport namespace EntityUnifier {\n export function getReadableType(entity: ConcreteEntity) {\n if (entity instanceof Element) return \"element\";\n else if (entity instanceof ElementAspect) return \"element aspect\";\n else if (entity instanceof Relationship) return \"relationship\";\n else return \"unknown entity type\";\n }\n\n type EntityUpdater = (entityProps: ConcreteEntityProps) => void;\n\n /** needs to return a widened type otherwise typescript complains when result is used with a narrow type */\n export function updaterFor(db: IModelDb, entity: ConcreteEntity) {\n if (entity instanceof Element)\n return db.elements.updateElement.bind(db.elements) as EntityUpdater;\n else if (entity instanceof Relationship)\n return db.relationships.updateInstance.bind(\n db.relationships\n ) as EntityUpdater;\n else if (entity instanceof ElementAspect)\n return db.elements.updateAspect.bind(db.elements) as EntityUpdater;\n else\n assert(\n false,\n `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`\n );\n }\n\n export function exists(\n db: IModelDb,\n arg: { entity: ConcreteEntity } | { entityReference: EntityReference }\n ) {\n const [type, id] =\n \"entityReference\" in arg\n ? EntityReferences.split(arg.entityReference)\n : [undefined, arg.entity.id];\n const classFullName =\n \"entityReference\" in arg\n ? // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-non-null-assertion\n ConcreteEntityTypes.toBisCoreRootClassFullName(type!)\n : `[${arg.entity.schemaName}].[${arg.entity.className}]`;\n\n if (id === undefined || Id64.isInvalid(id)) return false;\n\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n return db.withPreparedStatement(\n `SELECT 1 FROM ${classFullName} WHERE ECInstanceId=?`,\n (stmt) => {\n stmt.bindId(1, id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW) return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE) return false;\n else throw new IModelError(matchesResult, \"query failed\");\n }\n );\n }\n}\n"]}
1
+ {"version":3,"file":"EntityUnifier.js","sourceRoot":"","sources":["../../src/EntityUnifier.ts"],"names":[],"mappings":";AAAA;;;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E,IAAI;SACrB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;IACvB,CAAC;IAtBqB,oBAAM,SAsB3B,CAAA;AACH,CAAC,EA/BgB,aAAa,6BAAb,aAAa,QA+B7B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Utils\n * utilities that unify operations, especially CRUD operations, on entities\n * for entity-generic operations in the transformer\n */\n\nimport {\n ConcreteEntityTypes,\n EntityReference,\n QueryBinder,\n} from \"@itwin/core-common\";\nimport {\n ConcreteEntity,\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n EntityReferences,\n IModelDb,\n Relationship,\n} from \"@itwin/core-backend\";\nimport { Id64 } from \"@itwin/core-bentley\";\n\n/** @internal */\nexport namespace EntityUnifier {\n export function getReadableType(entity: ConcreteEntity) {\n if (entity instanceof Element) return \"element\";\n else if (entity instanceof ElementAspect) return \"element aspect\";\n else if (entity instanceof Relationship) return \"relationship\";\n else return \"unknown entity type\";\n }\n\n export async function exists(\n db: IModelDb,\n arg: { entity: ConcreteEntity } | { entityReference: EntityReference }\n ) {\n const [type, id] =\n \"entityReference\" in arg\n ? EntityReferences.split(arg.entityReference)\n : [undefined, arg.entity.id];\n const classFullName =\n \"entityReference\" in arg\n ? // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-non-null-assertion\n ConcreteEntityTypes.toBisCoreRootClassFullName(type!)\n : `[${arg.entity.schemaName}].[${arg.entity.className}]`;\n\n if (id === undefined || Id64.isInvalid(id)) return false;\n\n const query = `SELECT 1 FROM ${classFullName} WHERE ECInstanceId=:id`;\n const params = new QueryBinder().bindId(\"id\", id);\n const reader = db.createQueryReader(query, params, {\n usePrimaryConn: true,\n });\n return reader.step();\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { Id64String } from "@itwin/core-bentley";
2
2
  import { ElementAspectProps, ElementProps, EntityReference } from "@itwin/core-common";
3
3
  import { Element, ElementAspect, IModelElementCloneContext, IModelJsNative } from "@itwin/core-backend";
4
+ import type { IModelTransformContext } from "./IModelTransformContext";
4
5
  /** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.
5
- * @beta
6
+ * @internal
6
7
  */
7
- export declare class IModelCloneContext extends IModelElementCloneContext {
8
+ export declare class IModelCloneContext extends IModelElementCloneContext implements IModelTransformContext {
8
9
  private _refTypesCache;
9
10
  private _aspectRemapTable;
10
11
  /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */
@@ -12,7 +13,7 @@ export declare class IModelCloneContext extends IModelElementCloneContext {
12
13
  /** Clone the specified source Element into ElementProps for the target iModel.
13
14
  * @internal
14
15
  */
15
- cloneElement(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): ElementProps;
16
+ cloneElement(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): Promise<ElementProps>;
16
17
  /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */
17
18
  remapElementAspect(aspectSourceId: Id64String, aspectTargetId: Id64String): void;
18
19
  /** Remove a rule that remaps the specified source ElementAspect */
@@ -24,10 +25,10 @@ export declare class IModelCloneContext extends IModelElementCloneContext {
24
25
  /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)
25
26
  * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.
26
27
  */
27
- findTargetEntityId(sourceEntityId: EntityReference): EntityReference;
28
+ findTargetEntityId(sourceEntityId: EntityReference): Promise<EntityReference>;
28
29
  /** Clone the specified source Element into ElementProps for the target iModel.
29
30
  * @internal
30
31
  */
31
- cloneElementAspect(sourceElementAspect: ElementAspect): ElementAspectProps;
32
+ cloneElementAspect(sourceElementAspect: ElementAspect): Promise<ElementAspectProps>;
32
33
  }
33
34
  //# sourceMappingURL=IModelCloneContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"IModelCloneContext.d.ts","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":"AAQA,OAAO,EAAkB,UAAU,EAAU,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAIL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAOhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,OAAO,EACP,aAAa,EAEb,yBAAyB,EACzB,cAAc,EACf,MAAM,qBAAqB,CAAC;AAO7B;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,yBAAyB;IAC/D,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,iBAAiB,CAAqC;IAE9D,0HAA0H;IACpG,UAAU;IAIhC;;OAEG;IACa,YAAY,CAC1B,aAAa,EAAE,OAAO,EACtB,YAAY,CAAC,EAAE,cAAc,CAAC,mBAAmB,GAChD,YAAY;IA+Cf,uGAAuG;IAChG,kBAAkB,CACvB,cAAc,EAAE,UAAU,EAC1B,cAAc,EAAE,UAAU,GACzB,IAAI;IAIP,mEAAmE;IAC5D,mBAAmB,CAAC,cAAc,EAAE,UAAU,GAAG,IAAI;IAI5D;;OAEG;IACI,kBAAkB,CAAC,cAAc,EAAE,UAAU,GAAG,UAAU;IAIjE;;OAEG;IACI,kBAAkB,CAAC,cAAc,EAAE,eAAe,GAAG,eAAe;IAkI3E;;OAEG;IACI,kBAAkB,CACvB,mBAAmB,EAAE,aAAa,GACjC,kBAAkB;CAsCtB"}
1
+ {"version":3,"file":"IModelCloneContext.d.ts","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":"AAQA,OAAO,EAAQ,UAAU,EAAU,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAKL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAKhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,OAAO,EACP,aAAa,EAEb,yBAAyB,EACzB,cAAc,EACf,MAAM,qBAAqB,CAAC;AAM7B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAIvE;;GAEG;AACH,qBAAa,kBACX,SAAQ,yBACR,YAAW,sBAAsB;IAEjC,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,iBAAiB,CAA4B;IAErD,0HAA0H;IACpG,UAAU;IAIhC;;OAEG;IACmB,YAAY,CAChC,aAAa,EAAE,OAAO,EACtB,YAAY,CAAC,EAAE,cAAc,CAAC,mBAAmB,GAChD,OAAO,CAAC,YAAY,CAAC;IA2DxB,uGAAuG;IAChG,kBAAkB,CACvB,cAAc,EAAE,UAAU,EAC1B,cAAc,EAAE,UAAU,GACzB,IAAI;IAIP,mEAAmE;IAC5D,mBAAmB,CAAC,cAAc,EAAE,UAAU,GAAG,IAAI;IAI5D;;OAEG;IACI,kBAAkB,CAAC,cAAc,EAAE,UAAU,GAAG,UAAU;IAIjE;;OAEG;IACU,kBAAkB,CAC7B,cAAc,EAAE,eAAe,GAC9B,OAAO,CAAC,eAAe,CAAC;IAqI3B;;OAEG;IACU,kBAAkB,CAC7B,mBAAmB,EAAE,aAAa,GACjC,OAAO,CAAC,kBAAkB,CAAC;CAsD/B"}
@@ -8,20 +8,22 @@ exports.IModelCloneContext = void 0;
8
8
  /** @packageDocumentation
9
9
  * @module iModels
10
10
  */
11
- const assert = require("assert");
11
+ const node_assert_1 = require("node:assert");
12
12
  const core_bentley_1 = require("@itwin/core-bentley");
13
13
  const core_common_1 = require("@itwin/core-common");
14
14
  const core_backend_1 = require("@itwin/core-backend");
15
+ const ecschema_metadata_1 = require("@itwin/ecschema-metadata");
15
16
  const ECReferenceTypesCache_1 = require("./ECReferenceTypesCache");
16
17
  const EntityUnifier_1 = require("./EntityUnifier");
17
18
  const TransformerLoggerCategory_1 = require("./TransformerLoggerCategory");
19
+ const BigMap_1 = require("./BigMap");
18
20
  const loggerCategory = TransformerLoggerCategory_1.TransformerLoggerCategory.IModelCloneContext;
19
21
  /** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.
20
- * @beta
22
+ * @internal
21
23
  */
22
24
  class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
23
25
  _refTypesCache = new ECReferenceTypesCache_1.ECReferenceTypesCache();
24
- _aspectRemapTable = new Map();
26
+ _aspectRemapTable = new BigMap_1.BigMap();
25
27
  /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */
26
28
  async initialize() {
27
29
  await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);
@@ -29,15 +31,22 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
29
31
  /** Clone the specified source Element into ElementProps for the target iModel.
30
32
  * @internal
31
33
  */
32
- cloneElement(sourceElement, cloneOptions) {
34
+ async cloneElement(sourceElement, cloneOptions) {
33
35
  const targetElementProps = this["_nativeContext"].cloneElement(sourceElement.id, cloneOptions);
34
36
  // Ensure that all NavigationProperties in targetElementProps have a defined value so "clearing" changes will be part of the JSON used for update
35
- sourceElement.forEachProperty((propertyName, meta) => {
36
- if (meta.isNavigation &&
37
- undefined === sourceElement[propertyName]) {
38
- targetElementProps[propertyName] = core_common_1.RelatedElement.none;
37
+ const sourceElementClass = sourceElement.iModel.schemaContext.getSchemaItemSync(sourceElement.schemaItemKey, ecschema_metadata_1.EntityClass);
38
+ (0, node_assert_1.strict)(sourceElementClass !== undefined, `Cannot get metadata for ${sourceElement.classFullName}.`);
39
+ for (const property of sourceElementClass.getPropertiesSync()) {
40
+ // Exclude custom properties because C++ has already handled them.
41
+ if (property.customAttributes?.has("BisCore.CustomHandledProperty"))
42
+ continue;
43
+ const name = property.name;
44
+ if (property.isNavigation() &&
45
+ undefined === sourceElement[core_common_1.ECJsNames.toJsName(name)]) {
46
+ targetElementProps[core_common_1.ECJsNames.toJsName(name)] =
47
+ core_common_1.RelatedElement.none;
39
48
  }
40
- }, false); // exclude custom because C++ has already handled them
49
+ }
41
50
  if (this.isBetweenIModels) {
42
51
  // The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels
43
52
  targetElementProps.federationGuid = sourceElement.federationGuid;
@@ -54,7 +63,7 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
54
63
  targetElementProps.code = core_common_1.Code.createEmpty();
55
64
  }
56
65
  const jsClass = this.sourceDb.getJsClass(sourceElement.classFullName);
57
- jsClass["onCloned"](this, sourceElement.toJSON(), targetElementProps);
66
+ await jsClass["onCloned"](this, sourceElement.toJSON(), targetElementProps);
58
67
  return targetElementProps;
59
68
  }
60
69
  /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */
@@ -74,7 +83,7 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
74
83
  /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)
75
84
  * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.
76
85
  */
77
- findTargetEntityId(sourceEntityId) {
86
+ async findTargetEntityId(sourceEntityId) {
78
87
  const [type, rawId] = core_backend_1.EntityReferences.split(sourceEntityId);
79
88
  if (core_bentley_1.Id64.isValid(rawId)) {
80
89
  switch (type) {
@@ -97,7 +106,9 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
97
106
  }
98
107
  // Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.
99
108
  // That can occur in the transformer since a submodeled element is imported before its submodel.
100
- if (EntityUnifier_1.EntityUnifier.exists(this.targetDb, { entityReference: targetId }))
109
+ if (await EntityUnifier_1.EntityUnifier.exists(this.targetDb, {
110
+ entityReference: targetId,
111
+ }))
101
112
  return targetId;
102
113
  break;
103
114
  }
@@ -121,8 +132,7 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
121
132
  ELSE 'error'
122
133
  END
123
134
  `;
124
- // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated
125
- const relInSource = this.sourceDb.withPreparedStatement(`
135
+ const sql = `
126
136
  SELECT
127
137
  SourceECInstanceId,
128
138
  TargetECInstanceId,
@@ -130,14 +140,17 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
130
140
  (${makeGetConcreteEntityTypeSql("TargetECClassId")}) AS TargetType
131
141
  FROM BisCore:ElementRefersToElements
132
142
  WHERE ECInstanceId=?
133
- `, (stmt) => {
134
- stmt.bindId(1, rawId);
135
- let status;
136
- while ((status = stmt.step()) === core_bentley_1.DbResult.BE_SQLITE_ROW) {
137
- const sourceId = stmt.getValue(0).getId();
138
- const targetId = stmt.getValue(1).getId();
139
- const sourceType = stmt.getValue(2).getString();
140
- const targetType = stmt.getValue(3).getString();
143
+ `;
144
+ const params = new core_common_1.QueryBinder().bindId(1, rawId);
145
+ const reader = this.sourceDb.createQueryReader(sql, params, {
146
+ usePrimaryConn: true,
147
+ });
148
+ const relInSource = await (async () => {
149
+ if (await reader.step()) {
150
+ const sourceId = reader.current[0];
151
+ const targetId = reader.current[1];
152
+ const sourceType = reader.current[2];
153
+ const targetType = reader.current[3];
141
154
  if (sourceType === "error" || targetType === "error")
142
155
  throw Error("relationship end had unknown root class");
143
156
  return {
@@ -145,10 +158,8 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
145
158
  targetId: `${targetType}${targetId}`,
146
159
  };
147
160
  }
148
- if (status !== core_bentley_1.DbResult.BE_SQLITE_DONE)
149
- throw new core_common_1.IModelError(status, "unexpected query failure");
150
161
  return undefined;
151
- });
162
+ })();
152
163
  if (relInSource === undefined)
153
164
  break;
154
165
  // just in case prevent recursion
@@ -156,29 +167,30 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
156
167
  relInSource.targetId === sourceEntityId)
157
168
  throw Error("link table relationship end was resolved to itself. This should be impossible");
158
169
  const relInTarget = {
159
- sourceId: this.findTargetEntityId(relInSource.sourceId),
160
- targetId: this.findTargetEntityId(relInSource.targetId),
170
+ sourceId: await this.findTargetEntityId(relInSource.sourceId),
171
+ targetId: await this.findTargetEntityId(relInSource.targetId),
161
172
  };
162
173
  // return a null
163
174
  if (!core_backend_1.EntityReferences.isValid(relInTarget.sourceId) ||
164
175
  !core_backend_1.EntityReferences.isValid(relInTarget.targetId))
165
176
  break;
166
- // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated
167
- const relInTargetId = this.targetDb.withPreparedStatement(`
177
+ const relInTargetSql = `
168
178
  SELECT ECInstanceId
169
179
  FROM BisCore:ElementRefersToElements
170
180
  WHERE SourceECInstanceId=?
171
181
  AND TargetECInstanceId=?
172
- `, (stmt) => {
173
- stmt.bindId(1, core_backend_1.EntityReferences.toId64(relInTarget.sourceId));
174
- stmt.bindId(2, core_backend_1.EntityReferences.toId64(relInTarget.targetId));
175
- const status = stmt.step();
176
- if (status === core_bentley_1.DbResult.BE_SQLITE_ROW)
177
- return stmt.getValue(0).getId();
178
- if (status !== core_bentley_1.DbResult.BE_SQLITE_DONE)
179
- throw new core_common_1.IModelError(status, "unexpected query failure");
180
- return core_bentley_1.Id64.invalid;
181
- });
182
+ `;
183
+ const relInTargetParams = new core_common_1.QueryBinder();
184
+ relInTargetParams.bindId(1, core_backend_1.EntityReferences.toId64(relInTarget.sourceId));
185
+ relInTargetParams.bindId(2, core_backend_1.EntityReferences.toId64(relInTarget.targetId));
186
+ const relInTargetResult = await this.targetDb
187
+ .createQueryReader(relInTargetSql, relInTargetParams, {
188
+ usePrimaryConn: true,
189
+ })
190
+ .next();
191
+ const relInTargetId = relInTargetResult.done
192
+ ? core_bentley_1.Id64.invalid
193
+ : relInTargetResult.value.id;
182
194
  return `r${relInTargetId}`;
183
195
  }
184
196
  }
@@ -188,30 +200,35 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
188
200
  /** Clone the specified source Element into ElementProps for the target iModel.
189
201
  * @internal
190
202
  */
191
- cloneElementAspect(sourceElementAspect) {
203
+ async cloneElementAspect(sourceElementAspect) {
192
204
  const targetElementAspectProps = sourceElementAspect.toJSON();
193
205
  targetElementAspectProps.id = undefined;
194
- sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {
195
- if (propertyMetaData.isNavigation) {
196
- const sourceNavProp = sourceElementAspect.asAny[propertyName];
206
+ const targetEntityIds = [];
207
+ const sourceElementAspectClass = sourceElementAspect.iModel.schemaContext.getSchemaItemSync(sourceElementAspect.schemaItemKey, ecschema_metadata_1.EntityClass);
208
+ (0, node_assert_1.strict)(sourceElementAspectClass !== undefined, `Cannot get metadata for ${sourceElementAspect.classFullName}.`);
209
+ for (const property of sourceElementAspectClass.getPropertiesSync()) {
210
+ const ecName = property.name;
211
+ const name = core_common_1.ECJsNames.toJsName(ecName);
212
+ if (property.isNavigation()) {
213
+ const sourceNavProp = sourceElementAspect.asAny[name];
197
214
  if (sourceNavProp?.id) {
198
- const navPropRefType = this._refTypesCache.getNavPropRefType(sourceElementAspect.schemaName, sourceElementAspect.className, propertyName);
199
- assert(navPropRefType !== undefined, `nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`);
200
- const targetEntityReference = this.findTargetEntityId(core_backend_1.EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType));
201
- const targetEntityId = core_backend_1.EntityReferences.toId64(targetEntityReference);
202
- // spread the property in case toJSON did not deep-clone
203
- targetElementAspectProps[propertyName] = {
204
- ...targetElementAspectProps[propertyName],
205
- id: targetEntityId,
206
- };
215
+ const navPropRefType = this._refTypesCache.getNavPropRefType(sourceElementAspect.schemaName, sourceElementAspect.className, name);
216
+ (0, node_assert_1.strict)(navPropRefType !== undefined, `nav prop ref type for '${name}' was not in the cache, this is a bug.`);
217
+ targetEntityIds.push(this.findTargetEntityId(core_backend_1.EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType)).then((targetEntityReference) => {
218
+ const targetEntityId = core_backend_1.EntityReferences.toId64(targetEntityReference);
219
+ // spread the property in case toJSON did not deep-clone
220
+ targetElementAspectProps[name] = {
221
+ ...targetElementAspectProps[name],
222
+ id: targetEntityId,
223
+ };
224
+ }));
207
225
  }
208
226
  }
209
- else if (core_common_1.PrimitiveTypeCode.Long === propertyMetaData.primitiveType &&
210
- "Id" === propertyMetaData.extendedType) {
211
- targetElementAspectProps[propertyName] =
212
- this.findTargetElementId(sourceElementAspect.asAny[propertyName]);
227
+ else if (property.isPrimitive() && "Id" === property.extendedTypeName) {
228
+ targetElementAspectProps[name] = this.findTargetElementId(sourceElementAspect.asAny[name]);
213
229
  }
214
- });
230
+ }
231
+ await Promise.all(targetEntityIds);
215
232
  return targetElementAspectProps;
216
233
  }
217
234
  }
@@ -1 +1 @@
1
- {"version":3,"file":"IModelCloneContext.js","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":";;;AAAA;;;gGAGgG;AAChG;;GAEG;AACH,iCAAiC;AACjC,sDAAyE;AACzE,oDAa4B;AAC5B,sDAO6B;AAC7B,mEAAgE;AAChE,mDAAgD;AAChD,2EAAwE;AAExE,MAAM,cAAc,GAAW,qDAAyB,CAAC,kBAAkB,CAAC;AAE5E;;GAEG;AACH,MAAa,kBAAmB,SAAQ,wCAAyB;IACvD,cAAc,GAAG,IAAI,6CAAqB,EAAE,CAAC;IAC7C,iBAAiB,GAAG,IAAI,GAAG,EAA0B,CAAC;IAE9D,0HAA0H;IAC1G,KAAK,CAAC,UAAU;QAC9B,MAAM,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACa,YAAY,CAC1B,aAAsB,EACtB,YAAiD;QAEjD,MAAM,kBAAkB,GAAiB,IAAI,CAC3C,gBAAgB,CACjB,CAAC,YAAY,CAAC,aAAa,CAAC,EAAE,EAAE,YAAY,CAAC,CAAC;QAC/C,iJAAiJ;QACjJ,aAAa,CAAC,eAAe,CAC3B,CAAC,YAAoB,EAAE,IAAsB,EAAE,EAAE;YAC/C,IACE,IAAI,CAAC,YAAY;gBACjB,SAAS,KAAM,aAAqB,CAAC,YAAY,CAAC,EAClD,CAAC;gBACA,kBAA0B,CAAC,YAAY,CAAC,GAAG,4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,IAAI,KAAK,gBAAgB,CAAC,YAAY,EACtC,CAAC;gBACA,wBAAgC,CAAC,YAAY,CAAC;oBAC7C,IAAI,CAAC,mBAAmB,CAAC,mBAAmB,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC;YACtE,CAAC;QACH,CAAC,CAAC,CAAC;QACH,OAAO,wBAAwB,CAAC;IAClC,CAAC;CACF;AAlQD,gDAkQC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module iModels\n */\nimport * as assert from \"assert\";\nimport { DbResult, Id64, Id64String, Logger } from \"@itwin/core-bentley\";\nimport {\n Code,\n CodeScopeSpec,\n ConcreteEntityTypes,\n ElementAspectProps,\n ElementProps,\n EntityReference,\n IModel,\n IModelError,\n PrimitiveTypeCode,\n PropertyMetaData,\n RelatedElement,\n RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n EntityReferences,\n IModelElementCloneContext,\n IModelJsNative,\n} from \"@itwin/core-backend\";\nimport { ECReferenceTypesCache } from \"./ECReferenceTypesCache\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelCloneContext;\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @beta\n */\nexport class IModelCloneContext extends IModelElementCloneContext {\n private _refTypesCache = new ECReferenceTypesCache();\n private _aspectRemapTable = new Map<Id64String, Id64String>();\n\n /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */\n public override async initialize() {\n await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public override cloneElement(\n sourceElement: Element,\n cloneOptions?: IModelJsNative.CloneElementOptions\n ): ElementProps {\n const targetElementProps: ElementProps = this[\n \"_nativeContext\"\n ].cloneElement(sourceElement.id, cloneOptions);\n // Ensure that all NavigationProperties in targetElementProps have a defined value so \"clearing\" changes will be part of the JSON used for update\n sourceElement.forEachProperty(\n (propertyName: string, meta: PropertyMetaData) => {\n if (\n meta.isNavigation &&\n undefined === (sourceElement as any)[propertyName]\n ) {\n (targetElementProps as any)[propertyName] = RelatedElement.none;\n }\n },\n false\n ); // exclude custom because C++ has already handled them\n if (this.isBetweenIModels) {\n // The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels\n targetElementProps.federationGuid = sourceElement.federationGuid;\n const targetElementCodeScopeType = this.targetDb.codeSpecs.getById(\n targetElementProps.code.spec\n ).scopeType;\n if (\n CodeScopeSpec.Type.Repository === targetElementCodeScopeType &&\n targetElementProps.code.scope !== IModel.rootSubjectId\n ) {\n Logger.logWarning(\n loggerCategory,\n `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`\n );\n }\n }\n // unlike other references, code cannot be null. If it is null, use an empty code instead\n // this will be updated back later as the transformer resolves references\n if (\n targetElementProps.code.scope === Id64.invalid ||\n targetElementProps.code.spec === Id64.invalid\n ) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(\n sourceElement.classFullName\n );\n jsClass[\"onCloned\"](this, sourceElement.toJSON(), targetElementProps);\n return targetElementProps;\n }\n\n /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */\n public remapElementAspect(\n aspectSourceId: Id64String,\n aspectTargetId: Id64String\n ): void {\n this._aspectRemapTable.set(aspectSourceId, aspectTargetId);\n }\n\n /** Remove a rule that remaps the specified source ElementAspect */\n public removeElementAspect(aspectSourceId: Id64String): void {\n this._aspectRemapTable.delete(aspectSourceId);\n }\n\n /** Look up a target AspectId from the source AspectId.\n * @returns the target AspectId or [Id64.invalid]($bentley) if a mapping not found.\n */\n public findTargetAspectId(sourceAspectId: Id64String): Id64String {\n return this._aspectRemapTable.get(sourceAspectId) ?? Id64.invalid;\n }\n\n /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)\n * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.\n */\n public findTargetEntityId(sourceEntityId: EntityReference): EntityReference {\n const [type, rawId] = EntityReferences.split(sourceEntityId);\n if (Id64.isValid(rawId)) {\n switch (type) {\n case ConcreteEntityTypes.Model: {\n let targetId;\n /**\n * The repository model is a singleton container which exists in all iModels which has a modelId of 0x1.\n * It is possible to remap the root subject (id 0x1) to some other non root subject, but this is not possible for the repository model.\n * The RepositoryModel only contains bis:Subject elements and bis:InformationpartitionElement instances (https://www.itwinjs.org/bis/domains/biscore.ecschema/#repositorymodel)\n * The system handler for both bis:InformationPartitionElement and bis:Subject will only permit instances to be inserted into the RepositoryModel.\n * https://www.itwinjs.org/bis/domains/biscore.ecschema/#informationpartitionelement\n * https://www.itwinjs.org/bis/domains/biscore.ecschema/#subject\n * Since there is a chance that the root subject is remapped to some other subject which has the same id as the repositoryModel, we need to ignore the remapping for the repository model.\n */\n if (rawId === IModel.repositoryModelId) {\n targetId = `m${IModel.repositoryModelId}` as const;\n } else {\n targetId = `m${this.findTargetElementId(rawId)}` as const;\n }\n // Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.\n // That can occur in the transformer since a submodeled element is imported before its submodel.\n if (\n EntityUnifier.exists(this.targetDb, { entityReference: targetId })\n )\n return targetId;\n break;\n }\n case ConcreteEntityTypes.Element:\n return `e${this.findTargetElementId(rawId)}`;\n case ConcreteEntityTypes.ElementAspect:\n return `a${this.findTargetAspectId(rawId)}`;\n case ConcreteEntityTypes.Relationship: {\n const makeGetConcreteEntityTypeSql = (property: string) => `\n CASE\n WHEN [${property}] IS (BisCore.ElementUniqueAspect) OR [${property}] IS (BisCore.ElementMultiAspect)\n THEN 'a'\n WHEN [${property}] IS (BisCore.Element)\n THEN 'e'\n WHEN [${property}] IS (BisCore.Model)\n THEN 'm'\n WHEN [${property}] IS (BisCore.CodeSpec)\n THEN 'c'\n WHEN [${property}] IS (BisCore.ElementRefersToElements) -- TODO: ElementDrivesElement still not handled by the transformer\n THEN 'r'\n ELSE 'error'\n END\n `;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n const relInSource = this.sourceDb.withPreparedStatement(\n `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\n \"SourceECClassId\"\n )}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\n `,\n (stmt) => {\n stmt.bindId(1, rawId);\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const sourceId = stmt.getValue(0).getId();\n const targetId = stmt.getValue(1).getId();\n const sourceType = stmt.getValue(2).getString() as\n | ConcreteEntityTypes\n | \"error\";\n const targetType = stmt.getValue(3).getString() as\n | ConcreteEntityTypes\n | \"error\";\n if (sourceType === \"error\" || targetType === \"error\")\n throw Error(\"relationship end had unknown root class\");\n return {\n sourceId: `${sourceType}${sourceId}`,\n targetId: `${targetType}${targetId}`,\n } as const;\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return undefined;\n }\n );\n if (relInSource === undefined) break;\n // just in case prevent recursion\n if (\n relInSource.sourceId === sourceEntityId ||\n relInSource.targetId === sourceEntityId\n )\n throw Error(\n \"link table relationship end was resolved to itself. This should be impossible\"\n );\n const relInTarget = {\n sourceId: this.findTargetEntityId(relInSource.sourceId),\n targetId: this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (\n !EntityReferences.isValid(relInTarget.sourceId) ||\n !EntityReferences.isValid(relInTarget.targetId)\n )\n break;\n // eslint-disable-next-line @itwin/no-internal, @typescript-eslint/no-deprecated\n const relInTargetId = this.targetDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n `,\n (stmt) => {\n stmt.bindId(1, EntityReferences.toId64(relInTarget.sourceId));\n stmt.bindId(2, EntityReferences.toId64(relInTarget.targetId));\n const status: DbResult = stmt.step();\n if (status === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return Id64.invalid;\n }\n );\n return `r${relInTargetId}`;\n }\n }\n }\n return `${type}${Id64.invalid}`;\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public cloneElementAspect(\n sourceElementAspect: ElementAspect\n ): ElementAspectProps {\n const targetElementAspectProps: ElementAspectProps =\n sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {\n if (propertyMetaData.isNavigation) {\n const sourceNavProp: RelatedElementProps | undefined =\n sourceElementAspect.asAny[propertyName];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n propertyName\n );\n assert(\n navPropRefType !== undefined,\n `nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`\n );\n const targetEntityReference = this.findTargetEntityId(\n EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType)\n );\n const targetEntityId = EntityReferences.toId64(targetEntityReference);\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[propertyName] = {\n ...(targetElementAspectProps as any)[propertyName],\n id: targetEntityId,\n };\n }\n } else if (\n PrimitiveTypeCode.Long === propertyMetaData.primitiveType &&\n \"Id\" === propertyMetaData.extendedType\n ) {\n (targetElementAspectProps as any)[propertyName] =\n this.findTargetElementId(sourceElementAspect.asAny[propertyName]);\n }\n });\n return targetElementAspectProps;\n }\n}\n"]}
1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,CAAC,IAAI,CAClB,IAAI,CAAC,kBAAkB,CACrB,+BAAgB,CAAC,cAAc,CAAC,aAAa,CAAC,EAAE,EAAE,cAAc,CAAC,CAClE,CAAC,IAAI,CAAC,CAAC,qBAAqB,EAAE,EAAE;wBAC/B,MAAM,cAAc,GAAG,+BAAgB,CAAC,MAAM,CAC5C,qBAAqB,CACtB,CAAC;wBACF,wDAAwD;wBACvD,wBAAgC,CAAC,IAAI,CAAC,GAAG;4BACxC,GAAI,wBAAgC,CAAC,IAAI,CAAC;4BAC1C,EAAE,EAAE,cAAc;yBACnB,CAAC;oBACJ,CAAC,CAAC,CACH,CAAC;gBACJ,CAAC;YACH,CAAC;iBAAM,IAAI,QAAQ,CAAC,WAAW,EAAE,IAAI,IAAI,KAAK,QAAQ,CAAC,gBAAgB,EAAE,CAAC;gBACvE,wBAAgC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,mBAAmB,CAChE,mBAAmB,CAAC,KAAK,CAAC,IAAI,CAAC,CAChC,CAAC;YACJ,CAAC;QACH,CAAC;QACD,MAAM,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QACnC,OAAO,wBAAwB,CAAC;IAClC,CAAC;CACF;AAtSD,gDAsSC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module iModels\n */\nimport { strict as assert } from \"node:assert\";\nimport { Id64, Id64String, Logger } from \"@itwin/core-bentley\";\nimport {\n Code,\n CodeScopeSpec,\n ConcreteEntityTypes,\n ECJsNames,\n ElementAspectProps,\n ElementProps,\n EntityReference,\n IModel,\n QueryBinder,\n RelatedElement,\n RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n // eslint-disable-next-line @typescript-eslint/no-redeclare\n Element,\n ElementAspect,\n EntityReferences,\n IModelElementCloneContext,\n IModelJsNative,\n} from \"@itwin/core-backend\";\nimport { EntityClass } from \"@itwin/ecschema-metadata\";\nimport { ECReferenceTypesCache } from \"./ECReferenceTypesCache\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { BigMap } from \"./BigMap\";\nimport type { IModelTransformContext } from \"./IModelTransformContext\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelCloneContext;\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @internal\n */\nexport class IModelCloneContext\n extends IModelElementCloneContext\n implements IModelTransformContext\n{\n private _refTypesCache = new ECReferenceTypesCache();\n private _aspectRemapTable = new BigMap<Id64String>();\n\n /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */\n public override async initialize() {\n await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public override async cloneElement(\n sourceElement: Element,\n cloneOptions?: IModelJsNative.CloneElementOptions\n ): Promise<ElementProps> {\n const targetElementProps: ElementProps = this[\n \"_nativeContext\"\n ].cloneElement(sourceElement.id, cloneOptions);\n // Ensure that all NavigationProperties in targetElementProps have a defined value so \"clearing\" changes will be part of the JSON used for update\n const sourceElementClass =\n sourceElement.iModel.schemaContext.getSchemaItemSync(\n sourceElement.schemaItemKey,\n EntityClass\n );\n assert(\n sourceElementClass !== undefined,\n `Cannot get metadata for ${sourceElement.classFullName}.`\n );\n for (const property of sourceElementClass.getPropertiesSync()) {\n // Exclude custom properties because C++ has already handled them.\n if (property.customAttributes?.has(\"BisCore.CustomHandledProperty\"))\n continue;\n\n const name = property.name;\n if (\n property.isNavigation() &&\n undefined === (sourceElement as any)[ECJsNames.toJsName(name)]\n ) {\n (targetElementProps as any)[ECJsNames.toJsName(name)] =\n RelatedElement.none;\n }\n }\n if (this.isBetweenIModels) {\n // The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels\n targetElementProps.federationGuid = sourceElement.federationGuid;\n const targetElementCodeScopeType = this.targetDb.codeSpecs.getById(\n targetElementProps.code.spec\n ).scopeType;\n if (\n CodeScopeSpec.Type.Repository === targetElementCodeScopeType &&\n targetElementProps.code.scope !== IModel.rootSubjectId\n ) {\n Logger.logWarning(\n loggerCategory,\n `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`\n );\n }\n }\n // unlike other references, code cannot be null. If it is null, use an empty code instead\n // this will be updated back later as the transformer resolves references\n if (\n targetElementProps.code.scope === Id64.invalid ||\n targetElementProps.code.spec === Id64.invalid\n ) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(\n sourceElement.classFullName\n );\n await jsClass[\"onCloned\"](this, sourceElement.toJSON(), targetElementProps);\n return targetElementProps;\n }\n\n /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */\n public remapElementAspect(\n aspectSourceId: Id64String,\n aspectTargetId: Id64String\n ): void {\n this._aspectRemapTable.set(aspectSourceId, aspectTargetId);\n }\n\n /** Remove a rule that remaps the specified source ElementAspect */\n public removeElementAspect(aspectSourceId: Id64String): void {\n this._aspectRemapTable.delete(aspectSourceId);\n }\n\n /** Look up a target AspectId from the source AspectId.\n * @returns the target AspectId or [Id64.invalid]($bentley) if a mapping not found.\n */\n public findTargetAspectId(sourceAspectId: Id64String): Id64String {\n return this._aspectRemapTable.get(sourceAspectId) ?? Id64.invalid;\n }\n\n /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)\n * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.\n */\n public async findTargetEntityId(\n sourceEntityId: EntityReference\n ): Promise<EntityReference> {\n const [type, rawId] = EntityReferences.split(sourceEntityId);\n if (Id64.isValid(rawId)) {\n switch (type) {\n case ConcreteEntityTypes.Model: {\n let targetId;\n /**\n * The repository model is a singleton container which exists in all iModels which has a modelId of 0x1.\n * It is possible to remap the root subject (id 0x1) to some other non root subject, but this is not possible for the repository model.\n * The RepositoryModel only contains bis:Subject elements and bis:InformationpartitionElement instances (https://www.itwinjs.org/bis/domains/biscore.ecschema/#repositorymodel)\n * The system handler for both bis:InformationPartitionElement and bis:Subject will only permit instances to be inserted into the RepositoryModel.\n * https://www.itwinjs.org/bis/domains/biscore.ecschema/#informationpartitionelement\n * https://www.itwinjs.org/bis/domains/biscore.ecschema/#subject\n * Since there is a chance that the root subject is remapped to some other subject which has the same id as the repositoryModel, we need to ignore the remapping for the repository model.\n */\n if (rawId === IModel.repositoryModelId) {\n targetId = `m${IModel.repositoryModelId}` as const;\n } else {\n targetId = `m${this.findTargetElementId(rawId)}` as const;\n }\n // Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.\n // That can occur in the transformer since a submodeled element is imported before its submodel.\n if (\n await EntityUnifier.exists(this.targetDb, {\n entityReference: targetId,\n })\n )\n return targetId;\n break;\n }\n case ConcreteEntityTypes.Element:\n return `e${this.findTargetElementId(rawId)}`;\n case ConcreteEntityTypes.ElementAspect:\n return `a${this.findTargetAspectId(rawId)}`;\n case ConcreteEntityTypes.Relationship: {\n const makeGetConcreteEntityTypeSql = (property: string) => `\n CASE\n WHEN [${property}] IS (BisCore.ElementUniqueAspect) OR [${property}] IS (BisCore.ElementMultiAspect)\n THEN 'a'\n WHEN [${property}] IS (BisCore.Element)\n THEN 'e'\n WHEN [${property}] IS (BisCore.Model)\n THEN 'm'\n WHEN [${property}] IS (BisCore.CodeSpec)\n THEN 'c'\n WHEN [${property}] IS (BisCore.ElementRefersToElements) -- TODO: ElementDrivesElement still not handled by the transformer\n THEN 'r'\n ELSE 'error'\n END\n `;\n const sql = `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\n \"SourceECClassId\"\n )}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\n `;\n const params = new QueryBinder().bindId(1, rawId);\n const reader = this.sourceDb.createQueryReader(sql, params, {\n usePrimaryConn: true,\n });\n const relInSource = await (async () => {\n if (await reader.step()) {\n const sourceId = reader.current[0];\n const targetId = reader.current[1];\n const sourceType = reader.current[2] as\n | ConcreteEntityTypes\n | \"error\";\n const targetType = reader.current[3] as\n | ConcreteEntityTypes\n | \"error\";\n if (sourceType === \"error\" || targetType === \"error\")\n throw Error(\"relationship end had unknown root class\");\n return {\n sourceId: `${sourceType}${sourceId}`,\n targetId: `${targetType}${targetId}`,\n } as const;\n }\n return undefined;\n })();\n if (relInSource === undefined) break;\n // just in case prevent recursion\n if (\n relInSource.sourceId === sourceEntityId ||\n relInSource.targetId === sourceEntityId\n )\n throw Error(\n \"link table relationship end was resolved to itself. This should be impossible\"\n );\n const relInTarget = {\n sourceId: await this.findTargetEntityId(relInSource.sourceId),\n targetId: await this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (\n !EntityReferences.isValid(relInTarget.sourceId) ||\n !EntityReferences.isValid(relInTarget.targetId)\n )\n break;\n const relInTargetSql = `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n `;\n const relInTargetParams = new QueryBinder();\n relInTargetParams.bindId(\n 1,\n EntityReferences.toId64(relInTarget.sourceId)\n );\n relInTargetParams.bindId(\n 2,\n EntityReferences.toId64(relInTarget.targetId)\n );\n const relInTargetResult = await this.targetDb\n .createQueryReader(relInTargetSql, relInTargetParams, {\n usePrimaryConn: true,\n })\n .next();\n const relInTargetId = relInTargetResult.done\n ? Id64.invalid\n : relInTargetResult.value.id;\n return `r${relInTargetId}`;\n }\n }\n }\n return `${type}${Id64.invalid}`;\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public async cloneElementAspect(\n sourceElementAspect: ElementAspect\n ): Promise<ElementAspectProps> {\n const targetElementAspectProps: ElementAspectProps =\n sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n const targetEntityIds: Promise<void>[] = [];\n const sourceElementAspectClass =\n sourceElementAspect.iModel.schemaContext.getSchemaItemSync(\n sourceElementAspect.schemaItemKey,\n EntityClass\n );\n assert(\n sourceElementAspectClass !== undefined,\n `Cannot get metadata for ${sourceElementAspect.classFullName}.`\n );\n for (const property of sourceElementAspectClass.getPropertiesSync()) {\n const ecName = property.name;\n const name = ECJsNames.toJsName(ecName);\n if (property.isNavigation()) {\n const sourceNavProp: RelatedElementProps | undefined =\n sourceElementAspect.asAny[name];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n name\n );\n assert(\n navPropRefType !== undefined,\n `nav prop ref type for '${name}' was not in the cache, this is a bug.`\n );\n targetEntityIds.push(\n this.findTargetEntityId(\n EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType)\n ).then((targetEntityReference) => {\n const targetEntityId = EntityReferences.toId64(\n targetEntityReference\n );\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[name] = {\n ...(targetElementAspectProps as any)[name],\n id: targetEntityId,\n };\n })\n );\n }\n } else if (property.isPrimitive() && \"Id\" === property.extendedTypeName) {\n (targetElementAspectProps as any)[name] = this.findTargetElementId(\n sourceElementAspect.asAny[name]\n );\n }\n }\n await Promise.all(targetEntityIds);\n return targetElementAspectProps;\n }\n}\n"]}