-
Notifications
You must be signed in to change notification settings - Fork 208
/
IModelExporter.ts
553 lines (505 loc) · 27.2 KB
/
IModelExporter.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------------------------------------------*/
import { DbResult, Id64Set, Id64String, Logger } from "@bentley/bentleyjs-core";
import { ChangeOpCode, CodeSpec, FontProps, IModel } from "@bentley/imodeljs-common";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { AuthorizedBackendRequestContext } from "./BackendRequestContext";
import { ChangeSummary, ChangeSummaryExtractOptions, ChangeSummaryManager, InstanceChange } from "./ChangeSummaryManager";
import { ECSqlStatement } from "./ECSqlStatement";
import { Element, GeometricElement } from "./Element";
import { ElementAspect, ElementMultiAspect, ElementUniqueAspect } from "./ElementAspect";
import { Entity } from "./Entity";
import { IModelDb } from "./IModelDb";
import { DefinitionModel, Model } from "./Model";
import { ElementRefersToElements, Relationship, RelationshipProps } from "./Relationship";
const loggerCategory: string = BackendLoggerCategory.IModelExporter;
/** Options provided to the [[IModelExporter]] constructor.
* @alpha
*/
export interface IModelExportOptions { // tslint:disable-line:no-empty-interface
// WIP: expect export options in the future
}
/** Handles the events generated by IModelExporter.
* @alpha
*/
export abstract class IModelExportHandler {
/** If `true` is returned, then the CodeSpec will be exported. */
protected shouldExportCodeSpec(_codeSpec: CodeSpec): boolean { return true; }
/** Called when a CodeSpec should be exported.
* @param codeSpec The CodeSpec to export
* @param isUpdate If defined, then `true` indicates an UPDATE operation while `false` indicates an INSERT operation. If not defined, then INSERT vs. UPDATE is not known.
* @note This should be overridden to actually do the export.
*/
protected onExportCodeSpec(_codeSpec: CodeSpec, _isUpdate: boolean | undefined): void { }
/** Called when a font should be exported.
* @param font The font to export
* @note This should be overridden to actually do the export.
*/
protected onExportFont(_font: FontProps): void { }
/** Called when a model should be exported.
* @param model The model to export
* @param isUpdate If defined, then `true` indicates an UPDATE operation while `false` indicates an INSERT operation. If not defined, then INSERT vs. UPDATE is not known.
* @note This should be overridden to actually do the export.
*/
protected onExportModel(_model: Model, _isUpdate: boolean | undefined): void { }
/** Called when a model should be deleted. */
protected onDeleteModel(_modelId: Id64String): void { }
/** If `true` is returned, then the element will be exported. */
protected shouldExportElement(_element: Element): boolean { return true; }
/** Called when an element should be exported.
* @param element The element to export
* @param isUpdate If defined, then `true` indicates an UPDATE operation while `false` indicates an INSERT operation. If not defined, then INSERT vs. UPDATE is not known.
* @note This should be overridden to actually do the export.
*/
protected onExportElement(_element: Element, _isUpdate: boolean | undefined): void { }
/** Called when an element should be deleted. */
protected onDeleteElement(_elementId: Id64String): void { }
/** If `true` is returned, then the ElementAspect will be exported. */
protected shouldExportElementAspect(_aspect: ElementAspect): boolean { return true; }
/** Called when an ElementUniqueAspect should be exported.
* @param aspect The ElementUniqueAspect to export
* @param isUpdate If defined, then `true` indicates an UPDATE operation while `false` indicates an INSERT operation. If not defined, then INSERT vs. UPDATE is not known.
* @note This should be overridden to actually do the export.
*/
protected onExportElementUniqueAspect(_aspect: ElementUniqueAspect, _isUpdate: boolean | undefined): void { }
/** Called when ElementMultiAspects should be exported.
* @note This should be overridden to actually do the export.
*/
protected onExportElementMultiAspects(_aspects: ElementMultiAspect[]): void { }
/** If `true` is returned, then the relationship will be exported. */
protected shouldExportRelationship(_relationship: Relationship): boolean { return true; }
/** Called when a Relationship should be exported.
* @param relationship The Relationship to export
* @param isUpdate If defined, then `true` indicates an UPDATE operation while `false` indicates an INSERT operation. If not defined, then INSERT vs. UPDATE is not known.
* @note This should be overridden to actually do the export.
*/
protected onExportRelationship(_relationship: Relationship, _isUpdate: boolean | undefined): void { }
/** Called when a relationship should be deleted. */
protected onDeleteRelationship(_relInstanceId: Id64String): void { }
/** Helper method that allows IModelExporter to call protected methods in IModelExportHandler.
* @internal
*/
public get callProtected(): any { return this; }
}
/** Base class for exporting data from an iModel.
* @alpha
*/
export class IModelExporter {
/** The read-only source iModel. */
public readonly sourceDb: IModelDb;
/** Optionally cached entity change information */
private _sourceDbChanges?: EntityChangeOps;
/** The handler called by this IModelExporter. */
private _handler: IModelExportHandler | undefined;
/** The handler called by this IModelExporter. */
protected get handler(): IModelExportHandler {
if (undefined === this._handler) { throw new Error("IModelExportHandler not registered"); }
return this._handler;
}
/** The set of CodeSpecs to exclude from the export. */
private _excludedCodeSpecNames = new Set<string>();
/** The set of specific Elements to exclude from the export. */
private _excludedElementIds = new Set<Id64String>();
/** The set of Categories where Elements in that Category will be excluded from transformation to the target iModel. */
private _excludedElementCategoryIds = new Set<Id64String>();
/** The set of classes of Elements that will be excluded (polymorphically) from transformation to the target iModel. */
private _excludedElementClasses = new Set<typeof Element>();
/** The set of classes of ElementAspects that will be excluded (polymorphically) from transformation to the target iModel. */
private _excludedElementAspectClasses = new Set<typeof ElementAspect>();
/** The set of classes of Relationships that will be excluded (polymorphically) from transformation to the target iModel. */
private _excludedRelationshipClasses = new Set<typeof Relationship>();
/** Construct a new IModelExporter
* @param sourceDb The source IModelDb
* @param options The options that specify how the export should be done.
* @see registerHandler
*/
public constructor(sourceDb: IModelDb, options?: IModelExportOptions) {
this.sourceDb = sourceDb;
if (undefined !== options) { } // WIP
}
/** Register the handler that will be called by IModelExporter. */
public registerHandler(handler: IModelExportHandler): void {
this._handler = handler;
}
/** Add a rule to exclude a CodeSpec */
public excludeCodeSpec(codeSpecName: string): void {
this._excludedCodeSpecNames.add(codeSpecName);
}
/** Add a rule to exclude a specific Element. */
public excludeElement(elementId: Id64String): void {
this._excludedElementIds.add(elementId);
}
/** Add a rule to exclude all Elements of a specified Category. */
public excludeElementCategory(categoryId: Id64String): void {
this._excludedElementCategoryIds.add(categoryId);
}
/** Add a rule to exclude all Elements of a specified class. */
public excludeElementClass(classFullName: string): void {
this._excludedElementClasses.add(this.sourceDb.getJsClass<typeof Element>(classFullName));
}
/** Add a rule to exclude all ElementAspects of a specified class. */
public excludeElementAspectClass(classFullName: string): void {
this._excludedElementAspectClasses.add(this.sourceDb.getJsClass<typeof ElementAspect>(classFullName));
}
/** Add a rule to exclude all Relationships of a specified class. */
public excludeRelationshipClass(classFullName: string): void {
this._excludedRelationshipClasses.add(this.sourceDb.getJsClass<typeof Relationship>(classFullName));
}
/** Export everything from the source iModel. */
public exportAll(): void {
this.exportCodeSpecs();
this.exportFonts();
this.exportModelContainer(IModel.repositoryModelId);
this.exportElement(IModel.rootSubjectId);
this.exportSubModels(IModel.repositoryModelId);
this.exportRelationships(ElementRefersToElements.classFullName);
}
/** Export changes between the specified versions of the source iModel. */
public async exportChanges(requestContext: AuthorizedBackendRequestContext, options: ChangeSummaryExtractOptions): Promise<void> {
if ((undefined === this.sourceDb.briefcase.parentChangeSetId) || ("" === this.sourceDb.briefcase.parentChangeSetId)) {
this.exportAll(); // no changesets, so revert to exportAll
return Promise.resolve();
}
this._sourceDbChanges = await EntityChangeOps.initialize(requestContext, this.sourceDb, options);
this.exportCodeSpecs();
// WIP: handle font changes???
this.exportElement(IModel.rootSubjectId);
this.exportSubModels(IModel.repositoryModelId);
this.exportRelationships(ElementRefersToElements.classFullName);
// handle deletes
for (const elementId of this._sourceDbChanges.elements.deletedIds) {
this.handler.callProtected.onDeleteElement(elementId);
}
// WIP: handle ElementAspects?
for (const modelId of this._sourceDbChanges.models.deletedIds) {
this.handler.callProtected.onDeleteModel(modelId);
}
for (const relInstanceId of this._sourceDbChanges.relationships.deletedIds) {
this.handler.callProtected.onDeleteRelationship(relInstanceId);
}
}
/** Export all CodeSpecs from the source iModel. */
public exportCodeSpecs(): void {
Logger.logTrace(loggerCategory, `exportCodeSpecs()`);
const sql = `SELECT Name FROM BisCore:CodeSpec ORDER BY ECInstanceId`;
this.sourceDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {
while (DbResult.BE_SQLITE_ROW === statement.step()) {
const codeSpecName: string = statement.getValue(0).getString();
this.exportCodeSpecByName(codeSpecName);
}
});
}
/** Export a single CodeSpec from the source iModel. */
public exportCodeSpecByName(codeSpecName: string): void {
const codeSpec: CodeSpec = this.sourceDb.codeSpecs.getByName(codeSpecName);
let isUpdate: boolean | undefined;
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (this._sourceDbChanges.codeSpecs.insertedIds.has(codeSpec.id)) {
isUpdate = false;
} else if (this._sourceDbChanges.codeSpecs.updatedIds.has(codeSpec.id)) {
isUpdate = true;
} else {
return; // not in changeSet, don't export
}
}
// passed changeSet test, now apply standard exclusion rules
if (this._excludedCodeSpecNames.has(codeSpec.name)) {
Logger.logInfo(loggerCategory, `Excluding CodeSpec: ${codeSpec.name}`);
return;
}
// CodeSpec has passed standard exclusion rules, now give handler a chance to accept/reject export
if (this.handler.callProtected.shouldExportCodeSpec(codeSpec)) {
Logger.logTrace(loggerCategory, `exportCodeSpec(${codeSpecName})` + isUpdate ? " UPDATE" : "");
this.handler.callProtected.onExportCodeSpec(codeSpec, isUpdate);
}
}
/** Export a single CodeSpec from the source iModel. */
public exportCodeSpecById(codeSpecId: Id64String): void {
const codeSpec: CodeSpec = this.sourceDb.codeSpecs.getById(codeSpecId);
this.exportCodeSpecByName(codeSpec.name);
}
/** Export all fonts from the source iModel. */
public exportFonts(): void {
Logger.logTrace(loggerCategory, `exportFonts()`);
for (const font of this.sourceDb.fontMap.fonts.values()) {
this.handler.callProtected.onExportFont(font);
}
}
/** Export a single font from the source iModel. */
public exportFontByName(fontName: string): void {
Logger.logTrace(loggerCategory, `exportFontByName(${fontName})`);
const font: FontProps | undefined = this.sourceDb.fontMap.getFont(fontName);
if (undefined !== font) {
this.handler.callProtected.onExportFont(font);
}
}
/** Export a single font from the source iModel. */
public exportFontByNumber(fontNumber: number): void {
Logger.logTrace(loggerCategory, `exportFontById(${fontNumber})`);
const font: FontProps | undefined = this.sourceDb.fontMap.getFont(fontNumber);
if (undefined !== font) {
this.handler.callProtected.onExportFont(font);
}
}
/** Export the model container, contents, and sub-models from the source iModel. */
public exportModel(modeledElementId: Id64String): void {
const modeledElement: Element = this.sourceDb.elements.getElement({ id: modeledElementId, wantGeometry: true });
Logger.logTrace(loggerCategory, `exportModel()`);
if (this.shouldExportElement(modeledElement)) {
this.exportModelContainer(modeledElementId);
this.exportModelContents(modeledElementId);
this.exportSubModels(modeledElementId);
}
}
/** Export the model (the container only) from the source iModel. */
private exportModelContainer(modeledElementId: Id64String): void {
let isUpdate: boolean | undefined;
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (this._sourceDbChanges.models.insertedIds.has(modeledElementId)) {
isUpdate = false;
} else if (this._sourceDbChanges.models.updatedIds.has(modeledElementId)) {
isUpdate = true;
} else {
return; // not in changeSet, don't export
}
}
const model: Model = this.sourceDb.models.getModel(modeledElementId);
this.handler.callProtected.onExportModel(model, isUpdate);
}
/** Export the model contents. */
public exportModelContents(modelId: Id64String, elementClassFullName: string = Element.classFullName): void {
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (!this._sourceDbChanges.models.insertedIds.has(modelId) && !this._sourceDbChanges.models.updatedIds.has(modelId)) {
return; // this optimization assumes that the Model changes (LastMod) any time an Element in the Model changes
}
}
Logger.logTrace(loggerCategory, `exportModelContents()`);
const sql = `SELECT ECInstanceId FROM ${elementClassFullName} WHERE Parent.Id IS NULL AND Model.Id=:modelId ORDER BY ECInstanceId`;
this.sourceDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {
statement.bindId("modelId", modelId);
while (DbResult.BE_SQLITE_ROW === statement.step()) {
this.exportElement(statement.getValue(0).getId());
}
});
}
/** Export the sub-models directly below the specified model. */
public exportSubModels(parentModelId: Id64String): void {
const definitionModelIds: Id64String[] = [];
const otherModelIds: Id64String[] = [];
const sql = `SELECT ECInstanceId FROM ${Model.classFullName} WHERE ParentModel.Id=:parentModelId ORDER BY ECInstanceId`;
this.sourceDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {
statement.bindId("parentModelId", parentModelId);
while (DbResult.BE_SQLITE_ROW === statement.step()) {
const modelId: Id64String = statement.getValue(0).getId();
const model: Model = this.sourceDb.models.getModel(modelId);
if (model instanceof DefinitionModel) {
definitionModelIds.push(modelId);
} else {
otherModelIds.push(modelId);
}
}
});
// export DefinitionModels before other types of Models
definitionModelIds.forEach((modelId: Id64String) => this.exportModel(modelId));
otherModelIds.forEach((modelId: Id64String) => this.exportModel(modelId));
}
/** Returns true if the specified element should be exported. */
private shouldExportElement(element: Element): boolean {
if (this._excludedElementIds.has(element.id)) {
Logger.logInfo(loggerCategory, `Excluded element by Id`);
return false;
}
if (element instanceof GeometricElement) {
if (this._excludedElementCategoryIds.has(element.category)) {
Logger.logInfo(loggerCategory, `Excluded element by Category`);
return false;
}
}
for (const excludedElementClass of this._excludedElementClasses) {
if (element instanceof excludedElementClass) {
Logger.logInfo(loggerCategory, `Excluded element by class: ${excludedElementClass.classFullName}`);
return false;
}
}
// element has passed standard exclusion rules, now give handler a chance to accept/reject
return this.handler.callProtected.shouldExportElement(element);
}
/** Export the specified element and its child elements (if applicable). */
public exportElement(elementId: Id64String): void {
let isUpdate: boolean | undefined;
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (this._sourceDbChanges.elements.insertedIds.has(elementId)) {
isUpdate = false;
} else if (this._sourceDbChanges.elements.updatedIds.has(elementId)) {
isUpdate = true;
} else {
// NOTE: This optimization assumes that the Element will change (LastMod) if an owned ElementAspect changes
// NOTE: However, child elements may have changed without the parent changing
this.exportChildElements(elementId);
return;
}
}
const element: Element = this.sourceDb.elements.getElement({ id: elementId, wantGeometry: true });
Logger.logTrace(loggerCategory, `exportElement()`);
if (this.shouldExportElement(element)) {
this.handler.callProtected.onExportElement(element, isUpdate);
this.exportElementAspects(elementId);
this.exportChildElements(elementId);
}
}
/** Export the child elements of the specified element from the source iModel. */
public exportChildElements(elementId: Id64String): void {
const childElementIds: Id64String[] = this.sourceDb.elements.queryChildren(elementId);
if (childElementIds.length > 0) {
Logger.logTrace(loggerCategory, `exportChildElements(${elementId})`);
for (const childElementId of childElementIds) {
this.exportElement(childElementId);
}
}
}
/** Returns true if the specified ElementAspect should be excluded from the export. */
private shouldExportElementAspect(aspect: ElementAspect): boolean {
for (const excludedElementAspectClass of this._excludedElementAspectClasses) {
if (aspect instanceof excludedElementAspectClass) {
Logger.logInfo(loggerCategory, `Excluded ElementAspect by class`);
return false;
}
}
// ElementAspect has passed standard exclusion rules, now give handler a chance to accept/reject
return this.handler.callProtected.shouldExportElementAspect(aspect);
}
/** Export ElementAspects from the specified element from the source iModel. */
private exportElementAspects(elementId: Id64String): void {
const aspects: ElementUniqueAspect[] = this.sourceDb.elements.getAspects(elementId);
if (aspects.length > 0) {
// ElementUniqueAspects
const uniqueAspects: ElementUniqueAspect[] = aspects.filter((aspect) => {
return aspect instanceof ElementUniqueAspect && this.shouldExportElementAspect(aspect);
});
if (uniqueAspects.length > 0) {
uniqueAspects.forEach((uniqueAspect: ElementUniqueAspect) => {
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (this._sourceDbChanges.elementAspects.insertedIds.has(uniqueAspect.id)) {
this.handler.callProtected.onExportElementUniqueAspect(uniqueAspect, false);
} else if (this._sourceDbChanges.elementAspects.updatedIds.has(uniqueAspect.id)) {
this.handler.callProtected.onExportElementUniqueAspect(uniqueAspect, true);
} else {
// not in changeSet, don't export
}
} else {
this.handler.callProtected.onExportElementUniqueAspect(uniqueAspect, undefined);
}
});
}
// ElementMultiAspects
const multiAspects: ElementMultiAspect[] = aspects.filter((aspect) => {
return aspect instanceof ElementMultiAspect && this.shouldExportElementAspect(aspect);
});
if (multiAspects.length > 0) {
this.handler.callProtected.onExportElementMultiAspects(multiAspects);
}
}
}
/** Exports all relationships that subclass from the specified base class. */
public exportRelationships(baseRelClassFullName: string): void {
Logger.logTrace(loggerCategory, `exportRelationships(${baseRelClassFullName})`);
const sql = `SELECT ECInstanceId FROM ${baseRelClassFullName}`;
this.sourceDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {
while (DbResult.BE_SQLITE_ROW === statement.step()) {
const relInstanceId: Id64String = statement.getValue(0).getId();
const relProps: RelationshipProps = this.sourceDb.relationships.getInstanceProps(baseRelClassFullName, relInstanceId);
this.exportRelationship(relProps.classFullName, relInstanceId); // must call exportRelationship using the actual classFullName, not baseRelClassFullName
}
});
}
/** Export a relationship from the source iModel. */
private exportRelationship(relClassFullName: string, relInstanceId: Id64String): void {
let isUpdate: boolean | undefined;
if (undefined !== this._sourceDbChanges) { // is changeSet information available?
if (this._sourceDbChanges.relationships.insertedIds.has(relInstanceId)) {
isUpdate = false;
} else if (this._sourceDbChanges.relationships.updatedIds.has(relInstanceId)) {
isUpdate = true;
} else {
return; // not in changeSet, don't export
}
}
// passed changeSet test, now apply standard exclusion rules
Logger.logTrace(loggerCategory, `exportRelationship(${relClassFullName}, ${relInstanceId})`);
const relationship: Relationship = this.sourceDb.relationships.getInstance(relClassFullName, relInstanceId);
for (const excludedRelationshipClass of this._excludedRelationshipClasses) {
if (relationship instanceof excludedRelationshipClass) {
Logger.logInfo(loggerCategory, `Excluded relationship by class: ${excludedRelationshipClass.classFullName}`);
return;
}
}
// relationship has passed standard exclusion rules, now give handler a chance to accept/reject export
if (this.handler.callProtected.shouldExportRelationship(relationship)) {
this.handler.callProtected.onExportRelationship(relationship, isUpdate);
}
}
}
class ChangeOpTracker {
public insertedIds: Id64Set = new Set<Id64String>();
public updatedIds: Id64Set = new Set<Id64String>();
public deletedIds: Id64Set = new Set<Id64String>();
public addChange(changeOpCode: ChangeOpCode, id: Id64String): void {
switch (changeOpCode) {
case ChangeOpCode.Insert: this.insertedIds.add(id); break;
case ChangeOpCode.Update: this.updatedIds.add(id); break;
case ChangeOpCode.Delete: this.deletedIds.add(id); break;
}
}
}
class EntityChangeOps {
public codeSpecs: ChangeOpTracker = new ChangeOpTracker();
public elements: ChangeOpTracker = new ChangeOpTracker();
public elementAspects: ChangeOpTracker = new ChangeOpTracker();
public models: ChangeOpTracker = new ChangeOpTracker();
public relationships: ChangeOpTracker = new ChangeOpTracker();
private constructor() { }
public static async initialize(requestContext: AuthorizedBackendRequestContext, iModelDb: IModelDb, options: ChangeSummaryExtractOptions): Promise<EntityChangeOps> {
const entityChanges = new EntityChangeOps();
const changeSummaryIds: Id64String[] = await ChangeSummaryManager.extractChangeSummaries(requestContext, iModelDb, options);
ChangeSummaryManager.attachChangeCache(iModelDb);
changeSummaryIds.forEach((changeSummaryId: Id64String) => {
const changeSummary: ChangeSummary = ChangeSummaryManager.queryChangeSummary(iModelDb, changeSummaryId);
iModelDb.withPreparedStatement("SELECT ECInstanceId FROM ecchange.change.InstanceChange WHERE Summary.Id=?", (statement) => {
statement.bindId(1, changeSummary.id);
while (statement.step() === DbResult.BE_SQLITE_ROW) {
const instanceId: Id64String = statement.getValue(0).getId();
const instanceChange: InstanceChange = ChangeSummaryManager.queryInstanceChange(iModelDb, instanceId);
const entityClassFullName: string = EntityChangeOps._toClassFullName(instanceChange.changedInstance.className);
try {
const entityType: typeof Entity = iModelDb.getJsClass<typeof Entity>(entityClassFullName);
if (entityType.prototype instanceof Element) {
// const propertyNames: string[] = ChangeSummaryManager.getChangedPropertyValueNames(iModelDb, instanceChange.id);
entityChanges.elements.addChange(instanceChange.opCode, instanceChange.changedInstance.id);
} else if (entityType.prototype instanceof ElementAspect) {
entityChanges.elementAspects.addChange(instanceChange.opCode, instanceChange.changedInstance.id);
} else if (entityType.prototype instanceof Model) {
entityChanges.models.addChange(instanceChange.opCode, instanceChange.changedInstance.id);
} else if (entityType.prototype instanceof Relationship) {
entityChanges.relationships.addChange(instanceChange.opCode, instanceChange.changedInstance.id);
}
} catch (error) {
if ("BisCore:CodeSpec" === entityClassFullName) {
// In TypeScript, CodeSpec is not a subclass of Entity (should it be?), so must be handled separately.
entityChanges.codeSpecs.addChange(instanceChange.opCode, instanceChange.changedInstance.id);
} else {
// Changes to *navigation* relationship are also tracked (should they be?), but can be ignored
// console.log(`Ignoring ${entityClassFullName}`); // tslint:disable-line
}
}
}
});
});
return entityChanges;
}
/** Converts string from ChangedInstance format to classFullName format. For example: "[BisCore].[PhysicalElement]" --> "BisCore:PhysicalElement" */
private static _toClassFullName(changedInstanceClassName: string): string {
return changedInstanceClassName.replace(/\[|\]/g, "").replace(".", ":");
}
}