@itwin/imodel-transformer 1.0.0 → 1.0.1-customchanges.0

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.
@@ -1770,6 +1770,35 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1770
1770
  await this.processChangesets();
1771
1771
  this._initialized = true;
1772
1772
  }
1773
+ async handleCustomChanges(hasElementChangedCache, deleteIdsProcessed) {
1774
+ // The hasElementChangedCache gets populated by changes from this._csFileProps.
1775
+ // Because there is a possibility that someone could manually add ids to exporter.sourceDbChanges, we must separately process exporter.sourceDbChanges and add them to our hasElementChangedCache.
1776
+ // Without this change we risk onExportElement returning early because we use hasElementChangedCache to decide if an element has changed or not.
1777
+ this.exporter.sourceDbChanges?.element.updateIds.forEach((id) => hasElementChangedCache.add(id));
1778
+ this.exporter.sourceDbChanges?.element.insertIds.forEach((id) => hasElementChangedCache.add(id));
1779
+ // This loop is to process all custom deleteIds. Unclear if the special logic is still necessary for relationships or not (TODO!!). For all other entities, we assume that the element is still present in the sourceDb because it is not
1780
+ // a real delete and instead a simulated delete to update filtering criteria between source and target. Since the element is still present, we do not need to call processDeletedOp to find the corresponding targetId.
1781
+ // We can instead rely on `forEachTrackedElement` at the top of processChangesets to find the corresponding targetId.
1782
+ // Note this also assumes we don't need to handle entity recreation for these custom deletes. I.e. a caller of API would not be able to add a custom delete for an entity that was recreated.
1783
+ // a delete followed by an insert.
1784
+ // ASSUME: If a changeset has a deleteId then custom change will never reference it. Is this still true if it was re-inserted? (TODO!!)
1785
+ if (this.exporter.sourceDbChanges?.hasCustomChanges) {
1786
+ for (const id of this.exporter.sourceDbChanges?.relationship.deleteIds.keys() ??
1787
+ []) {
1788
+ if (deleteIdsProcessed?.has(id))
1789
+ continue;
1790
+ const customData = this.exporter.sourceDbChanges?.getCustomRelationshipDataFromId(id, "relationship");
1791
+ if (customData === undefined) {
1792
+ core_bentley_1.Logger.logError(loggerCategory, "Custom data not found for relationship.", { id });
1793
+ continue;
1794
+ }
1795
+ const classFullName = customData.classFullName;
1796
+ const sourceIdOfRelationshipInSource = customData?.sourceIdOfRelationship;
1797
+ const targetIdOfRelationshipInSource = customData?.targetIdOfRelationship;
1798
+ await this.processRelationshipDeleteOp(id, classFullName, sourceIdOfRelationshipInSource, targetIdOfRelationshipInSource);
1799
+ }
1800
+ }
1801
+ }
1773
1802
  /**
1774
1803
  * Reads all the changeset files in the private member of the transformer: _csFileProps and does two things with these changesets.
1775
1804
  * Finds the corresponding target entity for any deleted source entities and remaps the sourceId to the targetId.
@@ -1781,8 +1810,14 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1781
1810
  this.forEachTrackedElement((sourceElementId, targetElementId) => {
1782
1811
  this.context.remapElement(sourceElementId, targetElementId);
1783
1812
  });
1784
- if (this._csFileProps === undefined || this._csFileProps.length === 0)
1785
- return;
1813
+ this.exporter.addCustomChanges();
1814
+ if (this._csFileProps === undefined || this._csFileProps.length === 0) {
1815
+ if (this.exporter.sourceDbChanges?.isEmpty)
1816
+ return;
1817
+ // our sourcedbChanges aren't empty (probably due to someone adding custom changes), change our sourceChangeDataState to has-changes
1818
+ if (this._sourceChangeDataState === "no-changes")
1819
+ this._sourceChangeDataState = "has-changes";
1820
+ }
1786
1821
  const hasElementChangedCache = new Set();
1787
1822
  const relationshipECClassIdsToSkip = new Set();
1788
1823
  for await (const row of this.sourceDb.createQueryReader("SELECT ECInstanceId FROM ECDbMeta.ECClassDef where ECInstanceId IS (BisCore.ElementDrivesElement)")) {
@@ -1810,7 +1845,10 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1810
1845
  alreadyImportedModelInserts.add(targetModelId);
1811
1846
  });
1812
1847
  this._deletedSourceRelationshipData = new Map();
1813
- for (const csFile of this._csFileProps) {
1848
+ /** a map of element ids to this transformation scope's ESA data for that element, in case the ESA is deleted in the target */
1849
+ const elemIdToScopeEsa = new Map();
1850
+ const deleteIdsProcessed = new Set();
1851
+ for (const csFile of this._csFileProps ?? []) {
1814
1852
  const csReader = core_backend_1.SqliteChangesetReader.openFile({
1815
1853
  fileName: csFile.pathname,
1816
1854
  db: this.sourceDb,
@@ -1822,8 +1860,6 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1822
1860
  ecChangeUnifier.appendFrom(csAdaptor);
1823
1861
  }
1824
1862
  const changes = [...ecChangeUnifier.instances];
1825
- /** a map of element ids to this transformation scope's ESA data for that element, in case the ESA is deleted in the target */
1826
- const elemIdToScopeEsa = new Map();
1827
1863
  for (const change of changes) {
1828
1864
  if (change.ECClassId !== undefined &&
1829
1865
  relationshipECClassIdsToSkip.has(change.ECClassId))
@@ -1851,115 +1887,151 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1851
1887
  if (changeType !== "Deleted" ||
1852
1888
  relationshipECClassIdsToSkip.has(ecClassId))
1853
1889
  continue;
1854
- await this.processDeletedOp(change, elemIdToScopeEsa, relationshipECClassIds.has(ecClassId ?? ""), alreadyImportedElementInserts, alreadyImportedModelInserts);
1890
+ if (relationshipECClassIds.has(ecClassId)) {
1891
+ if (change.$meta?.classFullName === undefined) {
1892
+ core_bentley_1.Logger.logError(loggerCategory, "ClassFullName was not found for relationship when reading changes. Relationship delete will not propagate.", { relationshipId: change.ECInstanceId, ecClassId });
1893
+ continue;
1894
+ }
1895
+ if (change.SourceECInstanceId === undefined ||
1896
+ change.TargetECInstanceId === undefined) {
1897
+ core_bentley_1.Logger.logError(loggerCategory, "SourceECInstanceId or TargetECInstanceId was not found for relationship when reading changes. Relationship delete will not propagate.", {
1898
+ relationshipId: change.ECInstanceId,
1899
+ ecClassId,
1900
+ classFullName: change.$meta.classFullName,
1901
+ });
1902
+ continue;
1903
+ }
1904
+ await this.processRelationshipDeleteOp(change.ECInstanceId, change.$meta.classFullName, change.SourceECInstanceId, change.TargetECInstanceId);
1905
+ }
1906
+ else {
1907
+ await this.processElementDeleteOp(change.ECInstanceId, alreadyImportedElementInserts, alreadyImportedModelInserts, elemIdToScopeEsa, change.FederationGuid);
1908
+ }
1909
+ deleteIdsProcessed.add(change.ECInstanceId);
1855
1910
  }
1856
1911
  csReader.close();
1857
1912
  }
1913
+ await this.handleCustomChanges(hasElementChangedCache, deleteIdsProcessed);
1858
1914
  this._hasElementChangedCache = hasElementChangedCache;
1859
1915
  return;
1860
1916
  }
