@itwin/imodel-transformer 0.1.13 → 0.1.14-fedguidopt.2

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.
@@ -22,6 +22,7 @@ const PendingReferenceMap_1 = require("./PendingReferenceMap");
22
22
  const EntityMap_1 = require("./EntityMap");
23
23
  const IModelCloneContext_1 = require("./IModelCloneContext");
24
24
  const EntityUnifier_1 = require("./EntityUnifier");
25
+ const Algo_1 = require("./Algo");
25
26
  const loggerCategory = TransformerLoggerCategory_1.TransformerLoggerCategory.IModelTransformer;
26
27
  const nullLastProvenanceEntityInfo = {
27
28
  entityId: core_bentley_1.Id64.invalid,
@@ -94,6 +95,12 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
94
95
  get targetScopeElementId() {
95
96
  return this._options.targetScopeElementId;
96
97
  }
98
+ get _isReverseSynchronization() {
99
+ return this._isSynchronization && this._options.isReverseSynchronization;
100
+ }
101
+ get _isForwardSynchronization() {
102
+ return this._isSynchronization && !this._options.isReverseSynchronization;
103
+ }
97
104
  /** The element classes that are considered to define provenance in the iModel */
98
105
  static get provenanceElementClasses() {
99
106
  return [core_backend_1.FolderLink, core_backend_1.SynchronizationConfigLink, core_backend_1.ExternalSource, core_backend_1.ExternalSourceAttachment];
@@ -112,14 +119,42 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
112
119
  /** map of (unprocessed element, referencing processed element) pairs to the partially committed element that needs the reference resolved
113
120
  * and have some helper methods below for now */
114
121
  this._pendingReferences = new PendingReferenceMap_1.PendingReferenceMap();
122
+ /** a set of elements for which source provenance will be explicitly tracked by ExternalSourceAspects */
123
+ this._elementsWithExplicitlyTrackedProvenance = new Set();
115
124
  /** map of partially committed entities to their partial commit progress */
116
125
  this._partiallyCommittedEntities = new EntityMap_1.EntityMap();
126
+ this._isSynchronization = false;
127
+ this._changesetRanges = undefined;
128
+ // FIXME: add test using this
129
+ /**
130
+ * Previously the transformer would insert provenance always pointing to the "target" relationship.
131
+ * It should (and now by default does) instead insert provenance pointing to the provenanceSource
132
+ * SEE: https://github.com/iTwin/imodel-transformer/issues/54
133
+ * This exists only to facilitate testing that the transformer can handle the older, flawed method
134
+ */
135
+ this._forceOldRelationshipProvenanceMethod = false;
136
+ /** NOTE: the json properties must be converted to string before insertion */
137
+ this._targetScopeProvenanceProps = undefined;
138
+ /**
139
+ * Index of the changeset that the transformer was at when the transformation begins (was constructed).
140
+ * Used to determine at the end which changesets were part of a synchronization.
141
+ */
142
+ this._startingTargetChangesetIndex = undefined;
143
+ this._cachedSynchronizationVersion = undefined;
144
+ this._targetClassNameToClassIdCache = new Map();
145
+ // if undefined, it can be initialized by calling [[this._cacheSourceChanges]]
146
+ this._hasElementChangedCache = undefined;
147
+ this._deletedSourceRelationshipData = undefined;
117
148
  this._yieldManager = new core_bentley_1.YieldManager();
118
149
  /** The directory where schemas will be exported, a random temporary directory */
119
150
  this._schemaExportDir = path.join(core_backend_1.KnownLocations.tmpdir, core_bentley_1.Guid.createValue());
120
151
  this._longNamedSchemasMap = new Map();
121
152
  /** state to prevent reinitialization, @see [[initialize]] */
122
153
  this._initialized = false;
154
+ /** length === 0 when _changeDataState = "no-change", length > 0 means "has-changes", otherwise undefined */
155
+ this._changeSummaryIds = undefined;
156
+ this._sourceChangeDataState = "uninited";
157
+ /** previous provenance, either a federation guid, a `${sourceFedGuid}/${targetFedGuid}` pair, or required aspect props */
123
158
  this._lastProvenanceEntityInfo = nullLastProvenanceEntityInfo;
124
159
  // initialize IModelTransformOptions
125
160
  this._options = {
@@ -167,6 +202,7 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
167
202
  this.targetDb = this.importer.targetDb;
168
203
  // create the IModelCloneContext, it must be initialized later
169
204
  this.context = new IModelCloneContext_1.IModelCloneContext(this.sourceDb, this.targetDb);
205
+ this._startingTargetChangesetIndex = this.targetDb?.changeset.index;
170
206
  }
171
207
  /** Dispose any native resources associated with this IModelTransformer. */
172
208
  dispose() {
@@ -195,8 +231,14 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
195
231
  get provenanceDb() {
196
232
  return this._options.isReverseSynchronization ? this.sourceDb : this.targetDb;
197
233
  }
198
- /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */
234
+ /** Return the IModelDb where IModelTransformer will NOT store its provenance.
235
+ * @note This will be [[sourceDb]] except when it is a reverse synchronization. In that case it be [[targetDb]].
236
+ */
237
+ get provenanceSourceDb() {
238
+ return this._options.isReverseSynchronization ? this.targetDb : this.sourceDb;
239
+ }
199
240
  initElementProvenance(sourceElementId, targetElementId) {
241
+ // FIXME: deprecate isReverseSync option and instead detect from targetScopeElement provenance
200
242
  const elementId = this._options.isReverseSynchronization ? sourceElementId : targetElementId;
201
243
  const aspectIdentifier = this._options.isReverseSynchronization ? targetElementId : sourceElementId;
202
244
  const aspectProps = {
@@ -215,32 +257,89 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
215
257
  * The ECInstanceId of the relationship in the target iModel will be stored in the JsonProperties of the ExternalSourceAspect.
216
258
  */
217
259
  initRelationshipProvenance(sourceRelationship, targetRelInstanceId) {
218
- const targetRelationship = this.targetDb.relationships.getInstance(core_backend_1.ElementRefersToElements.classFullName, targetRelInstanceId);
219
- const elementId = this._options.isReverseSynchronization ? sourceRelationship.sourceId : targetRelationship.sourceId;
260
+ const elementId = this._options.isReverseSynchronization
261
+ ? sourceRelationship.sourceId
262
+ : this.targetDb.withPreparedStatement("SELECT SourceECInstanceId FROM Bis.ElementRefersToElements WHERE ECInstanceId=?", (stmt) => {
263
+ stmt.bindId(1, targetRelInstanceId);
264
+ nodeAssert(stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW);
265
+ return stmt.getValue(0).getId();
266
+ });
220
267
  const aspectIdentifier = this._options.isReverseSynchronization ? targetRelInstanceId : sourceRelationship.id;
268
+ const jsonProperties = this._forceOldRelationshipProvenanceMethod
269
+ ? { targetRelInstanceId }
270
+ : { provenanceRelInstanceId: this._isReverseSynchronization
271
+ ? sourceRelationship.id
272
+ : targetRelInstanceId,
273
+ };
221
274
  const aspectProps = {
222
275
  classFullName: core_backend_1.ExternalSourceAspect.classFullName,
223
276
  element: { id: elementId, relClassName: core_backend_1.ElementOwnsExternalSourceAspects.classFullName },
224
277
  scope: { id: this.targetScopeElementId },
225
278
  identifier: aspectIdentifier,
226
279
  kind: core_backend_1.ExternalSourceAspect.Kind.Relationship,
227
- jsonProperties: JSON.stringify({ targetRelInstanceId }),
280
+ jsonProperties: JSON.stringify(jsonProperties),
228
281
  };
229
- aspectProps.id = this.queryExternalSourceAspectId(aspectProps);
230
282
  return aspectProps;
231
283
  }
232
- validateScopeProvenance() {
284
+ /** the changeset in the scoping element's source version found for this transformation
285
+ * @note: the version depends on whether this is a reverse synchronization or not, as
286
+ * it is stored separately for both synchronization directions
287
+ * @note: empty string and -1 for changeset and index if it has never been transformed
288
+ */
289
+ get _synchronizationVersion() {
290
+ if (!this._cachedSynchronizationVersion) {
291
+ nodeAssert(this._targetScopeProvenanceProps, "_targetScopeProvenanceProps was not set yet");
292
+ const version = this._options.isReverseSynchronization
293
+ ? this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion
294
+ : this._targetScopeProvenanceProps.version;
295
+ nodeAssert(version !== undefined, "no version contained in target scope");
296
+ const [id, index] = version === ""
297
+ ? ["", -1]
298
+ : version.split(";");
299
+ this._cachedSynchronizationVersion = { index: Number(index), id };
300
+ nodeAssert(!Number.isNaN(this._cachedSynchronizationVersion.index), "bad parse: invalid index in version");
301
+ }
302
+ return this._cachedSynchronizationVersion;
303
+ }
304
+ /**
305
+ * Make sure there are no conflicting other scope-type external source aspects on the *target scope element*,
306
+ * If there are none at all, insert one, then this must be a first synchronization.
307
+ * @returns the last synced version (changesetId) on the target scope's external source aspect,
308
+ * if this was a [BriefcaseDb]($backend)
309
+ */
310
+ initScopeProvenance() {
233
311
  const aspectProps = {
312
+ id: undefined,
313
+ version: undefined,
234
314
  classFullName: core_backend_1.ExternalSourceAspect.classFullName,
235
315
  element: { id: this.targetScopeElementId, relClassName: core_backend_1.ElementOwnsExternalSourceAspects.classFullName },
236
316
  scope: { id: core_common_1.IModel.rootSubjectId },
237
- identifier: this._options.isReverseSynchronization ? this.targetDb.iModelId : this.sourceDb.iModelId,
317
+ identifier: this.provenanceSourceDb.iModelId,
238
318
  kind: core_backend_1.ExternalSourceAspect.Kind.Scope,
319
+ jsonProperties: undefined,
239
320
  };
240
- aspectProps.id = this.queryExternalSourceAspectId(aspectProps); // this query includes "identifier"
321
+ // FIXME: handle older transformed iModels which do NOT have the version
322
+ // or reverseSyncVersion set correctly
323
+ const externalSource = this.queryScopeExternalSource(aspectProps, { getJsonProperties: true }); // this query includes "identifier"
324
+ aspectProps.id = externalSource.aspectId;
325
+ aspectProps.version = externalSource.version;
326
+ aspectProps.jsonProperties = externalSource.jsonProperties ? JSON.parse(externalSource.jsonProperties) : {};
241
327
  if (undefined === aspectProps.id) {
328
+ aspectProps.version = ""; // empty since never before transformed. Will be updated in [[finalizeTransformation]]
329
+ aspectProps.jsonProperties = {
330
+ pendingReverseSyncChangesetIndices: [],
331
+ pendingSyncChangesetIndices: [],
332
+ reverseSyncVersion: "", // empty since never before transformed. Will be updated in first reverse sync
333
+ };
242
334
  // this query does not include "identifier" to find possible conflicts
243
- const sql = `SELECT ECInstanceId FROM ${core_backend_1.ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind LIMIT 1`;
335
+ const sql = `
336
+ SELECT ECInstanceId
337
+ FROM ${core_backend_1.ExternalSourceAspect.classFullName}
338
+ WHERE Element.Id=:elementId
339
+ AND Scope.Id=:scopeId
340
+ AND Kind=:kind
341
+ LIMIT 1
342
+ `;
244
343
  const hasConflictingScope = this.provenanceDb.withPreparedStatement(sql, (statement) => {
245
344
  statement.bindId("elementId", aspectProps.element.id);
246
345
  statement.bindId("scopeId", aspectProps.scope.id); // this scope.id can never be invalid, we create it above
@@ -251,41 +350,128 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
251
350
  throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, "Provenance scope conflict");
252
351
  }
253
352
  if (!this._options.noProvenance) {
254
- this.provenanceDb.elements.insertAspect(aspectProps);
353
+ this.provenanceDb.elements.insertAspect({
354
+ ...aspectProps,
355
+ jsonProperties: JSON.stringify(aspectProps.jsonProperties),
356
+ });
255
357
  }
256
358
  }
359
+ this._targetScopeProvenanceProps = aspectProps;
257
360
  }
258
- queryExternalSourceAspectId(aspectProps) {
259
- const sql = `SELECT ECInstanceId FROM ${core_backend_1.ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind AND Identifier=:identifier LIMIT 1`;
361
+ /**
362
+ * @returns the id and version of an aspect with the given element, scope, kind, and identifier
363
+ * May also return a reverseSyncVersion from json properties if requested
364
+ */
365
+ queryScopeExternalSource(aspectProps, { getJsonProperties = false } = {}) {
366
+ const sql = `
367
+ SELECT ECInstanceId, Version
368
+ ${getJsonProperties ? ", JsonProperties" : ""}
369
+ FROM ${core_backend_1.ExternalSourceAspect.classFullName}
370
+ WHERE Element.Id=:elementId
371
+ AND Scope.Id=:scopeId
372
+ AND Kind=:kind
373
+ AND Identifier=:identifier
374
+ LIMIT 1
375
+ `;
376
+ const emptyResult = { aspectId: undefined, version: undefined, jsonProperties: undefined };
260
377
  return this.provenanceDb.withPreparedStatement(sql, (statement) => {
261
378
  statement.bindId("elementId", aspectProps.element.id);
262
379
  if (aspectProps.scope === undefined)
263
- return undefined; // return undefined instead of binding an invalid id
380
+ return emptyResult; // return undefined instead of binding an invalid id
264
381
  statement.bindId("scopeId", aspectProps.scope.id);
265
382
  statement.bindString("kind", aspectProps.kind);
266
383
  statement.bindString("identifier", aspectProps.identifier);
267
- return (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getId() : undefined;
384
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== statement.step())
385
+ return emptyResult;
386
+ const aspectId = statement.getValue(0).getId();
387
+ const version = statement.getValue(1).getString();
388
+ const jsonProperties = getJsonProperties ? statement.getValue(2).getString() : undefined;
389
+ return { aspectId, version, jsonProperties };
268
390
  });
269
391
  }
270
- /** Iterate all matching ExternalSourceAspects in the provenance iModel (target unless reverse sync) and call a function for each one. */
392
+ /**
393
+ * Iterate all matching ExternalSourceAspects in the provenance iModel (target unless reverse sync) and call a function for each one.
394
+ * @note provenance is done by federation guids where possible
395
+ * @note this may execute on each element more than once! Only use in cases where that is handled
396
+ */
271
397
  forEachTrackedElement(fn) {
398
+ // FIXME: do we need an alternative for in-iModel transforms?
399
+ if (!this.context.isBetweenIModels)
400
+ return;
272
401
  if (!this.provenanceDb.containsClass(core_backend_1.ExternalSourceAspect.classFullName)) {
273
402
  throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadSchema, "The BisCore schema version of the target database is too old");
274
403
  }
275
- const sql = `SELECT Identifier,Element.Id FROM ${core_backend_1.ExternalSourceAspect.classFullName} WHERE Scope.Id=:scopeId AND Kind=:kind`;
276
- this.provenanceDb.withPreparedStatement(sql, (statement) => {
277
- statement.bindId("scopeId", this.targetScopeElementId);
278
- statement.bindString("kind", core_backend_1.ExternalSourceAspect.Kind.Element);
279
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
280
- const aspectIdentifier = statement.getValue(0).getString(); // ExternalSourceAspect.Identifier is of type string
281
- const elementId = statement.getValue(1).getId();
282
- if (this._options.isReverseSynchronization) {
283
- fn(elementId, aspectIdentifier); // provenance coming from the sourceDb
404
+ const runFnInProvDirection = (sourceId, targetId) => this._options.isReverseSynchronization ? fn(sourceId, targetId) : fn(targetId, sourceId);
405
+ // query for provenanceDb
406
+ const provenanceContainerQuery = `
407
+ SELECT e.ECInstanceId, FederationGuid
408
+ FROM bis.Element e
409
+ WHERE e.ECInstanceId NOT IN (0x1, 0xe, 0x10) -- special static elements
410
+ ORDER BY FederationGuid
411
+ `;
412
+ // query for nonProvenanceDb, the source to which the provenance is referring
413
+ const provenanceSourceQuery = `
414
+ SELECT e.ECInstanceId, FederationGuid
415
+ FROM bis.Element e
416
+ WHERE e.ECInstanceId NOT IN (0x1, 0xe, 0x10) -- special static elements
417
+ ORDER BY FederationGuid
418
+ `;
419
+ // iterate through sorted list of fed guids from both dbs to get the intersection
420
+ // NOTE: if we exposed the native attach database support,
421
+ // we could get the intersection of fed guids in one query, not sure if it would be faster
422
+ // OR we could do a raw sqlite query...
423
+ this.provenanceSourceDb.withStatement(provenanceSourceQuery, (sourceStmt) => this.provenanceDb.withStatement(provenanceContainerQuery, (containerStmt) => {
424
+ if (sourceStmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
425
+ return;
426
+ let sourceRow = sourceStmt.getRow();
427
+ if (containerStmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
428
+ return;
429
+ let containerRow = containerStmt.getRow();
430
+ // NOTE: these comparisons rely upon the lowercase of the guid,
431
+ // and the fact that '0' < '9' < a' < 'f' in ascii/utf8
432
+ while (true) {
433
+ const currSourceRow = sourceRow, currContainerRow = containerRow;
434
+ if (currSourceRow.federationGuid !== undefined
435
+ && currContainerRow.federationGuid !== undefined
436
+ && currSourceRow.federationGuid === currContainerRow.federationGuid) {
437
+ // not this is already in provenance direction, no need to use runFnInProvDirection
438
+ fn(sourceRow.id, containerRow.id);
284
439
  }
285
- else {
286
- fn(aspectIdentifier, elementId); // provenance coming from the targetDb
440
+ if (currContainerRow.federationGuid === undefined
441
+ || (currSourceRow.federationGuid !== undefined
442
+ && currSourceRow.federationGuid >= currContainerRow.federationGuid)) {
443
+ if (containerStmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
444
+ return;
445
+ containerRow = containerStmt.getRow();
446
+ }
447
+ if (currSourceRow.federationGuid === undefined
448
+ || (currContainerRow.federationGuid !== undefined
449
+ && currSourceRow.federationGuid <= currContainerRow.federationGuid)) {
450
+ if (sourceStmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
451
+ return;
452
+ sourceRow = sourceStmt.getRow();
287
453
  }
288
454
  }
455
+ }));
456
+ // query for provenanceDb
457
+ const provenanceAspectsQuery = `
458
+ SELECT esa.Identifier, Element.Id
459
+ FROM bis.ExternalSourceAspect esa
460
+ WHERE Scope.Id=:scopeId
461
+ AND Kind=:kind
462
+ `;
463
+ // Technically this will a second time call the function (as documented) on
464
+ // victims of the old provenance method that have both fedguids and an inserted aspect.
465
+ // But this is a private function with one known caller where that doesn't matter
466
+ this.provenanceDb.withPreparedStatement(provenanceAspectsQuery, (stmt) => {
467
+ stmt.bindId("scopeId", this.targetScopeElementId);
468
+ stmt.bindString("kind", core_backend_1.ExternalSourceAspect.Kind.Element);
469
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
470
+ // ExternalSourceAspect.Identifier is of type string
471
+ const aspectIdentifier = stmt.getValue(0).getString();
472
+ const elementId = stmt.getValue(1).getId();
473
+ runFnInProvDirection(elementId, aspectIdentifier);
474
+ }
289
475
  });
290
476
  }
291
477
  /** Initialize the source to target Element mapping from ExternalSourceAspects in the target iModel.
@@ -299,99 +485,326 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
299
485
  this.context.remapElement(sourceElementId, targetElementId);
300
486
  });
301
487
  if (args)
302
- return this.remapDeletedSourceElements(args);
488
+ return this.remapDeletedSourceEntities();
303
489
  }
304
- /** When processing deleted elements in a reverse synchronization, the [[provenanceDb]] (usually a branch iModel) has already
305
- * deleted the [ExternalSourceAspect]($backend)s that tell us which elements in the reverse synchronization target (usually
306
- * a master iModel) should be deleted. We must use the changesets to get the values of those before they were deleted.
490
+ /**
491
+ * Scan changesets for deleted entities, if in a reverse synchronization, provenance has
492
+ * already been deleted, so we must scan for that as well.
307
493
  */
308
- async remapDeletedSourceElements(args) {
494
+ async remapDeletedSourceEntities() {
309
495
  // we need a connected iModel with changes to remap elements with deletions
310
- if (this.sourceDb.iTwinId === undefined)
496
+ const notConnectedModel = this.sourceDb.iTwinId === undefined;
497
+ const noChanges = this._synchronizationVersion.index === this.sourceDb.changeset.index;
498
+ if (notConnectedModel || noChanges)
311
499
  return;
312
- try {
313
- const startChangesetId = args.startChangesetId ?? this.sourceDb.changeset.id;
314
- const endChangesetId = this.sourceDb.changeset.id;
315
- const [firstChangesetIndex, endChangesetIndex] = await Promise.all([startChangesetId, endChangesetId]
316
- .map(async (id) => core_backend_1.IModelHost.hubAccess
317
- .queryChangeset({
318
- iModelId: this.sourceDb.iModelId,
319
- changeset: { id },
320
- accessToken: args.accessToken,
321
- })
322
- .then((changeset) => changeset.index)));
323
- const changesetIds = await core_backend_1.ChangeSummaryManager.createChangeSummaries({
324
- accessToken: args.accessToken,
325
- iModelId: this.sourceDb.iModelId,
326
- iTwinId: this.sourceDb.iTwinId,
327
- range: { first: firstChangesetIndex, end: endChangesetIndex },
328
- });
329
- core_backend_1.ChangeSummaryManager.attachChangeCache(this.sourceDb);
330
- for (const changesetId of changesetIds) {
331
- this.sourceDb.withPreparedStatement(`
332
- SELECT esac.Element.Id, esac.Identifier
333
- FROM ecchange.change.InstanceChange ic
334
- JOIN BisCore.ExternalSourceAspect.Changes(:changesetId, 'BeforeDelete') esac
335
- ON ic.ChangedInstance.Id=esac.ECInstanceId
336
- WHERE ic.OpCode=:opcode
337
- AND ic.Summary.Id=:changesetId
338
- AND esac.Scope.Id=:targetScopeElementId
339
- -- not yet documented ecsql feature to check class id
340
- AND ic.ChangedInstance.ClassId IS (ONLY BisCore.ExternalSourceAspect)
341
- `, (stmt) => {
342
- stmt.bindInteger("opcode", core_common_1.ChangeOpCode.Delete);
343
- stmt.bindInteger("changesetId", changesetId);
344
- stmt.bindInteger("targetScopeElementId", this.targetScopeElementId);
345
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
346
- const targetId = stmt.getValue(0).getId();
347
- const sourceId = stmt.getValue(1).getString(); // BisCore.ExternalSourceAspect.Identifier stores a hex Id64String
348
- // TODO: maybe delete and don't just remap
349
- this.context.remapElement(targetId, sourceId);
500
+ this._deletedSourceRelationshipData = new Map();
501
+ nodeAssert(this._changeSummaryIds, "change summaries should be initialized before we get here");
502
+ nodeAssert(this._changeSummaryIds.length > 0, "change summaries should have at least one");
503
+ // optimization: if we have provenance, use it to avoid more querying later
504
+ // eventually when itwin.js supports attaching a second iModelDb in JS,
505
+ // this won't have to be a conditional part of the query, and we can always have it by attaching
506
+ const queryCanAccessProvenance = this.sourceDb === this.provenanceDb;
507
+ const deletedEntitySql = `
508
+ SELECT
509
+ 1 AS IsElemNotRel,
510
+ ic.ChangedInstance.Id AS InstanceId,
511
+ NULL AS InstId2, -- need these columns for relationship ends in the unioned query
512
+ NULL AS InstId3,
513
+ ec.FederationGuid AS FedGuid,
514
+ NULL AS FedGuid2,
515
+ ic.ChangedInstance.ClassId AS ClassId
516
+ ${queryCanAccessProvenance ? `
517
+ , coalesce(esa.Identifier, esac.Identifier) AS Identifier1
518
+ , NULL AS Identifier2
519
+ ` : ""}
520
+ FROM ecchange.change.InstanceChange ic
521
+ LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') ec
522
+ ON ic.ChangedInstance.Id=ec.ECInstanceId
523
+ ${queryCanAccessProvenance ? `
524
+ LEFT JOIN bis.ExternalSourceAspect esa
525
+ ON ec.ECInstanceId=esa.Element.Id
526
+ LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') esac
527
+ ON ec.ECInstanceId=esac.Element.Id
528
+ ` : ""}
529
+ WHERE ic.OpCode=:opDelete
530
+ AND ic.Summary.Id=:changeSummaryId
531
+ AND ic.ChangedInstance.ClassId IS (BisCore.Element)
532
+ ${queryCanAccessProvenance ? `
533
+ AND (esa.Scope.Id=:targetScopeElement OR esa.Scope.Id IS NULL)
534
+ AND (esa.Kind='Element' OR esa.Kind IS NULL)
535
+ AND (esac.Scope.Id=:targetScopeElement OR esac.Scope.Id IS NULL)
536
+ AND (esac.Kind='Element' OR esac.Kind IS NULL)
537
+ ` : ""}
538
+
539
+ UNION ALL
540
+
541
+ SELECT
542
+ 0 AS IsElemNotRel,
543
+ ic.ChangedInstance.Id AS InstanceId,
544
+ coalesce(se.ECInstanceId, sec.ECInstanceId) AS InstId2,
545
+ coalesce(te.ECInstanceId, tec.ECInstanceId) AS InstId3,
546
+ coalesce(se.FederationGuid, sec.FederationGuid) AS FedGuid1,
547
+ coalesce(te.FederationGuid, tec.FederationGuid) AS FedGuid2,
548
+ ic.ChangedInstance.ClassId AS ClassId
549
+ ${queryCanAccessProvenance ? `
550
+ , coalesce(sesa.Identifier, sesac.Identifier) AS Identifier1
551
+ , coalesce(tesa.Identifier, tesac.Identifier) AS Identifier2
552
+ ` : ""}
553
+ FROM ecchange.change.InstanceChange ic
554
+ LEFT JOIN bis.ElementRefersToElements.Changes(:changeSummaryId, 'BeforeDelete') ertec
555
+ ON ic.ChangedInstance.Id=ertec.ECInstanceId
556
+ -- FIXME: test a deletion of both an element and a relationship at the same time
557
+ LEFT JOIN bis.Element se
558
+ ON se.ECInstanceId=ertec.SourceECInstanceId
559
+ LEFT JOIN bis.Element te
560
+ ON te.ECInstanceId=ertec.TargetECInstanceId
561
+ LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') sec
562
+ ON sec.ECInstanceId=ertec.SourceECInstanceId
563
+ LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') tec
564
+ ON tec.ECInstanceId=ertec.TargetECInstanceId
565
+ ${queryCanAccessProvenance ? `
566
+ -- NOTE: need to join on both se/te and sec/tec incase the element was deleted
567
+ LEFT JOIN bis.ExternalSourceAspect sesa
568
+ ON se.ECInstanceId=sesa.Element.Id -- don't use *esac*.Identifier because it's a string
569
+ LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') sesac
570
+ ON sec.ECInstanceId=sesac.Element.Id
571
+ LEFT JOIN bis.ExternalSourceAspect tesa
572
+ ON te.ECInstanceId=tesa.Element.Id
573
+ LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') tesac
574
+ ON tec.ECInstanceId=tesac.Element.Id
575
+ ` : ""}
576
+ WHERE ic.OpCode=:opDelete
577
+ AND ic.Summary.Id=:changeSummaryId
578
+ AND ic.ChangedInstance.ClassId IS (BisCore.ElementRefersToElements)
579
+ ${queryCanAccessProvenance ? `
580
+ AND (sesa.Scope.Id=:targetScopeElement OR sesa.Scope.Id IS NULL)
581
+ AND (sesa.Kind='Relationship' OR sesa.Kind IS NULL)
582
+ AND (sesac.Scope.Id=:targetScopeElement OR sesac.Scope.Id IS NULL)
583
+ AND (sesac.Kind='Relationship' OR sesac.Kind IS NULL)
584
+ AND (tesa.Scope.Id=:targetScopeElement OR tesa.Scope.Id IS NULL)
585
+ AND (tesa.Kind='Relationship' OR tesa.Kind IS NULL)
586
+ AND (tesac.Scope.Id=:targetScopeElement OR tesac.Scope.Id IS NULL)
587
+ AND (tesac.Kind='Relationship' OR tesac.Kind IS NULL)
588
+ ` : ""}
589
+ `;
590
+ for (const changeSummaryId of this._changeSummaryIds) {
591
+ // FIXME: test deletion in both forward and reverse sync
592
+ this.sourceDb.withPreparedStatement(deletedEntitySql, (stmt) => {
593
+ stmt.bindInteger("opDelete", core_common_1.ChangeOpCode.Delete);
594
+ if (queryCanAccessProvenance)
595
+ stmt.bindId("targetScopeElement", this.targetScopeElementId);
596
+ stmt.bindId("changeSummaryId", changeSummaryId);
597
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
598
+ const isElemNotRel = stmt.getValue(0).getBoolean();
599
+ const instId = stmt.getValue(1).getId();
600
+ if (isElemNotRel) {
601
+ const sourceElemFedGuid = stmt.getValue(4).getGuid();
602
+ // "Identifier" is a string, so null value returns '' which doesn't work with ??, and I don't like ||
603
+ let identifierValue;
604
+ // TODO: if I could attach the second db, will probably be much faster to get target id
605
+ // as part of the whole query rather than with _queryElemIdByFedGuid
606
+ const targetId = (queryCanAccessProvenance
607
+ && (identifierValue = stmt.getValue(7))
608
+ && !identifierValue.isNull
609
+ && identifierValue.getString())
610
+ // maybe batching these queries would perform better but we should
611
+ // try to attach the second db and query both together anyway
612
+ || (sourceElemFedGuid && this._queryElemIdByFedGuid(this.targetDb, sourceElemFedGuid))
613
+ // FIXME: describe why it's safe to assume nothing has been deleted in provenanceDb
614
+ || this._queryProvenanceForElement(instId);
615
+ // since we are processing one changeset at a time, we can see local source deletes
616
+ // of entities that were never synced and can be safely ignored
617
+ const deletionNotInTarget = !targetId;
618
+ if (deletionNotInTarget)
619
+ continue;
620
+ this.context.remapElement(instId, targetId);
350
621
  }
351
- });
352
- }
622
+ else { // is deleted relationship
623
+ const classFullName = stmt.getValue(6).getClassNameForClassId();
624
+ const [sourceIdInTarget, targetIdInTarget] = [
625
+ { guidColumn: 4, identifierColumn: 7, isTarget: false },
626
+ { guidColumn: 5, identifierColumn: 8, isTarget: true },
627
+ ].map(({ guidColumn, identifierColumn }) => {
628
+ const fedGuid = stmt.getValue(guidColumn).getGuid();
629
+ let identifierValue;
630
+ return ((queryCanAccessProvenance
631
+ // FIXME: this is really far from idiomatic, try to undo that
632
+ && (identifierValue = stmt.getValue(identifierColumn))
633
+ && !identifierValue.isNull
634
+ && identifierValue.getString())
635
+ // maybe batching these queries would perform better but we should
636
+ // try to attach the second db and query both together anyway
637
+ || (fedGuid && this._queryElemIdByFedGuid(this.targetDb, fedGuid)));
638
+ });
639
+ // since we are processing one changeset at a time, we can see local source deletes
640
+ // of entities that were never synced and can be safely ignored
641
+ if (sourceIdInTarget && targetIdInTarget) {
642
+ this._deletedSourceRelationshipData.set(instId, {
643
+ classFullName,
644
+ sourceIdInTarget,
645
+ targetIdInTarget,
646
+ });
647
+ }
648
+ else {
649
+ // FIXME: describe why it's safe to assume nothing has been deleted in provenanceDb
650
+ const relProvenance = this._queryProvenanceForRelationship(instId, {
651
+ classFullName,
652
+ sourceId: stmt.getValue(2).getId(),
653
+ targetId: stmt.getValue(3).getId(),
654
+ });
655
+ if (relProvenance && relProvenance.relationshipId)
656
+ this._deletedSourceRelationshipData.set(instId, {
657
+ classFullName,
658
+ relId: relProvenance.relationshipId,
659
+ provenanceAspectId: relProvenance.aspectId,
660
+ });
661
+ }
662
+ }
663
+ }
664
+ // NEXT: remap sourceId and targetId to target, get provenance there
665
+ // NOTE: it is possible during a forward sync for the target to already have deleted
666
+ // something that the source deleted, in which case we can safely ignore the gone provenance
667
+ });
353
668
  }
354
- finally {
355
- if (core_backend_1.ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))
356
- core_backend_1.ChangeSummaryManager.detachChangeCache(this.sourceDb);
669
+ }
670
+ _queryProvenanceForElement(entityInProvenanceSourceId) {
671
+ return this.provenanceDb.withPreparedStatement(`
672
+ SELECT esa.Element.Id
673
+ FROM Bis.ExternalSourceAspect esa
674
+ WHERE esa.Kind=?
675
+ AND esa.Scope.Id=?
676
+ AND esa.Identifier=?
677
+ `, (stmt) => {
678
+ stmt.bindString(1, core_backend_1.ExternalSourceAspect.Kind.Element);
679
+ stmt.bindId(2, this.targetScopeElementId);
680
+ stmt.bindString(3, entityInProvenanceSourceId);
681
+ if (stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW)
682
+ return stmt.getValue(0).getId();
683
+ else
684
+ return undefined;
685
+ });
686
+ }
687
+ _queryProvenanceForRelationship(entityInProvenanceSourceId, sourceRelInfo) {
688
+ return this.provenanceDb.withPreparedStatement(`
689
+ SELECT
690
+ ECInstanceId,
691
+ JSON_EXTRACT(JsonProperties, '$.targetRelInstanceId'),
692
+ JSON_EXTRACT(JsonProperties, '$.provenanceRelInstanceId')
693
+ FROM Bis.ExternalSourceAspect
694
+ WHERE Kind=?
695
+ AND Scope.Id=?
696
+ AND Identifier=?
697
+ `, (stmt) => {
698
+ stmt.bindString(1, core_backend_1.ExternalSourceAspect.Kind.Relationship);
699
+ stmt.bindId(2, this.targetScopeElementId);
700
+ stmt.bindString(3, entityInProvenanceSourceId);
701
+ if (stmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
702
+ return undefined;
703
+ const aspectId = stmt.getValue(0).getId();
704
+ const provenanceRelInstIdVal = stmt.getValue(2);
705
+ const provenanceRelInstanceId = !provenanceRelInstIdVal.isNull
706
+ ? provenanceRelInstIdVal.getString()
707
+ : this._queryTargetRelId(sourceRelInfo);
708
+ return {
709
+ aspectId,
710
+ relationshipId: provenanceRelInstanceId,
711
+ };
712
+ });
713
+ }
714
+ _queryTargetRelId(sourceRelInfo) {
715
+ const targetRelInfo = {
716
+ sourceId: this.context.findTargetElementId(sourceRelInfo.sourceId),
717
+ targetId: this.context.findTargetElementId(sourceRelInfo.targetId),
718
+ };
719
+ if (targetRelInfo.sourceId === undefined || targetRelInfo.targetId === undefined)
720
+ return undefined; // couldn't find an element, rel is invalid or deleted
721
+ return this.targetDb.withPreparedStatement(`
722
+ SELECT ECInstanceId
723
+ FROM bis.ElementRefersToElements
724
+ WHERE SourceECInstanceId=?
725
+ AND TargetECInstanceId=?
726
+ AND ECClassId=?
727
+ `, (stmt) => {
728
+ stmt.bindId(1, targetRelInfo.sourceId);
729
+ stmt.bindId(2, targetRelInfo.targetId);
730
+ stmt.bindId(3, this._targetClassNameToClassId(sourceRelInfo.classFullName));
731
+ if (stmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
732
+ return undefined;
733
+ return stmt.getValue(0).getId();
734
+ });
735
+ }
736
+ _targetClassNameToClassId(classFullName) {
737
+ let classId = this._targetClassNameToClassIdCache.get(classFullName);
738
+ if (classId === undefined) {
739
+ classId = this._getRelClassId(this.targetDb, classFullName);
740
+ this._targetClassNameToClassIdCache.set(classFullName, classId);
357
741
  }
742
+ return classId;
743
+ }
744
+ // NOTE: this doesn't handle remapped element classes,
745
+ // but is only used for relationships rn
746
+ _getRelClassId(db, classFullName) {
747
+ return db.withPreparedStatement(`
748
+ SELECT c.ECInstanceId
749
+ FROM ECDbMeta.ECClassDef c
750
+ JOIN ECDbMeta.ECSchemaDef s ON c.Schema.Id=s.ECInstanceId
751
+ WHERE s.Name=? AND c.Name=?
752
+ `, (stmt) => {
753
+ const [schemaName, className] = classFullName.split(".");
754
+ stmt.bindString(1, schemaName);
755
+ stmt.bindString(2, className);
756
+ if (stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW)
757
+ return stmt.getValue(0).getId();
758
+ (0, core_bentley_1.assert)(false, "relationship was not found");
759
+ });
760
+ }
761
+ _queryElemIdByFedGuid(db, fedGuid) {
762
+ return db.withPreparedStatement("SELECT ECInstanceId FROM Bis.Element WHERE FederationGuid=?", (stmt) => {
763
+ stmt.bindGuid(1, fedGuid);
764
+ if (stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW)
765
+ return stmt.getValue(0).getId();
766
+ else
767
+ return undefined;
768
+ });
358
769
  }
359
770
  /** Returns `true` if *brute force* delete detections should be run.
360
771
  * @note Not relevant for processChanges when change history is known.
361
772
  */
362
773
  shouldDetectDeletes() {
774
+ // FIXME: all synchronizations should mark this as false
363
775
  if (this._isFirstSynchronization)
364
776
  return false; // not necessary the first time since there are no deletes to detect
365
777
  if (this._options.isReverseSynchronization)
366
778
  return false; // not possible for a reverse synchronization since provenance will be deleted when element is deleted
367
779
  return true;
368
780
  }
369
- /** Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements in the source iModel.
370
- * @see processChanges
371
- * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.
781
+ /**
782
+ * Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements
783
+ * in the source iModel.
784
+ * @deprecated in 0.1.x. This method is only called during [[processAll]] when the option
785
+ * [[IModelTransformerOptions.forceExternalSourceAspectProvenance]] is enabled. It is not
786
+ * necessary when using [[processChanges]] since changeset information is sufficient.
787
+ * @note you do not need to call this directly unless processing a subset of an iModel.
372
788
  * @throws [[IModelError]] If the required provenance information is not available to detect deletes.
373
789
  */
374
790
  async detectElementDeletes() {
375
- if (this._options.isReverseSynchronization) {
376
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Cannot detect deletes when isReverseSynchronization=true");
377
- }
378
- const targetElementsToDelete = [];
379
- this.forEachTrackedElement((sourceElementId, targetElementId) => {
380
- if (undefined === this.sourceDb.elements.tryGetElementProps(sourceElementId)) {
381
- // if the sourceElement is not found, then it must have been deleted, so propagate the delete to the target iModel
382
- targetElementsToDelete.push(targetElementId);
383
- }
384
- });
385
- targetElementsToDelete.forEach((targetElementId) => {
386
- try {
387
- // TODO: make it possible to delete more elements at once to prevent redundant expensive
388
- // element reference scanning
389
- this.importer.deleteElement(targetElementId);
390
- }
391
- catch (err) {
392
- // ignore not found elements, iterative element tree deletion might have already deleted them
393
- if (err.name !== "Not Found")
394
- throw err;
791
+ const sql = `
792
+ SELECT Identifier, Element.Id
793
+ FROM BisCore.ExternalSourceAspect
794
+ WHERE Scope.Id=:scopeId
795
+ AND Kind=:kind
796
+ `;
797
+ nodeAssert(!this._options.isReverseSynchronization, "synchronizations with processChagnes already detect element deletes, don't call detectElementDeletes");
798
+ this.provenanceDb.withPreparedStatement(sql, (stmt) => {
799
+ stmt.bindId("scopeId", this.targetScopeElementId);
800
+ stmt.bindString("kind", core_backend_1.ExternalSourceAspect.Kind.Element);
801
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
802
+ // ExternalSourceAspect.Identifier is of type string
803
+ const aspectIdentifier = stmt.getValue(0).getString();
804
+ const targetElemId = stmt.getValue(1).getId();
805
+ const wasDeletedInSource = !EntityUnifier_1.EntityUnifier.exists(this.sourceDb, { entityReference: `e${aspectIdentifier}` });
806
+ if (wasDeletedInSource)
807
+ this.importer.deleteElement(targetElemId);
395
808
  }
396
809
  });
397
810
  }
@@ -418,24 +831,53 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
418
831
  }
419
832
  return targetElementProps;
420
833
  }
834
+ // FIXME: this is a PoC, see if we minimize memory usage
835
+ _cacheSourceChanges() {
836
+ nodeAssert(this._changeSummaryIds && this._changeSummaryIds.length > 0, "should have changeset data by now");
837
+ this._hasElementChangedCache = new Set();
838
+ const query = `
839
+ SELECT
840
+ ic.ChangedInstance.Id AS InstId
841
+ FROM ecchange.change.InstanceChange ic
842
+ JOIN iModelChange.Changeset imc ON ic.Summary.Id=imc.Summary.Id
843
+ -- FIXME: do relationship entities also need this cache optimization?
844
+ WHERE ic.ChangedInstance.ClassId IS (BisCore.Element)
845
+ AND InVirtualSet(:changeSummaryIds, ic.Summary.Id)
846
+ -- ignore deleted, we take care of those in remapDeletedSourceEntities
847
+ -- include inserted since inserted code-colliding elements should be considered
848
+ -- a change so that the colliding element is exported to the target
849
+ AND ic.OpCode<>:opDelete
850
+ `;
851
+ // there is a single mega-query multi-join+coalescing hack that I used originally to get around
852
+ // only being able to run table.Changes() on one changeset at once, but sqlite only supports up to 64
853
+ // tables in a join. Need to talk to core about .Changes being able to take a set of changesets
854
+ // You can find this version in the `federation-guid-optimization-megaquery` branch
855
+ // I wouldn't use it unless we prove via profiling that it speeds things up significantly
856
+ // And even then let's first try scanning the raw changesets instead of applying them as these queries
857
+ // require
858
+ this.sourceDb.withPreparedStatement(query, (stmt) => {
859
+ stmt.bindInteger("opDelete", core_common_1.ChangeOpCode.Delete);
860
+ stmt.bindIdSet("changeSummaryIds", this._changeSummaryIds);
861
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
862
+ const instId = stmt.getValue(0).getId();
863
+ this._hasElementChangedCache.add(instId);
864
+ }
865
+ });
866
+ }
421
867
  /** Returns true if a change within sourceElement is detected.
422
868
  * @param sourceElement The Element from the source iModel
423
869
  * @param targetElementId The Element from the target iModel to compare against.
424
870
  * @note A subclass can override this method to provide custom change detection behavior.
425
871
  */
426
- hasElementChanged(sourceElement, targetElementId) {
427
- const sourceAspects = this.targetDb.elements.getAspects(targetElementId, core_backend_1.ExternalSourceAspect.classFullName);
428
- for (const sourceAspect of sourceAspects) {
429
- if (sourceAspect.scope === undefined) // if the scope was lost, we can't correlate so assume it changed
430
- return true;
431
- if (sourceAspect.identifier === sourceElement.id &&
432
- sourceAspect.scope.id === this.targetScopeElementId &&
433
- sourceAspect.kind === core_backend_1.ExternalSourceAspect.Kind.Element) {
434
- const lastModifiedTime = sourceElement.iModel.elements.queryLastModifiedTime(sourceElement.id);
435
- return lastModifiedTime !== sourceAspect.version;
436
- }
437
- }
438
- return true;
872
+ hasElementChanged(sourceElement, _targetElementId) {
873
+ if (this._sourceChangeDataState === "no-changes")
874
+ return false;
875
+ if (this._sourceChangeDataState === "unconnected")
876
+ return true;
877
+ nodeAssert(this._sourceChangeDataState === "has-changes", "change data should be initialized by now");
878
+ if (this._hasElementChangedCache === undefined)
879
+ this._cacheSourceChanges();
880
+ return this._hasElementChangedCache.has(sourceElement.id);
439
881
  }
440
882
  static transformCallbackFor(transformer, entity) {
441
883
  if (entity instanceof core_backend_1.Element)
@@ -607,51 +1049,68 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
607
1049
  targetElementId = this.context.findTargetElementId(sourceElement.id);
608
1050
  targetElementProps = this.onTransformElement(sourceElement);
609
1051
  }
1052
+ // if an existing remapping was not yet found, check by FederationGuid
1053
+ if (this.context.isBetweenIModels && !core_bentley_1.Id64.isValid(targetElementId) && sourceElement.federationGuid !== undefined) {
1054
+ targetElementId = this._queryElemIdByFedGuid(this.targetDb, sourceElement.federationGuid) ?? core_bentley_1.Id64.invalid;
1055
+ if (core_bentley_1.Id64.isValid(targetElementId))
1056
+ this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found
1057
+ }
610
1058
  // if an existing remapping was not yet found, check by Code as long as the CodeScope is valid (invalid means a missing reference so not worth checking)
611
- if (!core_bentley_1.Id64.isValidId64(targetElementId) && core_bentley_1.Id64.isValidId64(targetElementProps.code.scope)) {
1059
+ if (!core_bentley_1.Id64.isValid(targetElementId) && core_bentley_1.Id64.isValidId64(targetElementProps.code.scope)) {
612
1060
  // respond the same way to undefined code value as the @see Code class, but don't use that class because is trims
613
1061
  // whitespace from the value, and there are iModels out there with untrimmed whitespace that we ought not to trim
614
1062
  targetElementProps.code.value = targetElementProps.code.value ?? "";
615
- targetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code);
616
- if (undefined !== targetElementId) {
617
- const targetElement = this.targetDb.elements.getElement(targetElementId);
618
- if (targetElement.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class
1063
+ const maybeTargetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code);
1064
+ if (undefined !== maybeTargetElementId) {
1065
+ const maybeTargetElem = this.targetDb.elements.getElement(maybeTargetElementId);
1066
+ if (maybeTargetElem.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class
1067
+ targetElementId = maybeTargetElementId;
619
1068
  this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code
620
1069
  }
621
1070
  else {
622
- targetElementId = undefined;
623
1071
  targetElementProps.code = core_common_1.Code.createEmpty(); // clear out invalid code
624
1072
  }
625
1073
  }
626
1074
  }
627
- if (undefined !== targetElementId && core_bentley_1.Id64.isValidId64(targetElementId)) {
628
- // compare LastMod of sourceElement to ExternalSourceAspect of targetElement to see there are changes to import
629
- if (!this.hasElementChanged(sourceElement, targetElementId)) {
630
- return;
631
- }
632
- }
1075
+ if (core_bentley_1.Id64.isValid(targetElementId) && !this.hasElementChanged(sourceElement, targetElementId))
1076
+ return;
633
1077
  this.collectUnmappedReferences(sourceElement);
634
- // TODO: untangle targetElementId state...
635
- if (targetElementId === core_bentley_1.Id64.invalid)
636
- targetElementId = undefined;
637
- targetElementProps.id = targetElementId; // targetElementId will be valid (indicating update) or undefined (indicating insert)
1078
+ // targetElementId will be valid (indicating update) or undefined (indicating insert)
1079
+ targetElementProps.id
1080
+ = core_bentley_1.Id64.isValid(targetElementId)
1081
+ ? targetElementId
1082
+ : undefined;
638
1083
  if (!this._options.wasSourceIModelCopiedToTarget) {
639
1084
  this.importer.importElement(targetElementProps); // don't need to import if iModel was copied
640
1085
  }
641
1086
  this.context.remapElement(sourceElement.id, targetElementProps.id); // targetElementProps.id assigned by importElement
642
1087
  // now that we've mapped this elem we can fix unmapped references to it
643
1088
  this.resolvePendingReferences(sourceElement);
1089
+ // the transformer does not currently 'split' or 'join' any elements, therefore, it does not
1090
+ // insert external source aspects because federation guids are sufficient for this.
1091
+ // Other transformer subclasses must insert the appropriate aspect (as provided by a TBD API)
1092
+ // when splitting/joining elements
1093
+ // physical consolidation is an example of a 'joining' transform
1094
+ // FIXME: document this externally!
1095
+ // verify at finalization time that we don't lose provenance on new elements
1096
+ // make public and improve `initElementProvenance` API for usage by consolidators
644
1097
  if (!this._options.noProvenance) {
645
- const aspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id);
646
- let aspectId = this.queryExternalSourceAspectId(aspectProps);
647
- if (aspectId === undefined) {
648
- aspectId = this.provenanceDb.elements.insertAspect(aspectProps);
649
- }
650
- else {
651
- this.provenanceDb.elements.updateAspect(aspectProps);
1098
+ let provenance = this._options.forceExternalSourceAspectProvenance || this._elementsWithExplicitlyTrackedProvenance.has(sourceElement.id)
1099
+ ? undefined
1100
+ : sourceElement.federationGuid;
1101
+ if (!provenance) {
1102
+ const aspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id);
1103
+ const aspectId = this.queryScopeExternalSource(aspectProps).aspectId;
1104
+ if (aspectId === undefined) {
1105
+ aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);
1106
+ }
1107
+ else {
1108
+ aspectProps.id = aspectId;
1109
+ this.provenanceDb.elements.updateAspect(aspectProps);
1110
+ }
1111
+ provenance = aspectProps;
652
1112
  }
653
- aspectProps.id = aspectId;
654
- this.markLastProvenance(aspectProps, { isRelationship: false });
1113
+ this.markLastProvenance(provenance, { isRelationship: false });
655
1114
  }
656
1115
  }
657
1116
  resolvePendingReferences(entity) {
@@ -689,7 +1148,7 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
689
1148
  onDeleteModel(sourceModelId) {
690
1149
  // It is possible and apparently occasionally sensical to delete a model without deleting its underlying element.
691
1150
  // - If only the model is deleted, [[initFromExternalSourceAspects]] will have already remapped the underlying element since it still exists.
692
- // - If both were deleted, [[remapDeletedSourceElements]] will find and remap the deleted element making this operation valid
1151
+ // - If both were deleted, [[remapDeletedSourceEntities]] will find and remap the deleted element making this operation valid
693
1152
  const targetModelId = this.context.findTargetElementId(sourceModelId);
694
1153
  if (core_bentley_1.Id64.isValidId64(targetModelId)) {
695
1154
  this.importer.deleteModel(targetModelId);
@@ -765,7 +1224,52 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
765
1224
  * @deprecated in 3.x. This method is no longer necessary since the transformer no longer needs to defer elements
766
1225
  */
767
1226
  async processDeferredElements(_numRetries = 3) { }
1227
+ /** called at the end ([[finalizeTransformation]]) of a transformation,
1228
+ * updates the target scope element to say that transformation up through the
1229
+ * source's changeset has been performed.
1230
+ */
1231
+ _updateSynchronizationVersion() {
1232
+ if (this._sourceChangeDataState !== "has-changes" && !this._isFirstSynchronization)
1233
+ return;
1234
+ nodeAssert(this._targetScopeProvenanceProps);
1235
+ const newVersion = `${this.sourceDb.changeset.id};${this.sourceDb.changeset.index}`;
1236
+ if (this._options.isReverseSynchronization || this._isFirstSynchronization) {
1237
+ const oldVersion = this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion;
1238
+ core_bentley_1.Logger.logInfo(loggerCategory, `updating reverse version from ${oldVersion} to ${newVersion}`);
1239
+ // FIXME: could technically just put a delimiter in the version field to avoid using json properties
1240
+ this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion = newVersion;
1241
+ }
1242
+ if (!this._options.isReverseSynchronization || this._isFirstSynchronization) {
1243
+ core_bentley_1.Logger.logInfo(loggerCategory, `updating sync version from ${this._targetScopeProvenanceProps.version} to ${newVersion}`);
1244
+ this._targetScopeProvenanceProps.version = newVersion;
1245
+ }
1246
+ if (this._isSynchronization) {
1247
+ (0, core_bentley_1.assert)(this.targetDb.changeset.index !== undefined && this._startingTargetChangesetIndex !== undefined, "_updateSynchronizationVersion was called without change history");
1248
+ const jsonProps = this._targetScopeProvenanceProps.jsonProperties;
1249
+ core_bentley_1.Logger.logTrace(loggerCategory, `previous pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`);
1250
+ core_bentley_1.Logger.logTrace(loggerCategory, `previous pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`);
1251
+ const [syncChangesetsToClear, syncChangesetsToUpdate] = this._isReverseSynchronization
1252
+ ? [jsonProps.pendingReverseSyncChangesetIndices, jsonProps.pendingSyncChangesetIndices]
1253
+ : [jsonProps.pendingSyncChangesetIndices, jsonProps.pendingReverseSyncChangesetIndices];
1254
+ // NOTE that as documented in [[processChanges]], this assumes that right after
1255
+ // transformation finalization, the work will be saved immediately, otherwise we've
1256
+ // just marked this changeset as a synchronization to ignore, and the user can add other
1257
+ // stuff to it which would break future synchronizations
1258
+ // FIXME: force save for the user to prevent that
1259
+ for (let i = this._startingTargetChangesetIndex + 1; i <= this.targetDb.changeset.index + 1; i++)
1260
+ syncChangesetsToUpdate.push(i);
1261
+ syncChangesetsToClear.length = 0;
1262
+ core_bentley_1.Logger.logTrace(loggerCategory, `new pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`);
1263
+ core_bentley_1.Logger.logTrace(loggerCategory, `new pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`);
1264
+ }
1265
+ this.provenanceDb.elements.updateAspect({
1266
+ ...this._targetScopeProvenanceProps,
1267
+ jsonProperties: JSON.stringify(this._targetScopeProvenanceProps.jsonProperties),
1268
+ });
1269
+ }
1270
+ // FIXME: is this necessary when manually using lowlevel transform APIs?
768
1271
  finalizeTransformation() {
1272
+ this._updateSynchronizationVersion();
769
1273
  if (this._partiallyCommittedEntities.size > 0) {
770
1274
  core_bentley_1.Logger.logWarning(loggerCategory, [
771
1275
  "The following elements were never fully resolved:",
@@ -777,6 +1281,11 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
777
1281
  partiallyCommittedElem.forceComplete();
778
1282
  }
779
1283
  }
1284
+ // FIXME: make processAll have a try {} finally {} that cleans this up
1285
+ if (!this._options.noDetachChangeCache) {
1286
+ if (core_backend_1.ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))
1287
+ core_backend_1.ChangeSummaryManager.detachChangeCache(this.sourceDb);
1288
+ }
780
1289
  }
781
1290
  /** Imports all relationships that subclass from the specified base class.
782
1291
  * @param baseRelClassFullName The specified base relationship class.
@@ -794,40 +1303,52 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
794
1303
  * This override calls [[onTransformRelationship]] and then [IModelImporter.importRelationship]($transformer) to update the target iModel.
795
1304
  */
796
1305
  onExportRelationship(sourceRelationship) {
1306
+ const sourceFedGuid = queryElemFedGuid(this.sourceDb, sourceRelationship.sourceId);
1307
+ const targetFedGuid = queryElemFedGuid(this.sourceDb, sourceRelationship.targetId);
797
1308
  const targetRelationshipProps = this.onTransformRelationship(sourceRelationship);
798
1309
  const targetRelationshipInstanceId = this.importer.importRelationship(targetRelationshipProps);
799
- if (!this._options.noProvenance && core_bentley_1.Id64.isValidId64(targetRelationshipInstanceId)) {
800
- const aspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);
801
- if (undefined === aspectProps.id) {
802
- aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);
1310
+ if (!this._options.noProvenance && core_bentley_1.Id64.isValid(targetRelationshipInstanceId)) {
1311
+ let provenance = !this._options.forceExternalSourceAspectProvenance
1312
+ ? sourceFedGuid && targetFedGuid && `${sourceFedGuid}/${targetFedGuid}`
1313
+ : undefined;
1314
+ if (!provenance) {
1315
+ const aspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);
1316
+ aspectProps.id = this.queryScopeExternalSource(aspectProps).aspectId;
1317
+ if (undefined === aspectProps.id) {
1318
+ aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);
1319
+ }
1320
+ provenance = aspectProps;
803
1321
  }
804
- (0, core_bentley_1.assert)(aspectProps.id !== undefined);
805
- this.markLastProvenance(aspectProps, { isRelationship: true });
1322
+ this.markLastProvenance(provenance, { isRelationship: true });
806
1323
  }
807
1324
  }
808
1325
  /** Override of [IModelExportHandler.onDeleteRelationship]($transformer) that is called when [IModelExporter]($transformer) detects that a [Relationship]($backend) has been deleted from the source iModel.
809
1326
  * This override propagates the delete to the target iModel via [IModelImporter.deleteRelationship]($transformer).
810
1327
  */
811
1328
  onDeleteRelationship(sourceRelInstanceId) {
812
- const sql = `SELECT ECInstanceId,JsonProperties FROM ${core_backend_1.ExternalSourceAspect.classFullName} aspect` +
813
- ` WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind AND aspect.Identifier=:identifier LIMIT 1`;
814
- this.targetDb.withPreparedStatement(sql, (statement) => {
815
- statement.bindId("scopeId", this.targetScopeElementId);
816
- statement.bindString("kind", core_backend_1.ExternalSourceAspect.Kind.Relationship);
817
- statement.bindString("identifier", sourceRelInstanceId);
818
- if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
819
- const json = JSON.parse(statement.getValue(1).getString());
820
- if (undefined !== json.targetRelInstanceId) {
821
- const targetRelationship = this.targetDb.relationships.tryGetInstance(core_backend_1.ElementRefersToElements.classFullName, json.targetRelInstanceId);
822
- if (targetRelationship) {
823
- this.importer.deleteRelationship(targetRelationship.toJSON());
824
- }
825
- this.targetDb.elements.deleteAspect(statement.getValue(0).getId());
826
- }
827
- }
828
- });
1329
+ nodeAssert(this._deletedSourceRelationshipData, "should be defined at initialization by now");
1330
+ const deletedRelData = this._deletedSourceRelationshipData.get(sourceRelInstanceId);
1331
+ if (!deletedRelData) {
1332
+ // this can occur if both the source and target deleted it
1333
+ core_bentley_1.Logger.logWarning(loggerCategory, "tried to delete a relationship that wasn't in change data");
1334
+ return;
1335
+ }
1336
+ const relArg = deletedRelData.relId ?? {
1337
+ sourceId: deletedRelData.sourceIdInTarget,
1338
+ targetId: deletedRelData.targetIdInTarget,
1339
+ };
1340
+ //
1341
+ // FIXME: make importer.deleteRelationship not need full props
1342
+ const targetRelationship = this.targetDb.relationships.tryGetInstance(deletedRelData.classFullName, relArg);
1343
+ if (targetRelationship) {
1344
+ this.importer.deleteRelationship(targetRelationship.toJSON());
1345
+ }
1346
+ if (deletedRelData.provenanceAspectId) {
1347
+ this.provenanceDb.elements.deleteAspect(deletedRelData.provenanceAspectId);
1348
+ }
829
1349
  }
830
1350
  /** Detect Relationship deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against relationships in the source iModel.
1351
+ * @deprecated
831
1352
  * @see processChanges
832
1353
  * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.
833
1354
  * @throws [[IModelError]] If the required provenance information is not available to detect deletes.
@@ -837,13 +1358,20 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
837
1358
  throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Cannot detect deletes when isReverseSynchronization=true");
838
1359
  }
839
1360
  const aspectDeleteIds = [];
840
- const sql = `SELECT ECInstanceId,Identifier,JsonProperties FROM ${core_backend_1.ExternalSourceAspect.classFullName} aspect WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind`;
1361
+ const sql = `
1362
+ SELECT ECInstanceId, Identifier, JsonProperties
1363
+ FROM ${core_backend_1.ExternalSourceAspect.classFullName} aspect
1364
+ WHERE aspect.Scope.Id=:scopeId
1365
+ AND aspect.Kind=:kind
1366
+ `;
841
1367
  await this.targetDb.withPreparedStatement(sql, async (statement) => {
842
1368
  statement.bindId("scopeId", this.targetScopeElementId);
843
1369
  statement.bindString("kind", core_backend_1.ExternalSourceAspect.Kind.Relationship);
844
1370
  while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
845
1371
  const sourceRelInstanceId = core_bentley_1.Id64.fromJSON(statement.getValue(1).getString());
846
1372
  if (undefined === this.sourceDb.relationships.tryGetInstanceProps(core_backend_1.ElementRefersToElements.classFullName, sourceRelInstanceId)) {
1373
+ // FIXME: make sure matches new provenance-based method
1374
+ // FIXME: use sql JSON_EXTRACT
847
1375
  const json = JSON.parse(statement.getValue(2).getString());
848
1376
  if (undefined !== json.targetRelInstanceId) {
849
1377
  const targetRelationship = this.targetDb.relationships.getInstance(core_backend_1.ElementRefersToElements.classFullName, json.targetRelInstanceId);
@@ -865,6 +1393,7 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
865
1393
  const targetRelationshipProps = sourceRelationship.toJSON();
866
1394
  targetRelationshipProps.sourceId = this.context.findTargetElementId(sourceRelationship.sourceId);
867
1395
  targetRelationshipProps.targetId = this.context.findTargetElementId(sourceRelationship.targetId);
1396
+ // TODO: move to cloneRelationship in IModelCloneContext
868
1397
  sourceRelationship.forEachProperty((propertyName, propertyMetaData) => {
869
1398
  if ((core_common_1.PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && ("Id" === propertyMetaData.extendedType)) {
870
1399
  targetRelationshipProps[propertyName] = this.context.findTargetElementId(sourceRelationship.asAny[propertyName]);
@@ -1026,26 +1555,86 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1026
1555
  return this.processDeferredElements(); // eslint-disable-line deprecation/deprecation
1027
1556
  }
1028
1557
  /**
1029
- * Initialize prerequisites of processing, you must initialize with an [[InitFromExternalSourceAspectsArgs]] if you
1030
- * are intending process changes, but prefer using [[processChanges]]
1031
- * Called by all `process*` functions implicitly.
1558
+ * Initialize prerequisites of processing, you must initialize with an [[InitArgs]] if you
1559
+ * are intending to process changes, but prefer using [[processChanges]] explicitly since it calls this.
1560
+ * @note Called by all `process*` functions implicitly.
1032
1561
  * Overriders must call `super.initialize()` first
1033
1562
  */
1034
1563
  async initialize(args) {
1035
1564
  if (this._initialized)
1036
1565
  return;
1037
1566
  await this.context.initialize();
1567
+ await this._tryInitChangesetData(args);
1038
1568
  // eslint-disable-next-line deprecation/deprecation
1039
1569
  await this.initFromExternalSourceAspects(args);
1040
1570
  this._initialized = true;
1041
1571
  }
1572
+ async _tryInitChangesetData(args) {
1573
+ if (!args || this.sourceDb.iTwinId === undefined || this.sourceDb.changeset.index === undefined) {
1574
+ this._sourceChangeDataState = "unconnected";
1575
+ return;
1576
+ }
1577
+ const noChanges = this._synchronizationVersion.index === this.sourceDb.changeset.index;
1578
+ if (noChanges) {
1579
+ this._sourceChangeDataState = "no-changes";
1580
+ this._changeSummaryIds = [];
1581
+ return;
1582
+ }
1583
+ // NOTE: that we do NOT download the changesummary for the last transformed version, we want
1584
+ // to ignore those already processed changes
1585
+ const startChangesetIndexOrId = args.startChangeset?.index
1586
+ ?? args.startChangeset?.id
1587
+ ?? args.startChangesetId // eslint-disable-line deprecation/deprecation
1588
+ ?? this._synchronizationVersion.index + 1;
1589
+ const endChangesetId = this.sourceDb.changeset.id;
1590
+ const [startChangesetIndex, endChangesetIndex] = await Promise.all(([startChangesetIndexOrId, endChangesetId])
1591
+ .map(async (indexOrId) => typeof indexOrId === "number"
1592
+ ? indexOrId
1593
+ : core_backend_1.IModelHost.hubAccess
1594
+ .queryChangeset({
1595
+ iModelId: this.sourceDb.iModelId,
1596
+ // eslint-disable-next-line deprecation/deprecation
1597
+ changeset: { id: indexOrId },
1598
+ accessToken: args.accessToken,
1599
+ })
1600
+ .then((changeset) => changeset.index)));
1601
+ const missingChangesets = startChangesetIndex > this._synchronizationVersion.index + 1;
1602
+ // FIXME: add an option to ignore this check
1603
+ if (!this._options.ignoreMissingChangesetsInSynchronizations
1604
+ && startChangesetIndex !== this._synchronizationVersion.index + 1
1605
+ && this._synchronizationVersion.index !== -1) {
1606
+ throw Error(`synchronization is ${missingChangesets ? "missing changesets" : ""},`
1607
+ + " startChangesetId should be"
1608
+ + " exactly the first changeset *after* the previous synchronization to not miss data."
1609
+ + ` You specified '${startChangesetIndexOrId}' which is changeset #${startChangesetIndex}`
1610
+ + ` but the previous synchronization for this targetScopeElement was '${this._synchronizationVersion.id}'`
1611
+ + ` which is changeset #${this._synchronizationVersion.index}. The transformer expected`
1612
+ + ` #${this._synchronizationVersion.index + 1}.`);
1613
+ }
1614
+ nodeAssert(this._targetScopeProvenanceProps, "_targetScopeProvenanceProps should be set by now");
1615
+ const changesetsToSkip = this._isReverseSynchronization
1616
+ ? this._targetScopeProvenanceProps.jsonProperties.pendingReverseSyncChangesetIndices
1617
+ : this._targetScopeProvenanceProps.jsonProperties.pendingSyncChangesetIndices;
1618
+ core_bentley_1.Logger.logTrace(loggerCategory, `changesets to skip: ${changesetsToSkip}`);
1619
+ this._changesetRanges = (0, Algo_1.rangesFromRangeAndSkipped)(startChangesetIndex, endChangesetIndex, changesetsToSkip);
1620
+ core_bentley_1.Logger.logTrace(loggerCategory, `ranges: ${this._changesetRanges}`);
1621
+ for (const [first, end] of this._changesetRanges) {
1622
+ this._changeSummaryIds = await core_backend_1.ChangeSummaryManager.createChangeSummaries({
1623
+ accessToken: args.accessToken,
1624
+ iModelId: this.sourceDb.iModelId,
1625
+ iTwinId: this.sourceDb.iTwinId,
1626
+ range: { first, end },
1627
+ });
1628
+ }
1629
+ core_backend_1.ChangeSummaryManager.attachChangeCache(this.sourceDb);
1630
+ this._sourceChangeDataState = "has-changes";
1631
+ }
1042
1632
  /** Export everything from the source iModel and import the transformed entities into the target iModel.
1043
1633
  * @note [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.
1044
1634
  */
1045
1635
  async processAll() {
1046
- core_bentley_1.Logger.logTrace(loggerCategory, "processAll()");
1047
1636
  this.logSettings();
1048
- this.validateScopeProvenance();
1637
+ this.initScopeProvenance();
1049
1638
  await this.initialize();
1050
1639
  await this.exporter.exportCodeSpecs();
1051
1640
  await this.exporter.exportFonts();
@@ -1065,12 +1654,15 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1065
1654
  this.finalizeTransformation();
1066
1655
  }
1067
1656
  markLastProvenance(sourceAspect, { isRelationship = false }) {
1068
- this._lastProvenanceEntityInfo = {
1069
- entityId: sourceAspect.element.id,
1070
- aspectId: sourceAspect.id,
1071
- aspectVersion: sourceAspect.version ?? "",
1072
- aspectKind: isRelationship ? core_backend_1.ExternalSourceAspect.Kind.Relationship : core_backend_1.ExternalSourceAspect.Kind.Element,
1073
- };
1657
+ this._lastProvenanceEntityInfo
1658
+ = typeof sourceAspect === "string"
1659
+ ? sourceAspect
1660
+ : {
1661
+ entityId: sourceAspect.element.id,
1662
+ aspectId: sourceAspect.id,
1663
+ aspectVersion: sourceAspect.version ?? "",
1664
+ aspectKind: isRelationship ? core_backend_1.ExternalSourceAspect.Kind.Relationship : core_backend_1.ExternalSourceAspect.Kind.Element,
1665
+ };
1074
1666
  }
1075
1667
  /**
1076
1668
  * Load the state of the active transformation from an open SQLiteDb
@@ -1082,17 +1674,35 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1082
1674
  const lastProvenanceEntityInfo = db.withSqliteStatement(`SELECT entityId, aspectId, aspectVersion, aspectKind FROM ${IModelTransformer.lastProvenanceEntityInfoTable}`, (stmt) => {
1083
1675
  if (core_bentley_1.DbResult.BE_SQLITE_ROW !== stmt.step())
1084
1676
  throw Error("expected row when getting lastProvenanceEntityId from target state table");
1085
- return {
1086
- entityId: stmt.getValueString(0),
1087
- aspectId: stmt.getValueString(1),
1088
- aspectVersion: stmt.getValueString(2),
1089
- aspectKind: stmt.getValueString(3),
1090
- };
1677
+ const entityId = stmt.getValueString(0);
1678
+ const isGuidOrGuidPair = entityId.includes('-');
1679
+ return isGuidOrGuidPair
1680
+ ? entityId
1681
+ : {
1682
+ entityId,
1683
+ aspectId: stmt.getValueString(1),
1684
+ aspectVersion: stmt.getValueString(2),
1685
+ aspectKind: stmt.getValueString(3),
1686
+ };
1091
1687
  });
1092
- const targetHasCorrectLastProvenance =
1093
- // ignore provenance check if it's null since we can't bind those ids
1094
- !core_bentley_1.Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||
1688
+ /*
1689
+ // TODO: maybe save transformer state resumption state based on target changset and require calls
1690
+ // to saveChanges
1691
+ if () {
1692
+ const [sourceFedGuid, targetFedGuid, relClassFullName] = lastProvenanceEntityInfo.split("/");
1693
+ const isRelProvenance = targetFedGuid !== undefined;
1694
+ const instanceId = isRelProvenance
1695
+ ? this.targetDb.elements.getElement({federationGuid: sourceFedGuid})
1696
+ : "";
1697
+ //const classId =
1698
+ if (isRelProvenance) {
1699
+ }
1700
+ }
1701
+ */
1702
+ const targetHasCorrectLastProvenance = typeof lastProvenanceEntityInfo === "string" ||
1703
+ // ignore provenance check if it's null since we can't bind those ids
1095
1704
  !core_bentley_1.Id64.isValidId64(lastProvenanceEntityInfo.entityId) ||
1705
+ !core_bentley_1.Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||
1096
1706
  this.provenanceDb.withPreparedStatement(`
1097
1707
  SELECT Version FROM ${core_backend_1.ExternalSourceAspect.classFullName}
1098
1708
  WHERE Scope.Id=:scopeId
@@ -1133,6 +1743,7 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1133
1743
  this.context.loadStateFromDb(db);
1134
1744
  this.importer.loadStateFromJson(state.importerState);
1135
1745
  this.exporter.loadStateFromJson(state.exporterState);
1746
+ this._elementsWithExplicitlyTrackedProvenance = core_bentley_1.CompressedId64Set.decompressSet(state.explicitlyTrackedElements);
1136
1747
  this.loadAdditionalStateJson(state.additionalState);
1137
1748
  }
1138
1749
  /**
@@ -1180,6 +1791,7 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1180
1791
  const jsonState = {
1181
1792
  transformerClass: this.constructor.name,
1182
1793
  options: this._options,
1794
+ explicitlyTrackedElements: core_bentley_1.CompressedId64Set.compressSet(this._elementsWithExplicitlyTrackedProvenance),
1183
1795
  importerState: this.importer.saveStateToJson(),
1184
1796
  exporterState: this.exporter.saveStateToJson(),
1185
1797
  additionalState: this.getAdditionalStateJson(),
@@ -1189,8 +1801,9 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1189
1801
  throw Error("Failed to create the js state table in the state database");
1190
1802
  if (core_bentley_1.DbResult.BE_SQLITE_DONE !== db.executeSQL(`
1191
1803
  CREATE TABLE ${IModelTransformer.lastProvenanceEntityInfoTable} (
1192
- -- because we cannot bind the invalid id which we use for our null state, we actually store the id as a hex string
1804
+ -- either the invalid id for null provenance state, federation guid (or pair for rels) of the entity, or a hex element id
1193
1805
  entityId TEXT,
1806
+ -- the following are only valid if the above entityId is a hex id representation
1194
1807
  aspectId TEXT,
1195
1808
  aspectVersion TEXT,
1196
1809
  aspectKind TEXT
@@ -1204,10 +1817,11 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1204
1817
  throw Error("Failed to insert options into the state database");
1205
1818
  });
1206
1819
  db.withSqliteStatement(`INSERT INTO ${IModelTransformer.lastProvenanceEntityInfoTable} (entityId, aspectId, aspectVersion, aspectKind) VALUES (?,?,?,?)`, (stmt) => {
1207
- stmt.bindString(1, this._lastProvenanceEntityInfo.entityId);
1208
- stmt.bindString(2, this._lastProvenanceEntityInfo.aspectId);
1209
- stmt.bindString(3, this._lastProvenanceEntityInfo.aspectVersion);
1210
- stmt.bindString(4, this._lastProvenanceEntityInfo.aspectKind);
1820
+ const lastProvenanceEntityInfo = this._lastProvenanceEntityInfo;
1821
+ stmt.bindString(1, lastProvenanceEntityInfo?.entityId ?? this._lastProvenanceEntityInfo);
1822
+ stmt.bindString(2, lastProvenanceEntityInfo?.aspectId ?? "");
1823
+ stmt.bindString(3, lastProvenanceEntityInfo?.aspectVersion ?? "");
1824
+ stmt.bindString(4, lastProvenanceEntityInfo?.aspectKind ?? "");
1211
1825
  if (core_bentley_1.DbResult.BE_SQLITE_DONE !== stmt.step())
1212
1826
  throw Error("Failed to insert options into the state database");
1213
1827
  });
@@ -1235,25 +1849,51 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1235
1849
  db.closeDb();
1236
1850
  }
1237
1851
  }
1238
- /** Export changes from the source iModel and import the transformed entities into the target iModel.
1239
- * Inserts, updates, and deletes are determined by inspecting the changeset(s).
1240
- * @param accessToken A valid access token string
1241
- * @param startChangesetId Include changes from this changeset up through and including the current changeset.
1242
- * If this parameter is not provided, then just the current changeset will be exported.
1243
- * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.
1244
- */
1245
- async processChanges(accessToken, startChangesetId) {
1246
- core_bentley_1.Logger.logTrace(loggerCategory, "processChanges()");
1852
+ async processChanges(optionsOrAccessToken, startChangesetId) {
1853
+ this._isSynchronization = true;
1854
+ const args = typeof optionsOrAccessToken === "string"
1855
+ ? {
1856
+ accessToken: optionsOrAccessToken,
1857
+ startChangeset: startChangesetId
1858
+ ? { id: startChangesetId }
1859
+ : this.sourceDb.changeset,
1860
+ }
1861
+ : {
1862
+ ...optionsOrAccessToken,
1863
+ startChangeset: optionsOrAccessToken.startChangeset
1864
+ /* eslint-disable deprecation/deprecation */
1865
+ ?? (optionsOrAccessToken.startChangesetId !== undefined
1866
+ ? { id: optionsOrAccessToken.startChangesetId }
1867
+ : undefined),
1868
+ /* eslint-enable deprecation/deprecation */
1869
+ };
1247
1870
  this.logSettings();
1248
- this.validateScopeProvenance();
1249
- await this.initialize({ accessToken, startChangesetId });
1250
- await this.exporter.exportChanges(accessToken, startChangesetId);
1871
+ this.initScopeProvenance();
1872
+ await this.initialize(args);
1873
+ // must wait for initialization of synchronization provenance data
1874
+ const changeArgs = this._changesetRanges
1875
+ ? { changesetRanges: this._changesetRanges }
1876
+ : args.startChangeset
1877
+ ? { startChangeset: args.startChangeset }
1878
+ : { startChangeset: { index: this._synchronizationVersion.index + 1 } };
1879
+ await this.exporter.exportChanges({ accessToken: args.accessToken, ...changeArgs });
1251
1880
  await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation
1252
1881
  if (this._options.optimizeGeometry)
1253
1882
  this.importer.optimizeGeometry(this._options.optimizeGeometry);
1254
1883
  this.importer.computeProjectExtents();
1255
1884
  this.finalizeTransformation();
1256
1885
  }
1886
+ /** Combine an array of source elements into a single target element.
1887
+ * All source and target elements must be created before calling this method.
1888
+ * The "combine" operation is a remap and no properties from the source elements will be exported into the target
1889
+ * and provenance will be explicitly tracked by ExternalSourceAspects
1890
+ */
1891
+ combineElements(sourceElementIds, targetElementId) {
1892
+ for (const elementId of sourceElementIds) {
1893
+ this.context.remapElement(elementId, targetElementId);
1894
+ this._elementsWithExplicitlyTrackedProvenance.add(elementId);
1895
+ }
1896
+ }
1257
1897
  }
1258
1898
  /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */
1259
1899
  IModelTransformer.jsStateTable = "TransformerJsState";
@@ -1284,6 +1924,7 @@ class TemplateModelCloner extends IModelTransformer {
1284
1924
  * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.
1285
1925
  */
1286
1926
  async placeTemplate3d(sourceTemplateModelId, targetModelId, placement) {
1927
+ await this.initialize();
1287
1928
  this.context.remapElement(sourceTemplateModelId, targetModelId);
1288
1929
  this._transform3d = core_geometry_1.Transform.createOriginAndMatrix(placement.origin, placement.angles.toMatrix3d());
1289
1930
  this._sourceIdToTargetIdMap = new Map();
@@ -1304,6 +1945,7 @@ class TemplateModelCloner extends IModelTransformer {
1304
1945
  * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.
1305
1946
  */
1306
1947
  async placeTemplate2d(sourceTemplateModelId, targetModelId, placement) {
1948
+ await this.initialize();
1307
1949
  this.context.remapElement(sourceTemplateModelId, targetModelId);
1308
1950
  this._transform3d = core_geometry_1.Transform.createOriginAndMatrix(core_geometry_1.Point3d.createFrom(placement.origin), placement.rotation);
1309
1951
  this._sourceIdToTargetIdMap = new Map();
@@ -1340,16 +1982,12 @@ class TemplateModelCloner extends IModelTransformer {
1340
1982
  const targetElementProps = super.onTransformElement(sourceElement);
1341
1983
  targetElementProps.federationGuid = core_bentley_1.Guid.createValue(); // clone from template should create a new federationGuid
1342
1984
  targetElementProps.code = core_common_1.Code.createEmpty(); // clone from template should not maintain codes
1343
- if (sourceElement instanceof core_backend_1.GeometricElement3d) {
1344
- const placement = core_common_1.Placement3d.fromJSON(targetElementProps.placement);
1345
- if (placement.isValid) {
1346
- placement.multiplyTransform(this._transform3d);
1347
- targetElementProps.placement = placement;
1348
- }
1349
- }
1350
- else if (sourceElement instanceof core_backend_1.GeometricElement2d) {
1351
- const placement = core_common_1.Placement2d.fromJSON(targetElementProps.placement);
1985
+ if (sourceElement instanceof core_backend_1.GeometricElement) {
1986
+ const is3d = sourceElement instanceof core_backend_1.GeometricElement3d;
1987
+ const placementClass = is3d ? core_common_1.Placement3d : core_common_1.Placement2d;
1988
+ const placement = (placementClass).fromJSON(targetElementProps.placement);
1352
1989
  if (placement.isValid) {
1990
+ nodeAssert(this._transform3d);
1353
1991
  placement.multiplyTransform(this._transform3d);
1354
1992
  targetElementProps.placement = placement;
1355
1993
  }
@@ -1359,4 +1997,17 @@ class TemplateModelCloner extends IModelTransformer {
1359
1997
  }
1360
1998
  }
1361
1999
  exports.TemplateModelCloner = TemplateModelCloner;
2000
+ function queryElemFedGuid(db, elemId) {
2001
+ return db.withPreparedStatement(`
2002
+ SELECT FederationGuid
2003
+ FROM bis.Element
2004
+ WHERE ECInstanceId=?
2005
+ `, (stmt) => {
2006
+ stmt.bindId(1, elemId);
2007
+ (0, core_bentley_1.assert)(stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW);
2008
+ const result = stmt.getValue(0).getGuid();
2009
+ (0, core_bentley_1.assert)(stmt.step() === core_bentley_1.DbResult.BE_SQLITE_DONE);
2010
+ return result;
2011
+ });
2012
+ }
1362
2013
  //# sourceMappingURL=IModelTransformer.js.map