-
Notifications
You must be signed in to change notification settings - Fork 2
/
IModelCloneContext.ts
283 lines (274 loc) · 11.3 KB
/
IModelCloneContext.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module iModels
*/
import * as assert from "assert";
import { DbResult, Id64, Id64String, Logger } from "@itwin/core-bentley";
import {
Code,
CodeScopeSpec,
ConcreteEntityTypes,
ElementAspectProps,
ElementProps,
EntityReference,
IModel,
IModelError,
PrimitiveTypeCode,
PropertyMetaData,
RelatedElement,
RelatedElementProps,
} from "@itwin/core-common";
import {
// eslint-disable-next-line @typescript-eslint/no-redeclare
Element,
ElementAspect,
EntityReferences,
IModelElementCloneContext,
IModelJsNative,
} from "@itwin/core-backend";
import { ECReferenceTypesCache } from "./ECReferenceTypesCache";
import { EntityUnifier } from "./EntityUnifier";
import { TransformerLoggerCategory } from "./TransformerLoggerCategory";
const loggerCategory: string = TransformerLoggerCategory.IModelCloneContext;
/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.
* @beta
*/
export class IModelCloneContext extends IModelElementCloneContext {
private _refTypesCache = new ECReferenceTypesCache();
private _aspectRemapTable = new Map<Id64String, Id64String>();
/** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */
public override async initialize() {
await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);
}
/** Clone the specified source Element into ElementProps for the target iModel.
* @internal
*/
public override cloneElement(
sourceElement: Element,
cloneOptions?: IModelJsNative.CloneElementOptions
): ElementProps {
const targetElementProps: ElementProps = this[
"_nativeContext"
].cloneElement(sourceElement.id, cloneOptions);
// Ensure that all NavigationProperties in targetElementProps have a defined value so "clearing" changes will be part of the JSON used for update
sourceElement.forEachProperty(
(propertyName: string, meta: PropertyMetaData) => {
if (
meta.isNavigation &&
undefined === (sourceElement as any)[propertyName]
) {
(targetElementProps as any)[propertyName] = RelatedElement.none;
}
},
false
); // exclude custom because C++ has already handled them
if (this.isBetweenIModels) {
// The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels
targetElementProps.federationGuid = sourceElement.federationGuid;
const targetElementCodeScopeType = this.targetDb.codeSpecs.getById(
targetElementProps.code.spec
).scopeType;
if (
CodeScopeSpec.Type.Repository === targetElementCodeScopeType &&
targetElementProps.code.scope !== IModel.rootSubjectId
) {
Logger.logWarning(
loggerCategory,
`Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`
);
}
}
// unlike other references, code cannot be null. If it is null, use an empty code instead
// this will be updated back later as the transformer resolves references
if (
targetElementProps.code.scope === Id64.invalid ||
targetElementProps.code.spec === Id64.invalid
) {
targetElementProps.code = Code.createEmpty();
}
const jsClass = this.sourceDb.getJsClass<typeof Element>(
sourceElement.classFullName
);
jsClass["onCloned"](this, sourceElement.toJSON(), targetElementProps);
return targetElementProps;
}
/** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */
public remapElementAspect(
aspectSourceId: Id64String,
aspectTargetId: Id64String
): void {
this._aspectRemapTable.set(aspectSourceId, aspectTargetId);
}
/** Remove a rule that remaps the specified source ElementAspect */
public removeElementAspect(aspectSourceId: Id64String): void {
this._aspectRemapTable.delete(aspectSourceId);
}
/** Look up a target AspectId from the source AspectId.
* @returns the target AspectId or [Id64.invalid]($bentley) if a mapping not found.
*/
public findTargetAspectId(sourceAspectId: Id64String): Id64String {
return this._aspectRemapTable.get(sourceAspectId) ?? Id64.invalid;
}
/** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)
* @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.
*/
public findTargetEntityId(sourceEntityId: EntityReference): EntityReference {
const [type, rawId] = EntityReferences.split(sourceEntityId);
if (Id64.isValid(rawId)) {
switch (type) {
case ConcreteEntityTypes.Model: {
const targetId = `m${this.findTargetElementId(rawId)}` as const;
// Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.
// That can occur in the transformer since a submodeled element is imported before its submodel.
if (
EntityUnifier.exists(this.targetDb, { entityReference: targetId })
)
return targetId;
break;
}
case ConcreteEntityTypes.Element:
return `e${this.findTargetElementId(rawId)}`;
case ConcreteEntityTypes.ElementAspect:
return `a${this.findTargetAspectId(rawId)}`;
case ConcreteEntityTypes.Relationship: {
const makeGetConcreteEntityTypeSql = (property: string) => `
CASE
WHEN [${property}] IS (BisCore.ElementUniqueAspect) OR [${property}] IS (BisCore.ElementMultiAspect)
THEN 'a'
WHEN [${property}] IS (BisCore.Element)
THEN 'e'
WHEN [${property}] IS (BisCore.Model)
THEN 'm'
WHEN [${property}] IS (BisCore.CodeSpec)
THEN 'c'
WHEN [${property}] IS (BisCore.ElementRefersToElements) -- TODO: ElementDrivesElement still not handled by the transformer
THEN 'r'
ELSE 'error'
END
`;
const relInSource = this.sourceDb.withPreparedStatement(
`
SELECT
SourceECInstanceId,
TargetECInstanceId,
(${makeGetConcreteEntityTypeSql(
"SourceECClassId"
)}) AS SourceType,
(${makeGetConcreteEntityTypeSql("TargetECClassId")}) AS TargetType
FROM BisCore:ElementRefersToElements
WHERE ECInstanceId=?
`,
(stmt) => {
stmt.bindId(1, rawId);
let status: DbResult;
while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {
const sourceId = stmt.getValue(0).getId();
const targetId = stmt.getValue(1).getId();
const sourceType = stmt.getValue(2).getString() as
| ConcreteEntityTypes
| "error";
const targetType = stmt.getValue(3).getString() as
| ConcreteEntityTypes
| "error";
if (sourceType === "error" || targetType === "error")
throw Error("relationship end had unknown root class");
return {
sourceId: `${sourceType}${sourceId}`,
targetId: `${targetType}${targetId}`,
} as const;
}
if (status !== DbResult.BE_SQLITE_DONE)
throw new IModelError(status, "unexpected query failure");
return undefined;
}
);
if (relInSource === undefined) break;
// just in case prevent recursion
if (
relInSource.sourceId === sourceEntityId ||
relInSource.targetId === sourceEntityId
)
throw Error(
"link table relationship end was resolved to itself. This should be impossible"
);
const relInTarget = {
sourceId: this.findTargetEntityId(relInSource.sourceId),
targetId: this.findTargetEntityId(relInSource.targetId),
};
// return a null
if (
!EntityReferences.isValid(relInTarget.sourceId) ||
!EntityReferences.isValid(relInTarget.targetId)
)
break;
const relInTargetId = this.targetDb.withPreparedStatement(
`
SELECT ECInstanceId
FROM BisCore:ElementRefersToElements
WHERE SourceECInstanceId=?
AND TargetECInstanceId=?
`,
(stmt) => {
stmt.bindId(1, EntityReferences.toId64(relInTarget.sourceId));
stmt.bindId(2, EntityReferences.toId64(relInTarget.targetId));
const status: DbResult = stmt.step();
if (status === DbResult.BE_SQLITE_ROW)
return stmt.getValue(0).getId();
if (status !== DbResult.BE_SQLITE_DONE)
throw new IModelError(status, "unexpected query failure");
return Id64.invalid;
}
);
return `r${relInTargetId}`;
}
}
}
return `${type}${Id64.invalid}`;
}
/** Clone the specified source Element into ElementProps for the target iModel.
* @internal
*/
public cloneElementAspect(
sourceElementAspect: ElementAspect
): ElementAspectProps {
const targetElementAspectProps: ElementAspectProps =
sourceElementAspect.toJSON();
targetElementAspectProps.id = undefined;
sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {
if (propertyMetaData.isNavigation) {
const sourceNavProp: RelatedElementProps | undefined =
sourceElementAspect.asAny[propertyName];
if (sourceNavProp?.id) {
const navPropRefType = this._refTypesCache.getNavPropRefType(
sourceElementAspect.schemaName,
sourceElementAspect.className,
propertyName
);
assert(
navPropRefType !== undefined,
`nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`
);
const targetEntityReference = this.findTargetEntityId(
EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType)
);
const targetEntityId = EntityReferences.toId64(targetEntityReference);
// spread the property in case toJSON did not deep-clone
(targetElementAspectProps as any)[propertyName] = {
...(targetElementAspectProps as any)[propertyName],
id: targetEntityId,
};
}
} else if (
PrimitiveTypeCode.Long === propertyMetaData.primitiveType &&
"Id" === propertyMetaData.extendedType
) {
(targetElementAspectProps as any)[propertyName] =
this.findTargetElementId(sourceElementAspect.asAny[propertyName]);
}
});
return targetElementAspectProps;
}
}