1917
+ /**
1918
+ * Helper function for processChangesets.
1919
+ * Populates the '_deletedSourceRelationshipData' map, whose key is the id of the relationship in the source and the value is an object used to find that relationship in the target.
1920
+ * @param changedInstanceId The id of the relationship that was deleted
1921
+ * @param classFullName classFullName of relationship
1922
+ * @param sourceIdOfRelationshipInSource the element Id acting as the source of the relationship in the sourceDb
1923
+ * @param targetIdOfRelationshipInSource the element Id acting as the target of the relationship in the sourceDb
1924
+ * @returns
1925
+ */
1926
+ async processRelationshipDeleteOp(changedInstanceId, classFullName, sourceIdOfRelationshipInSource, targetIdOfRelationshipInSource) {
1927
+ // we need a connected iModel with changes to remap elements with deletions
1928
+ const notConnectedModel = this.sourceDb.iTwinId === undefined;
1929
+ const noChanges = this.synchronizationVersion.index === this.sourceDb.changeset.index &&
1930
+ this.exporter.sourceDbChanges?.isEmpty;
1931
+ if (notConnectedModel || noChanges)
1932
+ return;
1933
+ const sourceIdOfRelationshipInTarget = await this.getTargetIdFromSourceId(sourceIdOfRelationshipInSource, true);
1934
+ const targetIdOfRelationshipInTarget = await this.getTargetIdFromSourceId(targetIdOfRelationshipInSource, true);
1935
+ if (sourceIdOfRelationshipInTarget && targetIdOfRelationshipInTarget) {
1936
+ this._deletedSourceRelationshipData.set(changedInstanceId, {
1937
+ classFullName,
1938
+ sourceIdInTarget: sourceIdOfRelationshipInTarget,
1939
+ targetIdInTarget: targetIdOfRelationshipInTarget,
1940
+ });
1941
+ }
1942
+ else if (this.sourceDb === this.provenanceSourceDb) {
1943
+ const relProvenance = this._queryProvenanceForRelationship(changedInstanceId, {
1944
+ classFullName,
1945
+ sourceId: sourceIdOfRelationshipInSource,
1946
+ targetId: targetIdOfRelationshipInSource,
1947
+ });
1948
+ if (relProvenance && relProvenance.relationshipId)
1949
+ this._deletedSourceRelationshipData.set(changedInstanceId, {
1950
+ classFullName,
1951
+ relId: relProvenance.relationshipId,
1952
+ provenanceAspectId: relProvenance.aspectId,
1953
+ });
1954
+ }
1955
+ }
1861
1956
  /**
1862
1957
  * Helper function for processChangesets. Remaps the id of element deleted found in the 'change' to an element in the targetDb.
1863
1958
  * @param change the change to process, must be of changeType "Deleted"
1864
1959
  * @param mapOfDeletedElemIdToScopeEsas a map of elementIds to changedECInstances (which are ESAs). the elementId is not the id of the esa itself, but the elementid that the esa was stored on before the esa's deletion.
1865
1960
  * All ESAs in this map are part of the transformer's scope / ESA data and are tracked in case the ESA is deleted in the target.
1866
- * @param isRelationship is relationship or not
1867
1961
  * @param alreadyImportedElementInserts used to handle entity recreation and not delete already handled element inserts.
1868
1962
  * @param alreadyImportedModelInserts used to handle entity recreation and not delete already handled model inserts.
1869
1963
  * @returns void
1870
1964
  */
