@itwin/imodel-transformer 0.1.17-dev.2 → 0.1.17-fedguidopt.3
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/lib/cjs/Algo.d.ts +7 -0
- package/lib/cjs/Algo.d.ts.map +1 -0
- package/lib/cjs/Algo.js +50 -0
- package/lib/cjs/Algo.js.map +1 -0
- package/lib/cjs/ECReferenceTypesCache.js +1 -1
- package/lib/cjs/ECReferenceTypesCache.js.map +1 -1
- package/lib/cjs/EntityUnifier.js +1 -1
- package/lib/cjs/EntityUnifier.js.map +1 -1
- package/lib/cjs/IModelCloneContext.js +4 -4
- package/lib/cjs/IModelCloneContext.js.map +1 -1
- package/lib/cjs/IModelExporter.d.ts +14 -8
- package/lib/cjs/IModelExporter.d.ts.map +1 -1
- package/lib/cjs/IModelExporter.js +32 -19
- package/lib/cjs/IModelExporter.js.map +1 -1
- package/lib/cjs/IModelImporter.js +1 -1
- package/lib/cjs/IModelImporter.js.map +1 -1
- package/lib/cjs/IModelTransformer.d.ts +138 -26
- package/lib/cjs/IModelTransformer.d.ts.map +1 -1
- package/lib/cjs/IModelTransformer.js +846 -213
- package/lib/cjs/IModelTransformer.js.map +1 -1
- package/lib/cjs/PendingReferenceMap.js +1 -1
- package/lib/cjs/PendingReferenceMap.js.map +1 -1
- package/lib/cjs/TransformerLoggerCategory.js +1 -1
- package/lib/cjs/TransformerLoggerCategory.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** given a discrete inclusive range [start, end] e.g. [-10, 12] and several "skipped" values", e.g.
|
|
2
|
+
* (-10, 1, -3, 5, 15), return the ordered set of subranges of the original range that exclude
|
|
3
|
+
* those values
|
|
4
|
+
*/
|
|
5
|
+
export declare function rangesFromRangeAndSkipped(start: number, end: number, skipped: number[]): [number, number][];
|
|
6
|
+
export declare function renderRanges(ranges: [number, number][]): number[];
|
|
7
|
+
//# sourceMappingURL=Algo.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Algo.d.ts","sourceRoot":"","sources":["../../src/Algo.ts"],"names":[],"mappings":"AAMA;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAiC3G;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,CAMjE"}
|
package/lib/cjs/Algo.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*---------------------------------------------------------------------------------------------
|
|
3
|
+
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
|
|
4
|
+
* See LICENSE.md in the project root for license terms and full copyright notice.
|
|
5
|
+
*--------------------------------------------------------------------------------------------*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.renderRanges = exports.rangesFromRangeAndSkipped = void 0;
|
|
8
|
+
// FIXME: tests
|
|
9
|
+
/** given a discrete inclusive range [start, end] e.g. [-10, 12] and several "skipped" values", e.g.
|
|
10
|
+
* (-10, 1, -3, 5, 15), return the ordered set of subranges of the original range that exclude
|
|
11
|
+
* those values
|
|
12
|
+
*/
|
|
13
|
+
function rangesFromRangeAndSkipped(start, end, skipped) {
|
|
14
|
+
function validRange(range) {
|
|
15
|
+
return range[0] <= range[1];
|
|
16
|
+
}
|
|
17
|
+
const firstRange = [start, end];
|
|
18
|
+
if (!validRange(firstRange))
|
|
19
|
+
throw RangeError(`invalid range: [${start}, ${end}]`);
|
|
20
|
+
const ranges = [firstRange];
|
|
21
|
+
function findRangeContaining(pt, inRanges) {
|
|
22
|
+
// TODO: binary search
|
|
23
|
+
return inRanges.findIndex((r) => (pt >= r[0] && pt <= r[1]));
|
|
24
|
+
}
|
|
25
|
+
for (const skip of skipped) {
|
|
26
|
+
const rangeIndex = findRangeContaining(skip, ranges);
|
|
27
|
+
if (rangeIndex === -1)
|
|
28
|
+
continue;
|
|
29
|
+
const range = ranges[rangeIndex];
|
|
30
|
+
const leftRange = [range[0], skip - 1];
|
|
31
|
+
const rightRange = [skip + 1, range[1]];
|
|
32
|
+
if (validRange(leftRange) && validRange(rightRange))
|
|
33
|
+
ranges.splice(rangeIndex, 1, leftRange, rightRange);
|
|
34
|
+
else if (validRange(leftRange))
|
|
35
|
+
ranges.splice(rangeIndex, 1, leftRange);
|
|
36
|
+
else if (validRange(rightRange))
|
|
37
|
+
ranges.splice(rangeIndex, 1, rightRange);
|
|
38
|
+
}
|
|
39
|
+
return ranges;
|
|
40
|
+
}
|
|
41
|
+
exports.rangesFromRangeAndSkipped = rangesFromRangeAndSkipped;
|
|
42
|
+
function renderRanges(ranges) {
|
|
43
|
+
const result = [];
|
|
44
|
+
for (const range of ranges)
|
|
45
|
+
for (let i = range[0]; i <= range[1]; ++i)
|
|
46
|
+
result.push(i);
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
exports.renderRanges = renderRanges;
|
|
50
|
+
//# sourceMappingURL=Algo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Algo.js","sourceRoot":"","sources":["../../src/Algo.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,eAAe;AACf;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,KAAa,EAAE,GAAW,EAAE,OAAiB;IACrF,SAAS,UAAU,CAAC,KAAsB;QACxC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,GAAG,CAAqB,CAAC;IAEpD,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;QACzB,MAAM,UAAU,CAAC,mBAAmB,KAAK,KAAK,GAAG,GAAG,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QACxB,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;YACvC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACnB,OAAO,MAAM,CAAC;AAChB,CAAC;AAND,oCAMC","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\n// FIXME: tests\n/** given a discrete inclusive range [start, end] e.g. [-10, 12] and several \"skipped\" values\", e.g.\n * (-10, 1, -3, 5, 15), return the ordered set of subranges of the original range that exclude\n * those values\n */\nexport function rangesFromRangeAndSkipped(start: number, end: number, skipped: number[]): [number, number][] {\n function validRange(range: [number,number]): boolean {\n return range[0] <= range[1];\n }\n\n const firstRange = [start, end] as [number, number];\n\n if (!validRange(firstRange))\n throw RangeError(`invalid range: [${start}, ${end}]`);\n\n const ranges = [firstRange];\n\n function findRangeContaining(pt: number, inRanges: [number, number][]): number {\n // TODO: binary search\n return inRanges.findIndex((r) => (pt >= r[0] && pt <= r[1]));\n }\n\n for (const skip of skipped) {\n const rangeIndex = findRangeContaining(skip, ranges);\n if (rangeIndex === -1)\n continue;\n const range = ranges[rangeIndex];\n const leftRange = [range[0], skip - 1] as [number, number];\n const rightRange = [skip + 1, range[1]] as [number, number];\n if (validRange(leftRange) && validRange(rightRange))\n ranges.splice(rangeIndex, 1, leftRange, rightRange);\n else if (validRange(leftRange))\n ranges.splice(rangeIndex, 1, leftRange);\n else if (validRange(rightRange))\n ranges.splice(rangeIndex, 1, rightRange);\n }\n\n return ranges;\n}\n\nexport function renderRanges(ranges: [number, number][]): number[] {\n const result = [];\n for (const range of ranges)\n for (let i = range[0]; i <= range[1]; ++i)\n result.push(i);\n return result;\n}\n\n"]}
|
|
@@ -163,7 +163,6 @@ class ECReferenceTypesCache {
|
|
|
163
163
|
this._propQualifierToRefType.clear();
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
|
-
exports.ECReferenceTypesCache = ECReferenceTypesCache;
|
|
167
166
|
ECReferenceTypesCache.bisRootClassToRefType = {
|
|
168
167
|
/* eslint-disable quote-props, @typescript-eslint/naming-convention */
|
|
169
168
|
"Element": core_common_1.ConcreteEntityTypes.Element,
|
|
@@ -175,4 +174,5 @@ ECReferenceTypesCache.bisRootClassToRefType = {
|
|
|
175
174
|
// see [ConcreteEntityTypes]($common)
|
|
176
175
|
/* eslint-enable quote-props, @typescript-eslint/naming-convention */
|
|
177
176
|
};
|
|
177
|
+
exports.ECReferenceTypesCache = ECReferenceTypesCache;
|
|
178
178
|
//# sourceMappingURL=ECReferenceTypesCache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ECReferenceTypesCache.js","sourceRoot":"","sources":["../../src/ECReferenceTypesCache.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA8D;AAC9D,oDAAmF;AACnF,gEAAyJ;AACzJ,iCAAiC;AAGjC;;GAEG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,gBAAuB,KAAK,CAAC,iDAAiD,CAAC,CAAC,CAAC,CAAC;CACnF;AAFD,kDAEC;AAED;;;;;;;GAOG;AACH,MAAa,qBAAqB;IAAlC;QACE,uGAAuG;QAC/F,4BAAuB,GAAG,IAAI,4BAAa,EAAiD,CAAC;QAC7F,+BAA0B,GAAG,IAAI,4BAAa,EAAiC,CAAC;QAChF,mBAAc,GAAG,IAAI,GAAG,EAAqB,CAAC;IAyJxD,CAAC;IA3IS,KAAK,CAAC,eAAe,CAAC,OAAgB;QAC5C,IAAI,oBAAoB,GAAY,OAAO,CAAC;QAC5C,MAAM,OAAO,CAAC,mBAAmB,CAAC,CAAC,SAAS,EAAE,EAAE;YAC9C,2GAA2G;YAC3G,+GAA+G;YAC/G,iEAAiE;YACjE,MAAM,WAAW,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,UAAU,CAAC,WAAW,EAAE;YACxB,SAAS,CAAC,WAAW,EAAE;YACvB,QAAQ,CAAC,WAAW,EAAE;SACvB,CAAC,CAAC;IACL,CAAC;IAEM,sBAAsB,CAAC,UAAkB,EAAE,SAAiB;QACjE,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC;YACzC,UAAU,CAAC,WAAW,EAAE;YACxB,SAAS,CAAC,WAAW,EAAE;SACxB,CAAC,CAAC;IACL,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,uBAAuB,CAAC,KAAK,EAAE,CAAC;IACvC,CAAC;;AA5JH,sDA6JC;AAvJgB,2CAAqB,GAAoD;IACtF,sEAAsE;IACtE,SAAS,EAAE,iCAAmB,CAAC,OAAO;IACtC,OAAO,EAAE,iCAAmB,CAAC,KAAK;IAClC,eAAe,EAAE,iCAAmB,CAAC,aAAa;IAClD,yBAAyB,EAAE,iCAAmB,CAAC,YAAY;IAC3D,sBAAsB,EAAE,iCAAmB,CAAC,YAAY;IACxD,8EAA8E;IAC9E,qCAAqC;IACrC,qEAAqE;CACtE,AAVmC,CAUlC","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 */\n\nimport { DbResult, TupleKeyedMap } from \"@itwin/core-bentley\";\nimport { ConcreteEntityTypes, IModelError, RelTypeInfo } from \"@itwin/core-common\";\nimport { ECClass, Mixin, RelationshipClass, RelationshipConstraint, Schema, SchemaKey, SchemaLoader, StrengthDirection } from \"@itwin/ecschema-metadata\";\nimport * as assert from \"assert\";\nimport { IModelDb } from \"@itwin/core-backend\";\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 SchemaNotInCacheErr extends Error {\n public constructor() { super(\"Schema was not in cache, initialize that schema\"); }\n}\n\n/**\n * A cache of the entity types referenced by navprops in ecchemas, as well as the source and target entity types of\n * The transformer needs the referenced type to determine how to resolve references.\n *\n * Using multiple of these usually performs redundant computation, for static schemas at least. A possible future optimization\n * would be to seed the computation from a global cache of non-dynamic schemas, but dynamic schemas can collide willy-nilly\n * @internal\n */\nexport class ECReferenceTypesCache {\n /** nesting based tuple map keyed by qualified property path tuple [schemaName, className, propName] */\n private _propQualifierToRefType = new TupleKeyedMap<[string, string, string], ConcreteEntityTypes>();\n private _relClassNameEndToRefTypes = new TupleKeyedMap<[string, string], RelTypeInfo>();\n private _initedSchemas = new Map<string, SchemaKey>();\n\n private static bisRootClassToRefType: Record<string, ConcreteEntityTypes | undefined> = {\n /* eslint-disable quote-props, @typescript-eslint/naming-convention */\n \"Element\": ConcreteEntityTypes.Element,\n \"Model\": ConcreteEntityTypes.Model,\n \"ElementAspect\": ConcreteEntityTypes.ElementAspect,\n \"ElementRefersToElements\": ConcreteEntityTypes.Relationship,\n \"ElementDrivesElement\": ConcreteEntityTypes.Relationship,\n // code spec is technically a potential root class but it is ignored currently\n // see [ConcreteEntityTypes]($common)\n /* eslint-enable quote-props, @typescript-eslint/naming-convention */\n };\n\n private async getRootBisClass(ecclass: ECClass) {\n let bisRootForConstraint: ECClass = ecclass;\n await ecclass.traverseBaseClasses((baseClass) => {\n // The depth first traversal will descend all the way to the root class before making any lateral traversal\n // of mixin hierarchies, (or if the constraint is a mixin, it will traverse to the root of the mixin hierarchy)\n // Once we see that we've moved laterally, we can terminate early\n const isFirstTest = bisRootForConstraint === ecclass;\n const traversalSwitchedRootPath = baseClass.name !== bisRootForConstraint.baseClass?.name;\n const stillTraversingRootPath = isFirstTest || !traversalSwitchedRootPath;\n if (!stillTraversingRootPath)\n return true; // stop traversal early\n bisRootForConstraint = baseClass;\n return false;\n });\n // if the root class of the constraint was a mixin, use its AppliesToEntityClass\n if (bisRootForConstraint instanceof Mixin) {\n assert(bisRootForConstraint.appliesTo !== undefined, \"The referenced AppliesToEntityClass could not be found, how did it pass schema validation?\");\n bisRootForConstraint = await this.getRootBisClass(await bisRootForConstraint.appliesTo);\n }\n return bisRootForConstraint;\n }\n\n private async getAbstractConstraintClass(constraint: RelationshipConstraint): Promise<ECClass> {\n // constraint classes must share a base so we can get the root from any of them, just use the first\n const ecclass = await (constraint.constraintClasses?.[0] || constraint.abstractConstraint);\n assert(ecclass !== undefined, \"At least one constraint class or an abstract constraint must have been defined, the constraint is not valid\");\n return ecclass;\n }\n\n /** initialize from an imodel with metadata */\n public async initAllSchemasInIModel(imodel: IModelDb): Promise<void> {\n const schemaLoader = new SchemaLoader((name: string) => imodel.getSchemaProps(name));\n await imodel.withPreparedStatement(`\n WITH RECURSIVE refs(SchemaId) AS (\n SELECT ECInstanceId FROM ECDbMeta.ECSchemaDef WHERE Name='BisCore'\n UNION ALL\n SELECT sr.SourceECInstanceId\n FROM ECDbMeta.SchemaHasSchemaReferences sr\n JOIN refs ON sr.TargetECInstanceId = refs.SchemaId\n )\n SELECT s.Name\n FROM refs\n JOIN ECDbMeta.ECSchemaDef s ON refs.SchemaId=s.ECInstanceId\n -- ensure schema dependency order\n ORDER BY ECInstanceId\n `, async (stmt) => {\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const schemaName = stmt.getValue(0).getString();\n const schema = schemaLoader.getSchema(schemaName);\n await this.considerInitSchema(schema);\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n });\n }\n\n private async considerInitSchema(schema: Schema): Promise<void> {\n if (this._initedSchemas.has(schema.name)) {\n const cachedSchemaKey = this._initedSchemas.get(schema.name);\n assert(cachedSchemaKey !== undefined);\n const incomingSchemaIsEqualOrOlder = schema.schemaKey.compareByVersion(cachedSchemaKey) <= 0;\n if (incomingSchemaIsEqualOrOlder) {\n return;\n }\n }\n return this.initSchema(schema);\n }\n\n private async initSchema(schema: Schema): Promise<void> {\n for (const ecclass of schema.getClasses()) {\n for (const prop of await ecclass.getProperties()) {\n if (!prop.isNavigation())\n continue;\n const relClass = await prop.relationshipClass;\n const relInfo = await this.relInfoFromRelClass(relClass);\n if (relInfo === undefined)\n continue;\n const navPropRefType = prop.direction === StrengthDirection.Forward ? relInfo.target : relInfo.source;\n this._propQualifierToRefType.set([schema.name.toLowerCase(), ecclass.name.toLowerCase(), prop.name.toLowerCase()], navPropRefType);\n }\n\n if (ecclass instanceof RelationshipClass) {\n const relInfo = await this.relInfoFromRelClass(ecclass);\n if (relInfo)\n this._relClassNameEndToRefTypes.set([schema.name.toLowerCase(), ecclass.name.toLowerCase()], relInfo);\n }\n }\n\n this._initedSchemas.set(schema.name, schema.schemaKey);\n }\n\n private async relInfoFromRelClass(ecclass: RelationshipClass): Promise<RelTypeInfo | undefined> {\n assert(ecclass.source.constraintClasses !== undefined);\n assert(ecclass.target.constraintClasses !== undefined);\n const [[sourceClass, sourceRootBisClass], [targetClass, targetRootBisClass]] = await Promise.all([\n this.getAbstractConstraintClass(ecclass.source)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n this.getAbstractConstraintClass(ecclass.target)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n ]);\n\n if (sourceRootBisClass.name === \"CodeSpec\" || targetRootBisClass.name === \"CodeSpec\")\n return undefined;\n const sourceType = ECReferenceTypesCache.bisRootClassToRefType[sourceRootBisClass.name];\n const targetType = ECReferenceTypesCache.bisRootClassToRefType[targetRootBisClass.name];\n const makeAssertMsg = (root: ECClass, cls: ECClass) => [\n `An unknown root class '${root.fullName}' was encountered while populating`,\n `the nav prop reference type cache for ${cls.fullName}.`,\n \"This is a bug.\",\n ].join(\"\\n\");\n assert(sourceType !== undefined, makeAssertMsg(sourceRootBisClass, sourceClass));\n assert(targetType !== undefined, makeAssertMsg(targetRootBisClass, targetClass));\n return { source: sourceType, target: targetType };\n }\n\n public getNavPropRefType(schemaName: string, className: string, propName: string): undefined | ConcreteEntityTypes {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._propQualifierToRefType.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n propName.toLowerCase(),\n ]);\n }\n\n public getRelationshipEndType(schemaName: string, className: string): undefined | RelTypeInfo {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._relClassNameEndToRefTypes.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n ]);\n }\n\n public clear() {\n this._initedSchemas.clear();\n this._propQualifierToRefType.clear();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ECReferenceTypesCache.js","sourceRoot":"","sources":["../../src/ECReferenceTypesCache.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA8D;AAC9D,oDAAmF;AACnF,gEAAyJ;AACzJ,iCAAiC;AAGjC;;GAEG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,gBAAuB,KAAK,CAAC,iDAAiD,CAAC,CAAC,CAAC,CAAC;CACnF;AAFD,kDAEC;AAED;;;;;;;GAOG;AACH,MAAa,qBAAqB;IAAlC;QACE,uGAAuG;QAC/F,4BAAuB,GAAG,IAAI,4BAAa,EAAiD,CAAC;QAC7F,+BAA0B,GAAG,IAAI,4BAAa,EAAiC,CAAC;QAChF,mBAAc,GAAG,IAAI,GAAG,EAAqB,CAAC;IAyJxD,CAAC;IA3IS,KAAK,CAAC,eAAe,CAAC,OAAgB;QAC5C,IAAI,oBAAoB,GAAY,OAAO,CAAC;QAC5C,MAAM,OAAO,CAAC,mBAAmB,CAAC,CAAC,SAAS,EAAE,EAAE;YAC9C,2GAA2G;YAC3G,+GAA+G;YAC/G,iEAAiE;YACjE,MAAM,WAAW,GAAG,oBAAoB,KAAK,OA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E;YACxB,SAAS,CAAC,WAAW,EAAE;YACvB,QAAQ,CAAC,WAAW,EAAE;SACvB,CAAC,CAAC;IACL,CAAC;IAEM,sBAAsB,CAAC,UAAkB,EAAE,SAAiB;QACjE,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC;YACzC,UAAU,CAAC,WAAW,EAAE;YACxB,SAAS,CAAC,WAAW,EAAE;SACxB,CAAC,CAAC;IACL,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,uBAAuB,CAAC,KAAK,EAAE,CAAC;IACvC,CAAC;;AAtJc,2CAAqB,GAAoD;IACtF,sEAAsE;IACtE,SAAS,EAAE,iCAAmB,CAAC,OAAO;IACtC,OAAO,EAAE,iCAAmB,CAAC,KAAK;IAClC,eAAe,EAAE,iCAAmB,CAAC,aAAa;IAClD,yBAAyB,EAAE,iCAAmB,CAAC,YAAY;IAC3D,sBAAsB,EAAE,iCAAmB,CAAC,YAAY;IACxD,8EAA8E;IAC9E,qCAAqC;IACrC,qEAAqE;CACtE,AAVmC,CAUlC;AAhBS,sDAAqB","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 */\n\nimport { DbResult, TupleKeyedMap } from \"@itwin/core-bentley\";\nimport { ConcreteEntityTypes, IModelError, RelTypeInfo } from \"@itwin/core-common\";\nimport { ECClass, Mixin, RelationshipClass, RelationshipConstraint, Schema, SchemaKey, SchemaLoader, StrengthDirection } from \"@itwin/ecschema-metadata\";\nimport * as assert from \"assert\";\nimport { IModelDb } from \"@itwin/core-backend\";\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 SchemaNotInCacheErr extends Error {\n public constructor() { super(\"Schema was not in cache, initialize that schema\"); }\n}\n\n/**\n * A cache of the entity types referenced by navprops in ecchemas, as well as the source and target entity types of\n * The transformer needs the referenced type to determine how to resolve references.\n *\n * Using multiple of these usually performs redundant computation, for static schemas at least. A possible future optimization\n * would be to seed the computation from a global cache of non-dynamic schemas, but dynamic schemas can collide willy-nilly\n * @internal\n */\nexport class ECReferenceTypesCache {\n /** nesting based tuple map keyed by qualified property path tuple [schemaName, className, propName] */\n private _propQualifierToRefType = new TupleKeyedMap<[string, string, string], ConcreteEntityTypes>();\n private _relClassNameEndToRefTypes = new TupleKeyedMap<[string, string], RelTypeInfo>();\n private _initedSchemas = new Map<string, SchemaKey>();\n\n private static bisRootClassToRefType: Record<string, ConcreteEntityTypes | undefined> = {\n /* eslint-disable quote-props, @typescript-eslint/naming-convention */\n \"Element\": ConcreteEntityTypes.Element,\n \"Model\": ConcreteEntityTypes.Model,\n \"ElementAspect\": ConcreteEntityTypes.ElementAspect,\n \"ElementRefersToElements\": ConcreteEntityTypes.Relationship,\n \"ElementDrivesElement\": ConcreteEntityTypes.Relationship,\n // code spec is technically a potential root class but it is ignored currently\n // see [ConcreteEntityTypes]($common)\n /* eslint-enable quote-props, @typescript-eslint/naming-convention */\n };\n\n private async getRootBisClass(ecclass: ECClass) {\n let bisRootForConstraint: ECClass = ecclass;\n await ecclass.traverseBaseClasses((baseClass) => {\n // The depth first traversal will descend all the way to the root class before making any lateral traversal\n // of mixin hierarchies, (or if the constraint is a mixin, it will traverse to the root of the mixin hierarchy)\n // Once we see that we've moved laterally, we can terminate early\n const isFirstTest = bisRootForConstraint === ecclass;\n const traversalSwitchedRootPath = baseClass.name !== bisRootForConstraint.baseClass?.name;\n const stillTraversingRootPath = isFirstTest || !traversalSwitchedRootPath;\n if (!stillTraversingRootPath)\n return true; // stop traversal early\n bisRootForConstraint = baseClass;\n return false;\n });\n // if the root class of the constraint was a mixin, use its AppliesToEntityClass\n if (bisRootForConstraint instanceof Mixin) {\n assert(bisRootForConstraint.appliesTo !== undefined, \"The referenced AppliesToEntityClass could not be found, how did it pass schema validation?\");\n bisRootForConstraint = await this.getRootBisClass(await bisRootForConstraint.appliesTo);\n }\n return bisRootForConstraint;\n }\n\n private async getAbstractConstraintClass(constraint: RelationshipConstraint): Promise<ECClass> {\n // constraint classes must share a base so we can get the root from any of them, just use the first\n const ecclass = await (constraint.constraintClasses?.[0] || constraint.abstractConstraint);\n assert(ecclass !== undefined, \"At least one constraint class or an abstract constraint must have been defined, the constraint is not valid\");\n return ecclass;\n }\n\n /** initialize from an imodel with metadata */\n public async initAllSchemasInIModel(imodel: IModelDb): Promise<void> {\n const schemaLoader = new SchemaLoader((name: string) => imodel.getSchemaProps(name));\n await imodel.withPreparedStatement(`\n WITH RECURSIVE refs(SchemaId) AS (\n SELECT ECInstanceId FROM ECDbMeta.ECSchemaDef WHERE Name='BisCore'\n UNION ALL\n SELECT sr.SourceECInstanceId\n FROM ECDbMeta.SchemaHasSchemaReferences sr\n JOIN refs ON sr.TargetECInstanceId = refs.SchemaId\n )\n SELECT s.Name\n FROM refs\n JOIN ECDbMeta.ECSchemaDef s ON refs.SchemaId=s.ECInstanceId\n -- ensure schema dependency order\n ORDER BY ECInstanceId\n `, async (stmt) => {\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const schemaName = stmt.getValue(0).getString();\n const schema = schemaLoader.getSchema(schemaName);\n await this.considerInitSchema(schema);\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n });\n }\n\n private async considerInitSchema(schema: Schema): Promise<void> {\n if (this._initedSchemas.has(schema.name)) {\n const cachedSchemaKey = this._initedSchemas.get(schema.name);\n assert(cachedSchemaKey !== undefined);\n const incomingSchemaIsEqualOrOlder = schema.schemaKey.compareByVersion(cachedSchemaKey) <= 0;\n if (incomingSchemaIsEqualOrOlder) {\n return;\n }\n }\n return this.initSchema(schema);\n }\n\n private async initSchema(schema: Schema): Promise<void> {\n for (const ecclass of schema.getClasses()) {\n for (const prop of await ecclass.getProperties()) {\n if (!prop.isNavigation())\n continue;\n const relClass = await prop.relationshipClass;\n const relInfo = await this.relInfoFromRelClass(relClass);\n if (relInfo === undefined)\n continue;\n const navPropRefType = prop.direction === StrengthDirection.Forward ? relInfo.target : relInfo.source;\n this._propQualifierToRefType.set([schema.name.toLowerCase(), ecclass.name.toLowerCase(), prop.name.toLowerCase()], navPropRefType);\n }\n\n if (ecclass instanceof RelationshipClass) {\n const relInfo = await this.relInfoFromRelClass(ecclass);\n if (relInfo)\n this._relClassNameEndToRefTypes.set([schema.name.toLowerCase(), ecclass.name.toLowerCase()], relInfo);\n }\n }\n\n this._initedSchemas.set(schema.name, schema.schemaKey);\n }\n\n private async relInfoFromRelClass(ecclass: RelationshipClass): Promise<RelTypeInfo | undefined> {\n assert(ecclass.source.constraintClasses !== undefined);\n assert(ecclass.target.constraintClasses !== undefined);\n const [[sourceClass, sourceRootBisClass], [targetClass, targetRootBisClass]] = await Promise.all([\n this.getAbstractConstraintClass(ecclass.source)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n this.getAbstractConstraintClass(ecclass.target)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n ]);\n\n if (sourceRootBisClass.name === \"CodeSpec\" || targetRootBisClass.name === \"CodeSpec\")\n return undefined;\n const sourceType = ECReferenceTypesCache.bisRootClassToRefType[sourceRootBisClass.name];\n const targetType = ECReferenceTypesCache.bisRootClassToRefType[targetRootBisClass.name];\n const makeAssertMsg = (root: ECClass, cls: ECClass) => [\n `An unknown root class '${root.fullName}' was encountered while populating`,\n `the nav prop reference type cache for ${cls.fullName}.`,\n \"This is a bug.\",\n ].join(\"\\n\");\n assert(sourceType !== undefined, makeAssertMsg(sourceRootBisClass, sourceClass));\n assert(targetType !== undefined, makeAssertMsg(targetRootBisClass, targetClass));\n return { source: sourceType, target: targetType };\n }\n\n public getNavPropRefType(schemaName: string, className: string, propName: string): undefined | ConcreteEntityTypes {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._propQualifierToRefType.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n propName.toLowerCase(),\n ]);\n }\n\n public getRelationshipEndType(schemaName: string, className: string): undefined | RelTypeInfo {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._relClassNameEndToRefTypes.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n ]);\n }\n\n public clear() {\n this._initedSchemas.clear();\n this._propQualifierToRefType.clear();\n }\n}\n"]}
|
package/lib/cjs/EntityUnifier.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntityUnifier.js","sourceRoot":"","sources":["../../src/EntityUnifier.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;;;GAIG;AACH,iCAAiC;AACjC,oDAAkG;AAClG,sDAA4I;AAC5I,sDAA2C;AAE3C,gBAAgB;AAChB,IAAiB,aAAa,CA0D7B;AA1DD,WAAiB,aAAa;IAC5B,SAAgB,eAAe,CAAC,MAAsB;QACpD,IAAI,MAAM,YAAY,sBAAO;YAC3B,OAAO,SAAS,CAAC;aACd,IAAI,MAAM,YAAY,4BAAa;YACtC,OAAO,gBAAgB,CAAC;aACrB,IAAI,MAAM,YAAY,2BAAY;YACrC,OAAO,cAAc,CAAC;;YAEtB,OAAO,qBAAqB,CAAC;IACjC,CAAC;IATe,6BAAe,kBAS9B,CAAA;IAID,2GAA2G;IAC3G,SAAgB,UAAU,CAAC,EAAY,EAAE,MAAsB;QAC7D,IAAI,MAAM,YAAY,sBAAO;YAC3B,OAAO,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAkB,CAAC;aACjE,IAAI,MAAM,YAAY,2BAAY;Y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C,OAAO,KAAK,CAAC;;oBAEb,MAAM,IAAI,yBAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;YACzD,CAAC,CAAC,CAAC;SACJ;aAAM;YACL,IAAI,GAAG,CAAC,MAAM,CAAC,EAAE,KAAK,SAAS,IAAI,mBAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC9D,OAAO,KAAK,CAAC;YACf,OAAO,EAAE,CAAC,qBAAqB,CAAC,kBAAkB,GAAG,CAAC,MAAM,CAAC,UAAU,MAAM,GAAG,CAAC,MAAM,CAAC,SAAS,wBAAwB,EAAE,CAAC,IAAI,EAAE,EAAE;gBAClI,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC9B,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;gBAClC,IAAI,aAAa,KAAK,sBAAQ,CAAC,aAAa;oBAC1C,OAAO,IAAI,CAAC;gBACd,IAAI,aAAa,KAAK,sBAAQ,CAAC,cAAc;oBAC3C,OAAO,KAAK,CAAC;;oBAEb,MAAM,IAAI,yBAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;YACzD,CAAC,CAAC,CAAC;SACJ;IACH,CAAC;IA/Be,oBAAM,SA+BrB,CAAA;AACH,CAAC,EA1DgB,aAAa,GAAb,qBAAa,KAAb,qBAAa,QA0D7B","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 */\nimport * as assert from \"assert\";\nimport { ConcreteEntityTypes, DbResult, EntityReference, IModelError } from \"@itwin/core-common\";\nimport { ConcreteEntity, ConcreteEntityProps, Element, ElementAspect, EntityReferences, IModelDb, Relationship } 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)\n return \"element\";\n else if (entity instanceof ElementAspect)\n return \"element aspect\";\n else if (entity instanceof Relationship)\n return \"relationship\";\n else\n 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(db.relationships) as EntityUpdater;\n else if (entity instanceof ElementAspect)\n return db.elements.updateAspect.bind(db.elements) as EntityUpdater;\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n export function exists(db: IModelDb, arg: { entity: ConcreteEntity } | { entityReference: EntityReference }) {\n if (\"entityReference\" in arg) {\n const [type, id] = EntityReferences.split(arg.entityReference);\n // FIXME: add a test with a deleted reference that triggers this\n if (id === undefined || Id64.isInvalid(id))\n return false;\n const bisCoreRootClassName = ConcreteEntityTypes.toBisCoreRootClassFullName(type);\n return db.withPreparedStatement(`SELECT 1 FROM ${bisCoreRootClassName} WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n } else {\n if (arg.entity.id === undefined || Id64.isInvalid(arg.entity.id))\n return false;\n return db.withPreparedStatement(`SELECT 1 FROM [${arg.entity.schemaName}].[${arg.entity.className}] WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, arg.entity.id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n }\n }\n}\n"]}
|
|
@@ -147,7 +147,7 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
|
|
|
147
147
|
// return a null
|
|
148
148
|
if (!core_backend_1.EntityReferences.isValid(relInTarget.sourceId) || !core_backend_1.EntityReferences.isValid(relInTarget.targetId))
|
|
149
149
|
break;
|
|
150
|
-
const relInTargetId = this.
|
|
150
|
+
const relInTargetId = this.sourceDb.withPreparedStatement(`
|
|
151
151
|
SELECT ECInstanceId
|
|
152
152
|
FROM BisCore:ElementRefersToElements
|
|
153
153
|
WHERE SourceECInstanceId=?
|
|
@@ -155,8 +155,8 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
|
|
|
155
155
|
`, (stmt) => {
|
|
156
156
|
stmt.bindId(1, core_backend_1.EntityReferences.toId64(relInTarget.sourceId));
|
|
157
157
|
stmt.bindId(2, core_backend_1.EntityReferences.toId64(relInTarget.targetId));
|
|
158
|
-
|
|
159
|
-
if (status === core_bentley_1.DbResult.BE_SQLITE_ROW)
|
|
158
|
+
let status;
|
|
159
|
+
if ((status = stmt.step()) === core_bentley_1.DbResult.BE_SQLITE_ROW)
|
|
160
160
|
return stmt.getValue(0).getId();
|
|
161
161
|
if (status !== core_bentley_1.DbResult.BE_SQLITE_DONE)
|
|
162
162
|
throw new core_common_1.IModelError(status, "unexpected query failure");
|
|
@@ -221,6 +221,6 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
|
|
|
221
221
|
});
|
|
222
222
|
}
|
|
223
223
|
}
|
|
224
|
-
exports.IModelCloneContext = IModelCloneContext;
|
|
225
224
|
IModelCloneContext.aspectRemapTableName = "AspectIdRemaps";
|
|
225
|
+
exports.IModelCloneContext = IModelCloneContext;
|
|
226
226
|
//# sourceMappingURL=IModelCloneContext.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IMod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AAI,EAAE,EAAE;YACP,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,iBAAiB,EAAE;gBACrD,IAAI,CAAC,KAAK,EAAE,CAAC;gBACb,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;gBACvB,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;gBACvB,IAAI,uBAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,IAAI,EAAE;oBACzC,MAAM,KAAK,CAAC,2DAA2D,CAAC,CAAC;aAC5E;QACH,CAAC,CAAC,CAAC;IACP,CAAC;IAEe,eAAe,CAAC,EAAY;QAC1C,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;QAC1B,mBAAmB;QACnB,EAAE,CAAC,mBAAmB,CAAC,8BAA8B,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;YACvG,IAAI,MAAM,GAAG,uBAAQ,CAAC,eAAe,CAAC;YACtC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,uBAAQ,CAAC,aAAa,EAAE;gBACxD,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;aAC5C;YACD,MAAM,CAAC,MAAM,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACL,CAAC;;AA1NH,gDA2NC;AAnCgB,uCAAoB,GAAG,gBAAgB,AAAnB,CAAoB","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, ElementAspectProps, ElementProps, EntityReference, IModel, IModelError,\n PrimitiveTypeCode, PropertyMetaData, RelatedElement, RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n Element, ElementAspect, EntityReferences, IModelElementCloneContext, IModelJsNative, SQLiteDb,\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\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(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): ElementProps {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const targetElementProps: ElementProps = this[\"_nativeContext\"].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((propertyName: string, meta: PropertyMetaData) => {\n if ((meta.isNavigation) && (undefined === (sourceElement as any)[propertyName])) {\n (targetElementProps as any)[propertyName] = RelatedElement.none;\n }\n }, false); // 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(targetElementProps.code.spec).scopeType;\n if (CodeScopeSpec.Type.Repository === targetElementCodeScopeType && targetElementProps.code.scope !== IModel.rootSubjectId) {\n Logger.logWarning(loggerCategory, `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`);\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 (targetElementProps.code.scope === Id64.invalid || targetElementProps.code.spec === Id64.invalid) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(sourceElement.classFullName);\n // eslint-disable-next-line @typescript-eslint/dot-notation\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(aspectSourceId: Id64String, aspectTargetId: Id64String): 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 const targetId = `m${this.findTargetElementId(rawId)}` as const;\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 (EntityUnifier.exists(this.targetDb, { entityReference: targetId }))\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 relInSource = this.sourceDb.withPreparedStatement(\n `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\"SourceECClassId\")}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\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 ConcreteEntityTypes | \"error\";\n const targetType = stmt.getValue(3).getString() as ConcreteEntityTypes | \"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 if (relInSource === undefined)\n break;\n // just in case prevent recursion\n if (relInSource.sourceId === sourceEntityId || relInSource.targetId === sourceEntityId)\n throw Error(\"link table relationship end was resolved to itself. This should be impossible\");\n const relInTarget = {\n sourceId: this.findTargetEntityId(relInSource.sourceId),\n targetId: this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (!EntityReferences.isValid(relInTarget.sourceId) || !EntityReferences.isValid(relInTarget.targetId))\n break;\n const relInTargetId = this.targetDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\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 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(sourceElementAspect: ElementAspect): ElementAspectProps {\n const targetElementAspectProps: ElementAspectProps = sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {\n if (propertyMetaData.isNavigation) {\n const sourceNavProp: RelatedElementProps | undefined = sourceElementAspect.asAny[propertyName];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n propertyName\n );\n assert(navPropRefType !== undefined,`nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`);\n const targetEntityReference = this.findTargetEntityId(EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType));\n const targetEntityId = EntityReferences.toId64(targetEntityReference);\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[propertyName] = { ...(targetElementAspectProps as any)[propertyName], id: targetEntityId };\n }\n } else if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetElementAspectProps as any)[propertyName] = this.findTargetElementId(sourceElementAspect.asAny[propertyName]);\n }\n });\n return targetElementAspectProps;\n }\n\n private static aspectRemapTableName = \"AspectIdRemaps\";\n\n public override saveStateToDb(db: SQLiteDb): void {\n super.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(\n `CREATE TABLE ${IModelCloneContext.aspectRemapTableName} (Source INTEGER, Target INTEGER)`\n ))\n throw Error(\"Failed to create the aspect remap table in the state database\");\n db.saveChanges();\n db.withPreparedSqliteStatement(\n `INSERT INTO ${IModelCloneContext.aspectRemapTableName} (Source, Target) VALUES (?, ?)`,\n (stmt) => {\n for (const [source, target] of this._aspectRemapTable) {\n stmt.reset();\n stmt.bindId(1, source);\n stmt.bindId(2, target);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert aspect remapping into the state database\");\n }\n });\n }\n\n public override loadStateFromDb(db: SQLiteDb): void {\n super.loadStateFromDb(db);\n // FIXME: test this\n db.withSqliteStatement(`SELECT Source, Target FROM ${IModelCloneContext.aspectRemapTableName}`, (stmt) => {\n let status = DbResult.BE_SQLITE_ERROR;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const source = stmt.getValue(0).getId();\n const target = stmt.getValue(1).getId();\n this._aspectRemapTable.set(source, target);\n }\n assert(status === DbResult.BE_SQLITE_DONE);\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"IModelCloneContext.js","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,iCAAiC;AACjC,sDAAyE;AACzE,oDAK4B;AAC5B,sDAE6B;AAC7B,mEAAgE;AAChE,mDAAgD;AAChD,2EAAwE;AAExE,MAAM,cAAc,GAAW,qDAAyB,CAAC,kBAAkB,CAA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AE,MAAM,CAAC,CAAC;gBACvB,IAAI,uBAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,IAAI,EAAE;oBACzC,MAAM,KAAK,CAAC,2DAA2D,CAAC,CAAC;aAC5E;QACH,CAAC,CAAC,CAAC;IACP,CAAC;IAEe,eAAe,CAAC,EAAY;QAC1C,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;QAC1B,mBAAmB;QACnB,EAAE,CAAC,mBAAmB,CAAC,8BAA8B,kBAAkB,CAAC,oBAAoB,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;YACvG,IAAI,MAAM,GAAG,uBAAQ,CAAC,eAAe,CAAC;YACtC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,uBAAQ,CAAC,aAAa,EAAE;gBACxD,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;aAC5C;YACD,MAAM,CAAC,MAAM,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACL,CAAC;;AAlCc,uCAAoB,GAAG,gBAAgB,AAAnB,CAAoB;AAxL5C,gDAAkB","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, ElementAspectProps, ElementProps, EntityReference, IModel, IModelError,\n PrimitiveTypeCode, PropertyMetaData, RelatedElement, RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n Element, ElementAspect, EntityReferences, IModelElementCloneContext, IModelJsNative, SQLiteDb,\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\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(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): ElementProps {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const targetElementProps: ElementProps = this[\"_nativeContext\"].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((propertyName: string, meta: PropertyMetaData) => {\n if ((meta.isNavigation) && (undefined === (sourceElement as any)[propertyName])) {\n (targetElementProps as any)[propertyName] = RelatedElement.none;\n }\n }, false); // 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(targetElementProps.code.spec).scopeType;\n if (CodeScopeSpec.Type.Repository === targetElementCodeScopeType && targetElementProps.code.scope !== IModel.rootSubjectId) {\n Logger.logWarning(loggerCategory, `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`);\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 (targetElementProps.code.scope === Id64.invalid || targetElementProps.code.spec === Id64.invalid) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(sourceElement.classFullName);\n // eslint-disable-next-line @typescript-eslint/dot-notation\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(aspectSourceId: Id64String, aspectTargetId: Id64String): 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 const targetId = `m${this.findTargetElementId(rawId)}` as const;\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 (EntityUnifier.exists(this.targetDb, { entityReference: targetId }))\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 relInSource = this.sourceDb.withPreparedStatement(\n `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\"SourceECClassId\")}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\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 ConcreteEntityTypes | \"error\";\n const targetType = stmt.getValue(3).getString() as ConcreteEntityTypes | \"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 if (relInSource === undefined)\n break;\n // just in case prevent recursion\n if (relInSource.sourceId === sourceEntityId || relInSource.targetId === sourceEntityId)\n throw Error(\"link table relationship end was resolved to itself. This should be impossible\");\n const relInTarget = {\n sourceId: this.findTargetEntityId(relInSource.sourceId),\n targetId: this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (!EntityReferences.isValid(relInTarget.sourceId) || !EntityReferences.isValid(relInTarget.targetId))\n break;\n const relInTargetId = this.sourceDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, EntityReferences.toId64(relInTarget.sourceId));\n stmt.bindId(2, EntityReferences.toId64(relInTarget.targetId));\n let status: DbResult;\n if ((status = stmt.step()) === 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 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(sourceElementAspect: ElementAspect): ElementAspectProps {\n const targetElementAspectProps: ElementAspectProps = sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {\n if (propertyMetaData.isNavigation) {\n const sourceNavProp: RelatedElementProps | undefined = sourceElementAspect.asAny[propertyName];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n propertyName\n );\n assert(navPropRefType !== undefined,`nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`);\n const targetEntityReference = this.findTargetEntityId(EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType));\n const targetEntityId = EntityReferences.toId64(targetEntityReference);\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[propertyName] = { ...(targetElementAspectProps as any)[propertyName], id: targetEntityId };\n }\n } else if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetElementAspectProps as any)[propertyName] = this.findTargetElementId(sourceElementAspect.asAny[propertyName]);\n }\n });\n return targetElementAspectProps;\n }\n\n private static aspectRemapTableName = \"AspectIdRemaps\";\n\n public override saveStateToDb(db: SQLiteDb): void {\n super.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(\n `CREATE TABLE ${IModelCloneContext.aspectRemapTableName} (Source INTEGER, Target INTEGER)`\n ))\n throw Error(\"Failed to create the aspect remap table in the state database\");\n db.saveChanges();\n db.withPreparedSqliteStatement(\n `INSERT INTO ${IModelCloneContext.aspectRemapTableName} (Source, Target) VALUES (?, ?)`,\n (stmt) => {\n for (const [source, target] of this._aspectRemapTable) {\n stmt.reset();\n stmt.bindId(1, source);\n stmt.bindId(2, target);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert aspect remapping into the state database\");\n }\n });\n }\n\n public override loadStateFromDb(db: SQLiteDb): void {\n super.loadStateFromDb(db);\n // FIXME: test this\n db.withSqliteStatement(`SELECT Source, Target FROM ${IModelCloneContext.aspectRemapTableName}`, (stmt) => {\n let status = DbResult.BE_SQLITE_ERROR;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const source = stmt.getValue(0).getId();\n const target = stmt.getValue(1).getId();\n this._aspectRemapTable.set(source, target);\n }\n assert(status === DbResult.BE_SQLITE_DONE);\n });\n }\n}\n"]}
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { BriefcaseDb, Element, ElementAspect, ElementMultiAspect, ElementUniqueAspect, IModelDb, IModelJsNative, Model, Relationship } from "@itwin/core-backend";
|
|
5
5
|
import { AccessToken, CompressedId64Set, Id64String } from "@itwin/core-bentley";
|
|
6
|
-
import {
|
|
6
|
+
import { CodeSpec, FontProps } from "@itwin/core-common";
|
|
7
7
|
import { Schema, SchemaKey } from "@itwin/ecschema-metadata";
|
|
8
|
-
import type {
|
|
8
|
+
import type { InitOptions } from "./IModelTransformer";
|
|
9
9
|
/**
|
|
10
10
|
* @beta
|
|
11
11
|
* The (optional) result of [[IModelExportHandler.onExportSchema]]
|
|
@@ -18,13 +18,19 @@ export interface ExportSchemaResult {
|
|
|
18
18
|
* Arguments for [[IModelExporter.exportChanges]]
|
|
19
19
|
* @public
|
|
20
20
|
*/
|
|
21
|
-
export interface ExportChangesOptions extends
|
|
21
|
+
export interface ExportChangesOptions extends InitOptions {
|
|
22
22
|
/**
|
|
23
23
|
* Class instance that contains modified elements between 2 versions of an iModel.
|
|
24
24
|
* If this parameter is not provided, then [[ChangedInstanceIds.initialize]] in [[IModelExporter.exportChanges]]
|
|
25
25
|
* will be called to discover changed elements.
|
|
26
|
+
* @note mutually exclusive with @see changesetRanges
|
|
26
27
|
*/
|
|
27
28
|
changedInstanceIds?: ChangedInstanceIds;
|
|
29
|
+
/**
|
|
30
|
+
* An ordered array of changeset index ranges, e.g. [[2,2], [4,5]] is [2,4,5]
|
|
31
|
+
* @note mutually exclusive with @see startChangeset, so define one or the other, not both
|
|
32
|
+
*/
|
|
33
|
+
changesetRanges?: [number, number][];
|
|
28
34
|
}
|
|
29
35
|
/** Handles the events generated by IModelExporter.
|
|
30
36
|
* @note Change information is available when `IModelExportHandler` methods are invoked via [IModelExporter.exportChanges]($transformer), but not available when invoked via [IModelExporter.exportAll]($transformer).
|
|
@@ -204,11 +210,13 @@ export declare class IModelExporter {
|
|
|
204
210
|
* @note [[exportSchemas]] must be called separately.
|
|
205
211
|
*/
|
|
206
212
|
exportAll(): Promise<void>;
|
|
207
|
-
/**
|
|
208
|
-
*
|
|
213
|
+
/** Export changes from the source iModel.
|
|
214
|
+
* Inserts, updates, and deletes are determined by inspecting the changeset(s).
|
|
215
|
+
* @note To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired
|
|
216
|
+
* range and open the source iModel as of the end (inclusive) of the desired range.
|
|
209
217
|
*/
|
|
210
218
|
exportChanges(args?: ExportChangesOptions): Promise<void>;
|
|
211
|
-
/** @deprecated in 0.1.x, use a single
|
|
219
|
+
/** @deprecated in 0.1.x, use a single [[ExportChangesOptions]] object instead */
|
|
212
220
|
exportChanges(accessToken?: AccessToken, startChangesetId?: string, args?: ExportChangesOptions): Promise<void>;
|
|
213
221
|
/** Export schemas from the source iModel.
|
|
214
222
|
* @note This must be called separately from [[exportAll]] or [[exportChanges]].
|
|
@@ -336,8 +344,6 @@ export interface IModelExporterState {
|
|
|
336
344
|
* @beta
|
|
337
345
|
*/
|
|
338
346
|
export interface ChangedInstanceIdsInitOptions extends ExportChangesOptions {
|
|
339
|
-
/** @inheritdoc */
|
|
340
|
-
startChangeset: ChangesetIndexOrId;
|
|
341
347
|
iModel: BriefcaseDb;
|
|
342
348
|
}
|
|
343
349
|
/** Class for holding change information.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IModelExporter.d.ts","sourceRoot":"","sources":["../../src/IModelExporter.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EACL,WAAW,EAAqD,OAAO,EAAE,aAAa,EACtF,kBAAkB,EAA2B,mBAAmB,EAAoB,QAAQ,EAChF,cAAc,EAAE,KAAK,EAA2B,YAAY,EACzE,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAU,iBAAiB,EAAkB,UAAU,EAAsC,MAAM,qBAAqB,CAAC;AAC7I,OAAO,
|
|
1
|
+
{"version":3,"file":"IModelExporter.d.ts","sourceRoot":"","sources":["../../src/IModelExporter.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EACL,WAAW,EAAqD,OAAO,EAAE,aAAa,EACtF,kBAAkB,EAA2B,mBAAmB,EAAoB,QAAQ,EAChF,cAAc,EAAE,KAAK,EAA2B,YAAY,EACzE,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAU,iBAAiB,EAAkB,UAAU,EAAsC,MAAM,qBAAqB,CAAC;AAC7I,OAAO,EAAsB,QAAQ,EAAE,SAAS,EAAuB,MAAM,oBAAoB,CAAC;AAClG,OAAO,EAAa,MAAM,EAAE,SAAS,EAAgB,MAAM,0BAA0B,CAAC;AAEtF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAKv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BAA4B;IACxC,IAAI,qBAA4B;IACvC,OAAO;IAEP;;OAEG;WACiB,UAAU,CAAC,IAAI,EAAE,6BAA6B,GAAG,OAAO,CAAC,kBAAkB,CAAC;CA4EjG"}
|
|
@@ -13,6 +13,7 @@ const core_bentley_1 = require("@itwin/core-bentley");
|
|
|
13
13
|
const core_common_1 = require("@itwin/core-common");
|
|
14
14
|
const ecschema_metadata_1 = require("@itwin/ecschema-metadata");
|
|
15
15
|
const TransformerLoggerCategory_1 = require("./TransformerLoggerCategory");
|
|
16
|
+
const nodeAssert = require("assert");
|
|
16
17
|
const loggerCategory = TransformerLoggerCategory_1.TransformerLoggerCategory.IModelExporter;
|
|
17
18
|
/** Handles the events generated by IModelExporter.
|
|
18
19
|
* @note Change information is available when `IModelExportHandler` methods are invoked via [IModelExporter.exportChanges]($transformer), but not available when invoked via [IModelExporter.exportAll]($transformer).
|
|
@@ -217,30 +218,24 @@ class IModelExporter {
|
|
|
217
218
|
await this.exportModel(core_common_1.IModel.repositoryModelId);
|
|
218
219
|
await this.exportRelationships(core_backend_1.ElementRefersToElements.classFullName);
|
|
219
220
|
}
|
|
220
|
-
async exportChanges(
|
|
221
|
+
async exportChanges(accessTokenOrOpts, startChangesetId) {
|
|
221
222
|
if (!this.sourceDb.isBriefcaseDb())
|
|
222
223
|
throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Must be a briefcase to export changes");
|
|
223
224
|
if ("" === this.sourceDb.changeset.id) {
|
|
224
225
|
await this.exportAll(); // no changesets, so revert to exportAll
|
|
225
226
|
return;
|
|
226
227
|
}
|
|
227
|
-
const
|
|
228
|
-
?
|
|
228
|
+
const opts = typeof accessTokenOrOpts === "object"
|
|
229
|
+
? accessTokenOrOpts
|
|
229
230
|
: {
|
|
230
|
-
accessToken:
|
|
231
|
+
accessToken: accessTokenOrOpts,
|
|
231
232
|
startChangeset: { id: startChangesetId },
|
|
232
233
|
};
|
|
233
234
|
this._sourceDbChanges =
|
|
234
|
-
(typeof
|
|
235
|
-
?
|
|
235
|
+
(typeof accessTokenOrOpts === "object"
|
|
236
|
+
? accessTokenOrOpts.changedInstanceIds
|
|
236
237
|
: undefined)
|
|
237
|
-
?? await ChangedInstanceIds.initialize({
|
|
238
|
-
accessToken,
|
|
239
|
-
startChangeset: startChangeset?.id !== undefined || startChangeset?.index !== undefined
|
|
240
|
-
? startChangeset
|
|
241
|
-
: this.sourceDb.changeset,
|
|
242
|
-
iModel: this.sourceDb,
|
|
243
|
-
});
|
|
238
|
+
?? await ChangedInstanceIds.initialize({ ...opts, iModel: this.sourceDb });
|
|
244
239
|
await this.exportCodeSpecs();
|
|
245
240
|
await this.exportFonts();
|
|
246
241
|
await this.exportModelContents(core_common_1.IModel.repositoryModelId);
|
|
@@ -795,13 +790,31 @@ class ChangedInstanceIds {
|
|
|
795
790
|
iModel: iModel,
|
|
796
791
|
startChangeset: { id: startChangesetId },
|
|
797
792
|
};
|
|
798
|
-
|
|
793
|
+
nodeAssert(((opts.startChangeset ? 1 : 0) + (opts.changesetRanges ? 1 : 0)) === 1, "exactly one of options.startChangeset XOR opts.changesetRanges may be used");
|
|
799
794
|
const iModelId = opts.iModel.iModelId;
|
|
800
|
-
const
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
795
|
+
const accessToken = opts.accessToken;
|
|
796
|
+
const changesetRanges = opts.changesetRanges
|
|
797
|
+
?? [[
|
|
798
|
+
// we know startChangeset is defined because of the assert above
|
|
799
|
+
opts.startChangeset.index
|
|
800
|
+
?? (await core_backend_1.IModelHost.hubAccess.queryChangeset({
|
|
801
|
+
iModelId,
|
|
802
|
+
changeset: { id: opts.startChangeset.id ?? opts.iModel.changeset.id },
|
|
803
|
+
accessToken,
|
|
804
|
+
})).index,
|
|
805
|
+
opts.iModel.changeset.index
|
|
806
|
+
?? (await core_backend_1.IModelHost.hubAccess.queryChangeset({
|
|
807
|
+
iModelId,
|
|
808
|
+
changeset: { id: opts.iModel.changeset.id },
|
|
809
|
+
accessToken,
|
|
810
|
+
})).index,
|
|
811
|
+
]];
|
|
812
|
+
core_bentley_1.Logger.logTrace(loggerCategory, `ChangedInstanceIds.initialize ranges: ${changesetRanges.join("|")}`);
|
|
813
|
+
const changesets = (await Promise.all(changesetRanges.map(async ([first, end]) => core_backend_1.IModelHost.hubAccess.downloadChangesets({
|
|
814
|
+
accessToken,
|
|
815
|
+
iModelId, range: { first, end },
|
|
816
|
+
targetDir: core_backend_1.BriefcaseManager.getChangeSetsPath(iModelId),
|
|
817
|
+
})))).flat();
|
|
805
818
|
const changedInstanceIds = new ChangedInstanceIds();
|
|
806
819
|
const changesetFiles = changesets.map((c) => c.pathname);
|
|
807
820
|
const statusOrResult = opts.iModel.nativeDb.extractChangedInstanceIdsFromChangeSets(changesetFiles);
|