1871
- async processDeletedOp(change, mapOfDeletedElemIdToScopeEsas, isRelationship, alreadyImportedElementInserts, alreadyImportedModelInserts) {
1965
+ async processElementDeleteOp(changedInstanceId, alreadyImportedElementInserts, alreadyImportedModelInserts, mapOfDeletedElemIdToScopeEsas, federationGuid) {
1872
1966
  // we need a connected iModel with changes to remap elements with deletions
1873
1967
  const notConnectedModel = this.sourceDb.iTwinId === undefined;
1874
- const noChanges = this.synchronizationVersion.index === this.sourceDb.changeset.index;
1968
+ const noChanges = this.synchronizationVersion.index === this.sourceDb.changeset.index &&
1969
+ this.exporter.sourceDbChanges?.isEmpty;
1875
1970
  if (notConnectedModel || noChanges)
1876
1971
  return;
1972
+ let targetId = await this.getTargetIdFromSourceId(changedInstanceId, false, mapOfDeletedElemIdToScopeEsas, federationGuid);
1973
+ if (targetId === undefined && this.sourceDb === this.provenanceSourceDb) {
1974
+ targetId = this._queryProvenanceForElement(changedInstanceId);
1975
+ }
1976
+ // since we are processing one changeset at a time, we can see local source deletes
1977
+ // of entities that were never synced and can be safely ignored
1978
+ const deletionNotInTarget = !targetId;
1979
+ if (deletionNotInTarget)
1980
+ return;
1981
+ this.context.remapElement(changedInstanceId, targetId);
1982
+ // If an entity insert and an entity delete both point to the same entity in target iModel, that means that entity was recreated.
1983
+ // In such case an entity update will be triggered and we no longer need to delete the entity.
1984
+ if (alreadyImportedElementInserts.has(targetId)) {
1985
+ this.exporter.sourceDbChanges?.element.deleteIds.delete(changedInstanceId);
1986
+ }
1987
+ if (alreadyImportedModelInserts.has(targetId)) {
1988
+ this.exporter.sourceDbChanges?.model.deleteIds.delete(changedInstanceId);
1989
+ }
1990
+ }
1991
+ /**
1992
+ * Find the corresponding id in the targetDb given a id from the sourceDb
1993
+ * @param id the id in the source that we want to find the target id for
1994
+ * @param isRelationship Changes the way we look for the federationGuid , if true we look for the federationGuid on the element itself, if false we expect it to be passed in because it was part of the ChangedECInstance.
1995
+ * Typically the source and targetIds of the relationship and not the relationshipId itself is passed to this function
1996
+ * @param mapOfDeletedElemIdToScopeEsas a map of elementIds to changedECInstances (which are ESAs). the elementId is not the id of the esa itself, but the elementid that the esa was stored on before the esa's deletion.
1997
+ * All ESAs in this map are part of the transformer's scope / ESA data and are tracked in case the ESA is deleted in the target.
1998
+ * @param federationGuid
1999
+ * @returns id of the corresponding entity in the targetDb or undefined if not found
2000
+ */
2001
+ async getTargetIdFromSourceId(id, isRelationship, mapOfDeletedElemIdToScopeEsas, federationGuid) {
1877
2002
  /**
1878
2003
  * if our ChangedECInstance is in the provenanceDb, then we can use the ids we find in the ChangedECInstance to query for ESAs.
1879
2004
  * This is because the ESAs are stored on an element Id thats present in the provenanceDb.
1880
2005
  */
1881
2006
  const changeDataInProvenanceDb = this.sourceDb === this.provenanceDb;
1882
- const getTargetIdFromSourceId = async (id) => {
1883
- let identifierValue;
1884
- let element;
1885
- if (isRelationship) {
1886
- element = this.sourceDb.elements.tryGetElement(id);
1887
- }
1888
- const fedGuid = isRelationship
1889
- ? element?.federationGuid
1890
- : change.FederationGuid;
1891
- if (changeDataInProvenanceDb) {
1892
- // TODO: clarify what happens if there are multiple (e.g. elements were merged)
1893
- for await (const row of this.sourceDb.createQueryReader("SELECT esa.Identifier FROM bis.ExternalSourceAspect esa WHERE Scope.Id=:scopeId AND Kind=:kind AND Element.Id=:relatedElementId LIMIT 1", core_common_1.QueryBinder.from([
1894
- this.targetScopeElementId,
1895
- core_backend_1.ExternalSourceAspect.Kind.Element,
1896
- id,
1897
- ]))) {
1898
- identifierValue = row.Identifier;
1899
- }
1900
- identifierValue =
1901
- identifierValue ?? mapOfDeletedElemIdToScopeEsas.get(id)?.Identifier;
1902
- }
1903
- // Check for targetId by an esa first
1904
- if (changeDataInProvenanceDb && identifierValue) {
1905
- const targetId = identifierValue;
1906
- return targetId;
1907
- }
1908
- // Check for targetId using sourceId's fedguid if we didn't find an esa.
1909
- if (fedGuid) {
1910
- const targetId = this._queryElemIdByFedGuid(this.targetDb, fedGuid);
1911
- return targetId;
1912
- }
1913
- return undefined;
1914
- };
1915
- const changedInstanceId = change.ECInstanceId;
2007
+ let identifierValue;
2008
+ let element;
1916
2009
  if (isRelationship) {
1917
- const sourceIdOfRelationshipInSource = change.SourceECInstanceId;
1918
- const targetIdOfRelationshipInSource = change.TargetECInstanceId;
1919
- const classFullName = change.$meta?.classFullName;
1920
- const sourceIdOfRelationshipInTarget = await getTargetIdFromSourceId(sourceIdOfRelationshipInSource);
1921
- const targetIdOfRelationshipInTarget = await getTargetIdFromSourceId(targetIdOfRelationshipInSource);
1922
- if (sourceIdOfRelationshipInTarget && targetIdOfRelationshipInTarget) {
1923
- this._deletedSourceRelationshipData.set(changedInstanceId, {
1924
- classFullName: classFullName ?? "",
1925
- sourceIdInTarget: sourceIdOfRelationshipInTarget,
1926
- targetIdInTarget: targetIdOfRelationshipInTarget,
1927
- });
1928
- }
1929
- else if (this.sourceDb === this.provenanceSourceDb) {
1930
- const relProvenance = this._queryProvenanceForRelationship(changedInstanceId, {
1931
- classFullName: classFullName ?? "",
1932
- sourceId: sourceIdOfRelationshipInSource,
1933
- targetId: targetIdOfRelationshipInSource,
1934
- });
1935
- if (relProvenance && relProvenance.relationshipId)
1936
- this._deletedSourceRelationshipData.set(changedInstanceId, {
1937
- classFullName: classFullName ?? "",
1938
- relId: relProvenance.relationshipId,
1939
- provenanceAspectId: relProvenance.aspectId,
1940
- });
1941
- }
2010
+ element = this.sourceDb.elements.tryGetElement(id);
1942
2011
  }
1943
- else {
1944
- let targetId = await getTargetIdFromSourceId(changedInstanceId);
1945
- if (targetId === undefined && this.sourceDb === this.provenanceSourceDb) {
1946
- targetId = this._queryProvenanceForElement(changedInstanceId);
1947
- }
1948
- // since we are processing one changeset at a time, we can see local source deletes
1949
- // of entities that were never synced and can be safely ignored
1950
- const deletionNotInTarget = !targetId;
1951
- if (deletionNotInTarget)
1952
- return;
1953
- this.context.remapElement(changedInstanceId, targetId);
1954
- // If an entity insert and an entity delete both point to the same entity in target iModel, that means that entity was recreated.
1955
- // In such case an entity update will be triggered and we no longer need to delete the entity.
1956
- if (alreadyImportedElementInserts.has(targetId)) {
1957
- this.exporter.sourceDbChanges?.element.deleteIds.delete(changedInstanceId);
1958
- }
1959
- if (alreadyImportedModelInserts.has(targetId)) {
1960
- this.exporter.sourceDbChanges?.model.deleteIds.delete(changedInstanceId);
2012
+ const fedGuid = isRelationship ? element?.federationGuid : federationGuid;
2013
+ // Check for targetId using sourceId's fedguid
2014
+ if (fedGuid) {
2015
+ const targetId = this._queryElemIdByFedGuid(this.targetDb, fedGuid);
2016
+ if (targetId !== undefined)
2017
+ return targetId;
2018
+ }
2019
+ // Check for targetId by esa
2020
+ if (changeDataInProvenanceDb) {
2021
+ // TODO: clarify what happens if there are multiple (e.g. elements were merged)
2022
+ for await (const row of this.sourceDb.createQueryReader("SELECT esa.Identifier FROM bis.ExternalSourceAspect esa WHERE Scope.Id=:scopeId AND Kind=:kind AND Element.Id=:relatedElementId LIMIT 1", core_common_1.QueryBinder.from([
2023
+ this.targetScopeElementId,
2024
+ core_backend_1.ExternalSourceAspect.Kind.Element,
2025
+ id,
2026
+ ]))) {
2027
+ identifierValue = row.Identifier;
1961
2028
  }
2029
+ identifierValue =
2030
+ identifierValue ?? mapOfDeletedElemIdToScopeEsas?.get(id)?.Identifier;
2031
+ if (identifierValue)
2032
+ return identifierValue;
1962
2033
  }
2034
+ return undefined;
1963
2035
  }
1964
2036
  async _tryInitChangesetData(args) {
1965
2037
  if (!args ||