@itwin/core-backend 4.0.0-dev.28 → 4.0.0-dev.32

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.
Files changed (244) hide show
  1. package/lib/cjs/AliCloudStorageService.d.ts +23 -23
  2. package/lib/cjs/AliCloudStorageService.js +71 -71
  3. package/lib/cjs/AliCloudStorageService.js.map +1 -1
  4. package/lib/cjs/BackendHubAccess.d.ts +224 -224
  5. package/lib/cjs/BackendHubAccess.js +41 -41
  6. package/lib/cjs/BackendHubAccess.js.map +1 -1
  7. package/lib/cjs/BackendLoggerCategory.d.ts +91 -91
  8. package/lib/cjs/BackendLoggerCategory.js +99 -99
  9. package/lib/cjs/BackendLoggerCategory.js.map +1 -1
  10. package/lib/cjs/BisCoreSchema.d.ts +21 -21
  11. package/lib/cjs/BisCoreSchema.js +60 -60
  12. package/lib/cjs/BisCoreSchema.js.map +1 -1
  13. package/lib/cjs/BriefcaseManager.d.ts +170 -170
  14. package/lib/cjs/BriefcaseManager.js +408 -408
  15. package/lib/cjs/BriefcaseManager.js.map +1 -1
  16. package/lib/cjs/Category.d.ts +153 -153
  17. package/lib/cjs/Category.js +243 -243
  18. package/lib/cjs/Category.js.map +1 -1
  19. package/lib/cjs/ChangeSummaryManager.d.ts +187 -187
  20. package/lib/cjs/ChangeSummaryManager.js +446 -446
  21. package/lib/cjs/ChangeSummaryManager.js.map +1 -1
  22. package/lib/cjs/ChangedElementsDb.d.ts +99 -99
  23. package/lib/cjs/ChangedElementsDb.js +165 -165
  24. package/lib/cjs/ChangedElementsDb.js.map +1 -1
  25. package/lib/cjs/ChangedElementsManager.d.ts +39 -39
  26. package/lib/cjs/ChangedElementsManager.js +88 -88
  27. package/lib/cjs/ChangedElementsManager.js.map +1 -1
  28. package/lib/cjs/CheckpointManager.d.ts +121 -121
  29. package/lib/cjs/CheckpointManager.js +348 -348
  30. package/lib/cjs/CheckpointManager.js.map +1 -1
  31. package/lib/cjs/ClassRegistry.d.ts +79 -79
  32. package/lib/cjs/ClassRegistry.js +249 -249
  33. package/lib/cjs/ClassRegistry.js.map +1 -1
  34. package/lib/cjs/CloudSqlite.d.ts +350 -350
  35. package/lib/cjs/CloudSqlite.js +153 -153
  36. package/lib/cjs/CloudSqlite.js.map +1 -1
  37. package/lib/cjs/CloudStorageBackend.d.ts +58 -58
  38. package/lib/cjs/CloudStorageBackend.js +170 -170
  39. package/lib/cjs/CloudStorageBackend.js.map +1 -1
  40. package/lib/cjs/CodeService.d.ts +396 -396
  41. package/lib/cjs/CodeService.js +63 -63
  42. package/lib/cjs/CodeService.js.map +1 -1
  43. package/lib/cjs/CodeSpecs.d.ts +55 -55
  44. package/lib/cjs/CodeSpecs.js +124 -124
  45. package/lib/cjs/CodeSpecs.js.map +1 -1
  46. package/lib/cjs/ConcurrentQuery.d.ts +13 -13
  47. package/lib/cjs/ConcurrentQuery.js +36 -36
  48. package/lib/cjs/ConcurrentQuery.js.map +1 -1
  49. package/lib/cjs/CustomViewState3dCreator.d.ts +21 -21
  50. package/lib/cjs/CustomViewState3dCreator.js +81 -81
  51. package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
  52. package/lib/cjs/DevTools.d.ts +73 -73
  53. package/lib/cjs/DevTools.js +156 -156
  54. package/lib/cjs/DevTools.js.map +1 -1
  55. package/lib/cjs/DisplayStyle.d.ts +106 -106
  56. package/lib/cjs/DisplayStyle.js +253 -253
  57. package/lib/cjs/DisplayStyle.js.map +1 -1
  58. package/lib/cjs/ECDb.d.ts +191 -191
  59. package/lib/cjs/ECDb.js +348 -348
  60. package/lib/cjs/ECDb.js.map +1 -1
  61. package/lib/cjs/ECSchemaXmlContext.d.ts +18 -18
  62. package/lib/cjs/ECSchemaXmlContext.js +41 -41
  63. package/lib/cjs/ECSchemaXmlContext.js.map +1 -1
  64. package/lib/cjs/ECSqlStatement.d.ts +473 -473
  65. package/lib/cjs/ECSqlStatement.js +791 -791
  66. package/lib/cjs/ECSqlStatement.js.map +1 -1
  67. package/lib/cjs/Element.d.ts +1109 -1109
  68. package/lib/cjs/Element.js +1419 -1419
  69. package/lib/cjs/Element.js.map +1 -1
  70. package/lib/cjs/ElementAspect.d.ts +179 -179
  71. package/lib/cjs/ElementAspect.js +211 -211
  72. package/lib/cjs/ElementAspect.js.map +1 -1
  73. package/lib/cjs/ElementGraphics.d.ts +9 -9
  74. package/lib/cjs/ElementGraphics.js +41 -41
  75. package/lib/cjs/ElementGraphics.js.map +1 -1
  76. package/lib/cjs/ElementTreeWalker.d.ts +162 -162
  77. package/lib/cjs/ElementTreeWalker.js +409 -409
  78. package/lib/cjs/ElementTreeWalker.js.map +1 -1
  79. package/lib/cjs/Entity.d.ts +106 -106
  80. package/lib/cjs/Entity.js +134 -134
  81. package/lib/cjs/Entity.js.map +1 -1
  82. package/lib/cjs/EntityReferences.d.ts +49 -49
  83. package/lib/cjs/EntityReferences.js +95 -95
  84. package/lib/cjs/EntityReferences.js.map +1 -1
  85. package/lib/cjs/ExportGraphics.d.ts +317 -317
  86. package/lib/cjs/ExportGraphics.js +208 -208
  87. package/lib/cjs/ExportGraphics.js.map +1 -1
  88. package/lib/cjs/ExternalSource.d.ts +96 -96
  89. package/lib/cjs/ExternalSource.js +131 -131
  90. package/lib/cjs/ExternalSource.js.map +1 -1
  91. package/lib/cjs/GeoCoordConfig.d.ts +19 -19
  92. package/lib/cjs/GeoCoordConfig.js +85 -85
  93. package/lib/cjs/GeoCoordConfig.js.map +1 -1
  94. package/lib/cjs/GeometrySummary.d.ts +4 -4
  95. package/lib/cjs/GeometrySummary.js +380 -380
  96. package/lib/cjs/GeometrySummary.js.map +1 -1
  97. package/lib/cjs/HubMock.d.ts +94 -94
  98. package/lib/cjs/HubMock.js +220 -220
  99. package/lib/cjs/HubMock.js.map +1 -1
  100. package/lib/cjs/IModelCloneContext.d.ts +8 -8
  101. package/lib/cjs/IModelCloneContext.js +15 -15
  102. package/lib/cjs/IModelCloneContext.js.map +1 -1
  103. package/lib/cjs/IModelDb.d.ts +1210 -1210
  104. package/lib/cjs/IModelDb.js +2377 -2377
  105. package/lib/cjs/IModelDb.js.map +1 -1
  106. package/lib/cjs/IModelElementCloneContext.d.ts +89 -89
  107. package/lib/cjs/IModelElementCloneContext.js +159 -159
  108. package/lib/cjs/IModelElementCloneContext.js.map +1 -1
  109. package/lib/cjs/IModelHost.d.ts +369 -369
  110. package/lib/cjs/IModelHost.js +488 -488
  111. package/lib/cjs/IModelHost.js.map +1 -1
  112. package/lib/cjs/IModelJsFs.d.ts +62 -62
  113. package/lib/cjs/IModelJsFs.js +139 -139
  114. package/lib/cjs/IModelJsFs.js.map +1 -1
  115. package/lib/cjs/IpcHost.d.ts +104 -104
  116. package/lib/cjs/IpcHost.js +276 -276
  117. package/lib/cjs/IpcHost.js.map +1 -1
  118. package/lib/cjs/LineStyle.d.ts +311 -311
  119. package/lib/cjs/LineStyle.js +295 -295
  120. package/lib/cjs/LineStyle.js.map +1 -1
  121. package/lib/cjs/LocalHub.d.ts +162 -162
  122. package/lib/cjs/LocalHub.js +580 -580
  123. package/lib/cjs/LocalHub.js.map +1 -1
  124. package/lib/cjs/LocalhostIpcHost.d.ts +20 -20
  125. package/lib/cjs/LocalhostIpcHost.js +79 -79
  126. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  127. package/lib/cjs/Material.d.ts +131 -131
  128. package/lib/cjs/Material.js +180 -180
  129. package/lib/cjs/Material.js.map +1 -1
  130. package/lib/cjs/Model.d.ts +392 -392
  131. package/lib/cjs/Model.js +485 -485
  132. package/lib/cjs/Model.js.map +1 -1
  133. package/lib/cjs/NativeAppStorage.d.ts +51 -51
  134. package/lib/cjs/NativeAppStorage.js +202 -202
  135. package/lib/cjs/NativeAppStorage.js.map +1 -1
  136. package/lib/cjs/NativeHost.d.ts +52 -52
  137. package/lib/cjs/NativeHost.js +160 -160
  138. package/lib/cjs/NativeHost.js.map +1 -1
  139. package/lib/cjs/NavigationRelationship.d.ts +156 -156
  140. package/lib/cjs/NavigationRelationship.js +225 -225
  141. package/lib/cjs/NavigationRelationship.js.map +1 -1
  142. package/lib/cjs/PromiseMemoizer.d.ts +51 -51
  143. package/lib/cjs/PromiseMemoizer.js +101 -101
  144. package/lib/cjs/PromiseMemoizer.js.map +1 -1
  145. package/lib/cjs/PropertyStore.d.ts +132 -132
  146. package/lib/cjs/PropertyStore.js +11 -11
  147. package/lib/cjs/PropertyStore.js.map +1 -1
  148. package/lib/cjs/Relationship.d.ts +416 -416
  149. package/lib/cjs/Relationship.js +494 -494
  150. package/lib/cjs/Relationship.js.map +1 -1
  151. package/lib/cjs/RpcBackend.d.ts +5 -5
  152. package/lib/cjs/RpcBackend.js +32 -32
  153. package/lib/cjs/RpcBackend.js.map +1 -1
  154. package/lib/cjs/SQLiteDb.d.ts +219 -219
  155. package/lib/cjs/SQLiteDb.js +212 -212
  156. package/lib/cjs/SQLiteDb.js.map +1 -1
  157. package/lib/cjs/Schema.d.ts +55 -55
  158. package/lib/cjs/Schema.js +83 -83
  159. package/lib/cjs/Schema.js.map +1 -1
  160. package/lib/cjs/ServerBasedLocks.d.ts +57 -57
  161. package/lib/cjs/ServerBasedLocks.js +168 -168
  162. package/lib/cjs/ServerBasedLocks.js.map +1 -1
  163. package/lib/cjs/SqliteStatement.d.ts +360 -360
  164. package/lib/cjs/SqliteStatement.js +586 -586
  165. package/lib/cjs/SqliteStatement.js.map +1 -1
  166. package/lib/cjs/Texture.d.ts +58 -58
  167. package/lib/cjs/Texture.js +82 -82
  168. package/lib/cjs/Texture.js.map +1 -1
  169. package/lib/cjs/TileStorage.d.ts +18 -18
  170. package/lib/cjs/TileStorage.js +87 -87
  171. package/lib/cjs/TileStorage.js.map +1 -1
  172. package/lib/cjs/TxnManager.d.ts +202 -202
  173. package/lib/cjs/TxnManager.js +356 -356
  174. package/lib/cjs/TxnManager.js.map +1 -1
  175. package/lib/cjs/ViewDefinition.d.ts +435 -439
  176. package/lib/cjs/ViewDefinition.d.ts.map +1 -1
  177. package/lib/cjs/ViewDefinition.js +646 -646
  178. package/lib/cjs/ViewDefinition.js.map +1 -1
  179. package/lib/cjs/ViewStateHydrator.d.ts +13 -13
  180. package/lib/cjs/ViewStateHydrator.js +103 -103
  181. package/lib/cjs/ViewStateHydrator.js.map +1 -1
  182. package/lib/cjs/assets/IModelChange.02.00.00.ecschema.xml +90 -90
  183. package/lib/cjs/assets/Settings/Schemas/Cloud.Schema.json +67 -67
  184. package/lib/cjs/assets/Settings/Schemas/Gcs.schema.json +31 -31
  185. package/lib/cjs/assets/Settings/Schemas/Workspace.Schema.json +52 -52
  186. package/lib/cjs/assets/Settings/backend.setting.json5 +138 -138
  187. package/lib/cjs/core-backend.d.ts +184 -184
  188. package/lib/cjs/core-backend.js +204 -204
  189. package/lib/cjs/core-backend.js.map +1 -1
  190. package/lib/cjs/domains/FunctionalElements.d.ts +101 -101
  191. package/lib/cjs/domains/FunctionalElements.js +145 -145
  192. package/lib/cjs/domains/FunctionalElements.js.map +1 -1
  193. package/lib/cjs/domains/FunctionalSchema.d.ts +13 -13
  194. package/lib/cjs/domains/FunctionalSchema.js +40 -40
  195. package/lib/cjs/domains/FunctionalSchema.js.map +1 -1
  196. package/lib/cjs/domains/GenericElements.d.ts +177 -177
  197. package/lib/cjs/domains/GenericElements.js +263 -263
  198. package/lib/cjs/domains/GenericElements.js.map +1 -1
  199. package/lib/cjs/domains/GenericSchema.d.ts +10 -10
  200. package/lib/cjs/domains/GenericSchema.js +28 -28
  201. package/lib/cjs/domains/GenericSchema.js.map +1 -1
  202. package/lib/cjs/rpc/multipart.d.ts +11 -11
  203. package/lib/cjs/rpc/multipart.js +71 -71
  204. package/lib/cjs/rpc/multipart.js.map +1 -1
  205. package/lib/cjs/rpc/tracing.d.ts +28 -28
  206. package/lib/cjs/rpc/tracing.js +73 -73
  207. package/lib/cjs/rpc/tracing.js.map +1 -1
  208. package/lib/cjs/rpc/web/logging.d.ts +9 -9
  209. package/lib/cjs/rpc/web/logging.js +43 -43
  210. package/lib/cjs/rpc/web/logging.js.map +1 -1
  211. package/lib/cjs/rpc/web/request.d.ts +6 -6
  212. package/lib/cjs/rpc/web/request.js +73 -73
  213. package/lib/cjs/rpc/web/request.js.map +1 -1
  214. package/lib/cjs/rpc/web/response.d.ts +6 -6
  215. package/lib/cjs/rpc/web/response.js +105 -105
  216. package/lib/cjs/rpc/web/response.js.map +1 -1
  217. package/lib/cjs/rpc-impl/DevToolsRpcImpl.d.ts +15 -15
  218. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js +32 -32
  219. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js.map +1 -1
  220. package/lib/cjs/rpc-impl/IModelReadRpcImpl.d.ts +47 -47
  221. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js +293 -293
  222. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
  223. package/lib/cjs/rpc-impl/IModelTileRpcImpl.d.ts +22 -22
  224. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js +202 -202
  225. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
  226. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.d.ts +36 -36
  227. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js +166 -166
  228. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
  229. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.d.ts +16 -16
  230. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js +42 -42
  231. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
  232. package/lib/cjs/rpc-impl/WipRpcImpl.d.ts +15 -15
  233. package/lib/cjs/rpc-impl/WipRpcImpl.js +37 -37
  234. package/lib/cjs/rpc-impl/WipRpcImpl.js.map +1 -1
  235. package/lib/cjs/workspace/Settings.d.ts +186 -186
  236. package/lib/cjs/workspace/Settings.js +154 -154
  237. package/lib/cjs/workspace/Settings.js.map +1 -1
  238. package/lib/cjs/workspace/SettingsSchemas.d.ts +75 -75
  239. package/lib/cjs/workspace/SettingsSchemas.js +190 -190
  240. package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
  241. package/lib/cjs/workspace/Workspace.d.ts +414 -414
  242. package/lib/cjs/workspace/Workspace.js +537 -537
  243. package/lib/cjs/workspace/Workspace.js.map +1 -1
  244. package/package.json +11 -11
@@ -1,2378 +1,2378 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module iModels
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.StandaloneDb = exports.SnapshotDb = exports.BriefcaseDb = exports.IModelDb = exports.BriefcaseLocalValue = void 0;
11
- const path_1 = require("path");
12
- const core_bentley_1 = require("@itwin/core-bentley");
13
- const core_common_1 = require("@itwin/core-common");
14
- const core_geometry_1 = require("@itwin/core-geometry");
15
- const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
16
- const BriefcaseManager_1 = require("./BriefcaseManager");
17
- const CheckpointManager_1 = require("./CheckpointManager");
18
- const ClassRegistry_1 = require("./ClassRegistry");
19
- const CodeService_1 = require("./CodeService");
20
- const CodeSpecs_1 = require("./CodeSpecs");
21
- const ConcurrentQuery_1 = require("./ConcurrentQuery");
22
- const ECSqlStatement_1 = require("./ECSqlStatement");
23
- const Element_1 = require("./Element");
24
- const ElementAspect_1 = require("./ElementAspect");
25
- const ElementGraphics_1 = require("./ElementGraphics");
26
- const GeoCoordConfig_1 = require("./GeoCoordConfig");
27
- const IModelHost_1 = require("./IModelHost");
28
- const IModelJsFs_1 = require("./IModelJsFs");
29
- const IpcHost_1 = require("./IpcHost");
30
- const Model_1 = require("./Model");
31
- const Relationship_1 = require("./Relationship");
32
- const ServerBasedLocks_1 = require("./ServerBasedLocks");
33
- const SqliteStatement_1 = require("./SqliteStatement");
34
- const TxnManager_1 = require("./TxnManager");
35
- const ViewDefinition_1 = require("./ViewDefinition");
36
- const Settings_1 = require("./workspace/Settings");
37
- const Workspace_1 = require("./workspace/Workspace");
38
- // spell:ignore fontid fontmap
39
- const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
40
- /** A null-implementation of LockControl that does not attempt to limit access between briefcases. This relies on change-merging to resolve conflicts. */
41
- class NoLocks {
42
- get isServerBased() { return false; }
43
- close() { }
44
- clearAllLocks() { }
45
- holdsExclusiveLock() { return false; }
46
- holdsSharedLock() { return false; }
47
- checkExclusiveLock() { }
48
- checkSharedLock() { }
49
- elementWasCreated() { }
50
- async acquireLocks() { }
51
- async releaseAllLocks() { }
52
- }
53
- /** @internal */
54
- var BriefcaseLocalValue;
55
- (function (BriefcaseLocalValue) {
56
- BriefcaseLocalValue["StandaloneEdit"] = "StandaloneEdit";
57
- BriefcaseLocalValue["NoLocking"] = "NoLocking";
58
- })(BriefcaseLocalValue = exports.BriefcaseLocalValue || (exports.BriefcaseLocalValue = {}));
59
- // function to open an briefcaseDb, perform an operation, and then close it.
60
- const withBriefcaseDb = async (briefcase, fn) => {
61
- const db = await BriefcaseDb.open(briefcase);
62
- try {
63
- return await fn(db);
64
- }
65
- finally {
66
- db.close();
67
- }
68
- };
69
- /**
70
- * Settings for an individual iModel. May only include settings priority for iModel, iTwin and organization.
71
- * @note if there is more than one iModel for an iTwin or organization, they will *each* hold a copy of the settings for those priorities.
72
- */
73
- class IModelSettings extends Settings_1.BaseSettings {
74
- verifyPriority(priority) {
75
- if (priority <= Settings_1.SettingsPriority.application)
76
- throw new Error("Use IModelHost.appSettings");
77
- }
78
- // attempt to resolve a setting from this iModel's settings, otherwise use appWorkspace's settings, otherwise defaultValue.
79
- resolveSetting(name, resolver, defaultValue) {
80
- return super.resolveSetting(name, resolver) ?? IModelHost_1.IModelHost.appWorkspace.settings.resolveSetting(name, resolver, defaultValue);
81
- }
82
- }
83
- /** An iModel database file. The database file can either be a briefcase or a snapshot.
84
- * @see [Accessing iModels]($docs/learning/backend/AccessingIModels.md)
85
- * @see [About IModelDb]($docs/learning/backend/IModelDb.md)
86
- * @public
87
- */
88
- class IModelDb extends core_common_1.IModel {
89
- /** @internal */
90
- constructor(args) {
91
- super({ ...args, iTwinId: args.nativeDb.getITwinId(), iModelId: args.nativeDb.getIModelId() });
92
- this._initialized = false;
93
- this.models = new IModelDb.Models(this);
94
- this.elements = new IModelDb.Elements(this);
95
- this.views = new IModelDb.Views(this);
96
- this.tiles = new IModelDb.Tiles(this);
97
- this._statementCache = new SqliteStatement_1.StatementCache();
98
- this._sqliteStatementCache = new SqliteStatement_1.StatementCache();
99
- this._snaps = new Map();
100
- /** @internal */
101
- this._locks = new NoLocks();
102
- /** Event called after a changeset is applied to this IModelDb. */
103
- this.onChangesetApplied = new core_bentley_1.BeEvent();
104
- /** Event called when the iModel is about to be closed. */
105
- this.onBeforeClose = new core_bentley_1.BeEvent();
106
- this._nativeDb = args.nativeDb;
107
- this.nativeDb.setIModelDb(this);
108
- this.loadSettingDictionaries();
109
- GeoCoordConfig_1.GeoCoordConfig.loadForImodel(this.workspace.settings); // load gcs data specified by iModel's settings dictionaries, must be done before calling initializeIModelDb
110
- this.initializeIModelDb();
111
- IModelDb._openDbs.set(this._fileKey, this);
112
- if (undefined === IModelDb._shutdownListener) { // the first time we create an IModelDb, add a listener to close any orphan files at shutdown.
113
- IModelDb._shutdownListener = IModelHost_1.IModelHost.onBeforeShutdown.addListener(() => {
114
- IModelDb._openDbs.forEach((db) => {
115
- try {
116
- db.abandonChanges();
117
- db.close();
118
- }
119
- catch { }
120
- });
121
- });
122
- }
123
- }
124
- /** @alpha */
125
- get codeService() { return this._codeService; }
126
- /**
127
- * Get the [[LockControl]] for this iModel.
128
- * @beta
129
- */
130
- get locks() { return this._locks; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
131
- /**
132
- * Get the [[Workspace]] for this iModel.
133
- * @beta
134
- */
135
- get workspace() {
136
- if (undefined === this._workspace)
137
- this._workspace = new Workspace_1.ITwinWorkspace(new IModelSettings());
138
- return this._workspace;
139
- }
140
- /** Acquire the exclusive schema lock on this iModel.
141
- * > Note: To acquire the schema lock, all other briefcases must first release *all* their locks. No other briefcases
142
- * will be able to acquire *any* locks while the schema lock is held.
143
- */
144
- async acquireSchemaLock() {
145
- return this.locks.acquireLocks({ exclusive: core_common_1.IModel.repositoryModelId });
146
- }
147
- /** determine whether the schema lock is currently held for this iModel. */
148
- get holdsSchemaLock() {
149
- return this.locks.holdsExclusiveLock(core_common_1.IModel.repositoryModelId);
150
- }
151
- /** @internal */
152
- notifyChangesetApplied() {
153
- this.changeset = this.nativeDb.getCurrentChangeset();
154
- this.onChangesetApplied.raiseEvent();
155
- }
156
- get fontMap() {
157
- return this._fontMap ?? (this._fontMap = new core_common_1.FontMap(this.nativeDb.readFontMap()));
158
- }
159
- /** @internal */
160
- clearFontMap() {
161
- this._fontMap = undefined;
162
- }
163
- /**
164
- * Add a new font name/type to the FontMap for this iModel and return its FontId.
165
- * @param name The name of the font to add
166
- * @param type The type of the font. Default is TrueType.
167
- * @returns The FontId for the newly added font. If a font by that name/type already exists, this method does not fail, it returns the existing Id.
168
- * @see [FontId and FontMap]($docs/learning/backend/Fonts.md#fontid-and-fontmap)
169
- * @beta
170
- */
171
- addNewFont(name, type) {
172
- this.locks.checkExclusiveLock(core_common_1.IModel.repositoryModelId, "schema", "addNewFont");
173
- this.clearFontMap();
174
- return this.nativeDb.addNewFont({ name, type: type ?? core_common_1.FontType.TrueType });
175
- }
176
- /** Check if this iModel has been opened read-only or not. */
177
- get isReadonly() { return this.openMode === core_bentley_1.OpenMode.Readonly; }
178
- /** The Guid that identifies this iModel. */
179
- get iModelId() {
180
- (0, core_bentley_1.assert)(undefined !== super.iModelId);
181
- return super.iModelId;
182
- } // GuidString | undefined for the IModel superclass, but required for all IModelDb subclasses
183
- /** @internal*/
184
- get nativeDb() { return this._nativeDb; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
185
- /** Get the full path fileName of this iModelDb
186
- * @note this member is only valid while the iModel is opened.
187
- */
188
- get pathName() { return this.nativeDb.getFilePath(); }
189
- /** Close this IModel, if it is currently open. */
190
- close() {
191
- if (!this.isOpen)
192
- return; // don't continue if already closed
193
- this.beforeClose();
194
- IModelDb._openDbs.delete(this._fileKey);
195
- this._workspace?.close();
196
- this.locks.close();
197
- this._locks = undefined;
198
- this._codeService?.close();
199
- this._codeService = undefined;
200
- this.nativeDb.closeIModel();
201
- this._nativeDb = undefined; // the underlying nativeDb has been freed by closeIModel
202
- }
203
- /** @internal */
204
- async refreshContainerSas(_userAccessToken) { }
205
- /**
206
- * Called by derived classes before closing the connection
207
- * @internal
208
- */
209
- beforeClose() {
210
- this.onBeforeClose.raiseEvent();
211
- this.clearCaches();
212
- }
213
- /** @internal */
214
- initializeIModelDb() {
215
- const props = this.nativeDb.getIModelProps();
216
- super.initialize(props.rootSubject.name, props);
217
- if (this._initialized)
218
- return;
219
- this._initialized = true;
220
- const db = this.isBriefcaseDb() ? this : undefined;
221
- if (!db || !IpcHost_1.IpcHost.isValid)
222
- return;
223
- db.onNameChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyIModelNameChanged", db.name));
224
- db.onRootSubjectChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyRootSubjectChanged", db.rootSubject));
225
- db.onProjectExtentsChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyProjectExtentsChanged", db.projectExtents.toJSON()));
226
- db.onGlobalOriginChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyGlobalOriginChanged", db.globalOrigin.toJSON()));
227
- db.onEcefLocationChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyEcefLocationChanged", db.ecefLocation?.toJSON()));
228
- db.onGeographicCoordinateSystemChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyGeographicCoordinateSystemChanged", db.geographicCoordinateSystem?.toJSON()));
229
- }
230
- /** Returns true if this is a BriefcaseDb
231
- * @see [[BriefcaseDb.open]]
232
- */
233
- get isBriefcase() { return false; }
234
- /** Type guard for instanceof [[BriefcaseDb]] */
235
- isBriefcaseDb() { return this.isBriefcase; }
236
- /** Returns true if this is a SnapshotDb
237
- * @see [[SnapshotDb.open]]
238
- */
239
- get isSnapshot() { return false; }
240
- /** Type guard for instanceof [[SnapshotDb]] */
241
- isSnapshotDb() { return this.isSnapshot; }
242
- /** Returns true if this is a *standalone* iModel
243
- * @see [[StandaloneDb.open]]
244
- * @internal
245
- */
246
- get isStandalone() { return false; }
247
- /** Type guard for instanceof [[StandaloneDb]]
248
- * @internal
249
- */
250
- isStandaloneDb() { return this.isStandalone; }
251
- /** Return `true` if the underlying nativeDb is open and valid.
252
- * @internal
253
- */
254
- get isOpen() { return undefined !== this.nativeDb; }
255
- /** Get the briefcase Id of this iModel */
256
- getBriefcaseId() { return this.isOpen ? this.nativeDb.getBriefcaseId() : core_common_1.BriefcaseIdValue.Illegal; }
257
- /**
258
- * Use a prepared ECSQL statement, potentially from the statement cache. If the requested statement doesn't exist
259
- * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
260
- * in the statement cache so it can be reused in the future. Use this method for ECSQL statements that will be
261
- * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
262
- * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withStatement]].
263
- * @param sql The SQLite SQL statement to execute
264
- * @param callback the callback to invoke on the prepared statement
265
- * @param logErrors Determines if error will be logged if statement fail to prepare
266
- * @returns the value returned by `callback`.
267
- * @see [[withStatement]]
268
- * @public
269
- */
270
- withPreparedStatement(ecsql, callback, logErrors = true) {
271
- const stmt = this._statementCache.findAndRemove(ecsql) ?? this.prepareStatement(ecsql, logErrors);
272
- const release = () => this._statementCache.addOrDispose(stmt);
273
- try {
274
- const val = callback(stmt);
275
- if (val instanceof Promise) {
276
- val.then(release, release);
277
- }
278
- else {
279
- release();
280
- }
281
- return val;
282
- }
283
- catch (err) {
284
- release();
285
- throw err;
286
- }
287
- }
288
- /**
289
- * Prepared and execute a callback on an ECSQL statement. After the callback completes the statement is disposed.
290
- * Use this method for ECSQL statements are either not expected to be reused, or are not expensive to prepare.
291
- * For statements that will be reused often, instead use [[withPreparedStatement]].
292
- * @param sql The SQLite SQL statement to execute
293
- * @param callback the callback to invoke on the prepared statement
294
- * @param logErrors Determines if error will be logged if statement fail to prepare
295
- * @returns the value returned by `callback`.
296
- * @see [[withPreparedStatement]]
297
- * @public
298
- */
299
- withStatement(ecsql, callback, logErrors = true) {
300
- const stmt = this.prepareStatement(ecsql, logErrors);
301
- const release = () => stmt.dispose();
302
- try {
303
- const val = callback(stmt);
304
- if (val instanceof Promise) {
305
- val.then(release, release);
306
- }
307
- else {
308
- release();
309
- }
310
- return val;
311
- }
312
- catch (err) {
313
- release();
314
- throw err;
315
- }
316
- }
317
- /** Allow to execute query and read results along with meta data. The result are streamed.
318
- * @param params The values to bind to the parameters (if the ECSQL has any).
319
- * @param config Allow to specify certain flags which control how query is executed.
320
- * @returns Returns *ECSqlQueryReader* which help iterate over result set and also give access to meta data.
321
- * @beta
322
- * */
323
- createQueryReader(ecsql, params, config) {
324
- if (!this._nativeDb || !this._nativeDb.isOpen()) {
325
- throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "db not open");
326
- }
327
- const executor = {
328
- execute: async (request) => {
329
- return ConcurrentQuery_1.ConcurrentQuery.executeQueryRequest(this.nativeDb, request);
330
- },
331
- };
332
- return new core_common_1.ECSqlReader(executor, ecsql, params, config);
333
- }
334
- /** Execute a query and stream its results
335
- * The result of the query is async iterator over the rows. The iterator will get next page automatically once rows in current page has been read.
336
- * [ECSQL row]($docs/learning/ECSQLRowFormat).
337
- *
338
- * See also:
339
- * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
340
- * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
341
- *
342
- * @param ecsql The ECSQL statement to execute
343
- * @param params The values to bind to the parameters (if the ECSQL has any).
344
- * @param options Allow to specify certain flags which control how query is executed.
345
- * @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
346
- * See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
347
- * @throws [IModelError]($common) If there was any error while submitting, preparing or stepping into query
348
- */
349
- async *query(ecsql, params, options) {
350
- const builder = new core_common_1.QueryOptionsBuilder(options);
351
- const reader = this.createQueryReader(ecsql, params, builder.getOptions());
352
- while (await reader.step())
353
- yield reader.formatCurrentRow();
354
- }
355
- /** Compute number of rows that would be returned by the ECSQL.
356
- *
357
- * See also:
358
- * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
359
- * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
360
- *
361
- * @param ecsql The ECSQL statement to execute
362
- * @param params The values to bind to the parameters (if the ECSQL has any).
363
- * See "[iTwin.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
364
- * @returns Return row count.
365
- * @throws [IModelError]($common) If the statement is invalid
366
- */
367
- async queryRowCount(ecsql, params) {
368
- for await (const row of this.query(`select count(*) from (${ecsql})`, params)) {
369
- return row[0];
370
- }
371
- throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "Failed to get row count");
372
- }
373
- /** Cancel any previous query with same token and run execute the current specified query.
374
- * The result of the query is async iterator over the rows. The iterator will get next page automatically once rows in current page has been read.
375
- * [ECSQL row]($docs/learning/ECSQLRowFormat).
376
- *
377
- * See also:
378
- * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
379
- * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
380
- *
381
- * @param ecsql The ECSQL statement to execute
382
- * @param token None empty restart token. The previous query with same token would be cancelled. This would cause
383
- * exception which user code must handle.
384
- * @param params The values to bind to the parameters (if the ECSQL has any).
385
- * @param options Allow to specify certain flags which control how query is executed.
386
- * @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
387
- * See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
388
- * @throws [IModelError]($common) If there was any error while submitting, preparing or stepping into query
389
- */
390
- async *restartQuery(token, ecsql, params, options) {
391
- for await (const row of this.query(ecsql, params, new core_common_1.QueryOptionsBuilder(options).setRestartToken(token).getOptions())) {
392
- yield row;
393
- }
394
- }
395
- /**
396
- * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist
397
- * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
398
- * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be
399
- * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
400
- * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].
401
- * @param sql The SQLite SQL statement to execute
402
- * @param callback the callback to invoke on the prepared statement
403
- * @param logErrors Determine if errors are logged or not
404
- * @returns the value returned by `callback`.
405
- * @see [[withPreparedStatement]]
406
- * @public
407
- */
408
- withPreparedSqliteStatement(sql, callback, logErrors = true) {
409
- const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql, logErrors);
410
- const release = () => this._sqliteStatementCache.addOrDispose(stmt);
411
- try {
412
- const val = callback(stmt);
413
- if (val instanceof Promise) {
414
- val.then(release, release);
415
- }
416
- else {
417
- release();
418
- }
419
- return val;
420
- }
421
- catch (err) {
422
- release();
423
- throw err;
424
- }
425
- }
426
- /**
427
- * Prepared and execute a callback on a SQL statement. After the callback completes the statement is disposed.
428
- * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.
429
- * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].
430
- * @param sql The SQLite SQL statement to execute
431
- * @param callback the callback to invoke on the prepared statement
432
- * @param logErrors Determine if errors are logged or not
433
- * @returns the value returned by `callback`.
434
- * @public
435
- */
436
- withSqliteStatement(sql, callback, logErrors = true) {
437
- const stmt = this.prepareSqliteStatement(sql, logErrors);
438
- const release = () => stmt.dispose();
439
- try {
440
- const val = callback(stmt);
441
- if (val instanceof Promise) {
442
- val.then(release, release);
443
- }
444
- else {
445
- release();
446
- }
447
- return val;
448
- }
449
- catch (err) {
450
- release();
451
- throw err;
452
- }
453
- }
454
- /** Prepare an SQL statement.
455
- * @param sql The SQL statement to prepare
456
- * @throws [[IModelError]] if there is a problem preparing the statement.
457
- * @internal
458
- */
459
- prepareSqliteStatement(sql, logErrors = true) {
460
- const stmt = new SqliteStatement_1.SqliteStatement(sql);
461
- stmt.prepare(this.nativeDb, logErrors);
462
- return stmt;
463
- }
464
- /**
465
- * queries the BisCore.SubCategory table for the entries that are children of the passed categoryIds
466
- * @param categoryIds categoryIds to query
467
- * @returns array of SubCategoryResultRow
468
- * @internal
469
- */
470
- async querySubCategories(categoryIds) {
471
- const result = [];
472
- const where = [...categoryIds].join(",");
473
- const query = `SELECT ECInstanceId as id, Parent.Id as parentId, Properties as appearance FROM BisCore.SubCategory WHERE Parent.Id IN (${where})`;
474
- try {
475
- for await (const row of this.query(query, undefined, { rowFormat: core_common_1.QueryRowFormat.UseJsPropertyNames })) {
476
- result.push(row);
477
- }
478
- }
479
- catch {
480
- // We can ignore the error here, and just return whatever we were able to query.
481
- }
482
- return result;
483
- }
484
- /** Query for a set of entity ids, given an EntityQueryParams
485
- * @param params The query parameters. The `limit` and `offset` members should be used to page results.
486
- * @returns an Id64Set with results of query
487
- * @throws [[IModelError]] if the generated statement is invalid or [IModelDb.maxLimit]($backend) exceeded when collecting ids.
488
- *
489
- * *Example:*
490
- * ``` ts
491
- * [[include:ECSQL-backend-queries.select-element-by-code-value-using-queryEntityIds]]
492
- * ```
493
- */
494
- queryEntityIds(params) {
495
- let sql = "SELECT ECInstanceId FROM ";
496
- if (params.only)
497
- sql += "ONLY ";
498
- sql += params.from;
499
- if (params.where)
500
- sql += ` WHERE ${params.where}`;
501
- if (params.orderBy)
502
- sql += ` ORDER BY ${params.orderBy}`;
503
- if (typeof params.limit === "number" && params.limit > 0)
504
- sql += ` LIMIT ${params.limit}`;
505
- if (typeof params.offset === "number" && params.offset > 0)
506
- sql += ` OFFSET ${params.offset}`;
507
- const ids = new Set();
508
- this.withPreparedStatement(sql, (stmt) => {
509
- if (params.bindings)
510
- stmt.bindValues(params.bindings);
511
- for (const row of stmt) {
512
- if (row.id !== undefined) {
513
- ids.add(row.id);
514
- if (ids.size > IModelDb.maxLimit) {
515
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Max LIMIT exceeded in SELECT statement");
516
- }
517
- }
518
- }
519
- });
520
- return ids;
521
- }
522
- /** Clear all in-memory caches held in this IModelDb. */
523
- clearCaches() {
524
- this._statementCache.clear();
525
- this._sqliteStatementCache.clear();
526
- }
527
- /** Update the project extents for this iModel.
528
- * <p><em>Example:</em>
529
- * ``` ts
530
- * [[include:IModelDb.updateProjectExtents]]
531
- * ```
532
- */
533
- updateProjectExtents(newExtents) {
534
- this.projectExtents = newExtents;
535
- this.updateIModelProps();
536
- }
537
- /** Compute an appropriate project extents for this iModel based on the ranges of all spatial elements.
538
- * Typically, the result is simply the union of the ranges of all spatial elements. However, the algorithm also detects "outlier elements",
539
- * whose placements locate them so far from the rest of the spatial geometry that they are considered statistically insignificant. The
540
- * range of an outlier element does not contribute to the computed extents.
541
- * @param options Specifies the level of detail desired in the return value.
542
- * @returns the computed extents.
543
- * @note This method does not modify the IModel's stored project extents. @see [[updateProjectExtents]].
544
- */
545
- computeProjectExtents(options) {
546
- const wantFullExtents = true === options?.reportExtentsWithOutliers;
547
- const wantOutliers = true === options?.reportOutliers;
548
- const result = this.nativeDb.computeProjectExtents(wantFullExtents, wantOutliers);
549
- return {
550
- extents: core_geometry_1.Range3d.fromJSON(result.extents),
551
- extentsWithOutliers: result.fullExtents ? core_geometry_1.Range3d.fromJSON(result.fullExtents) : undefined,
552
- outliers: result.outliers,
553
- };
554
- }
555
- /** Update the [EcefLocation]($docs/learning/glossary#eceflocation) of this iModel. */
556
- updateEcefLocation(ecef) {
557
- this.setEcefLocation(ecef);
558
- this.updateIModelProps();
559
- }
560
- /** Update the IModelProps of this iModel in the database. */
561
- updateIModelProps() {
562
- this.nativeDb.updateIModelProps(this.toJSON());
563
- }
564
- /** Commit pending changes to this iModel.
565
- * @param description Optional description of the changes
566
- * @throws [[IModelError]] if there is a problem saving changes or if there are pending, un-processed lock or code requests.
567
- */
568
- saveChanges(description) {
569
- if (this.openMode === core_bentley_1.OpenMode.Readonly)
570
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ReadOnly, "IModelDb was opened read-only");
571
- const stat = this.nativeDb.saveChanges(description);
572
- if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat)
573
- throw new core_common_1.IModelError(stat, `Could not save changes (${description})`);
574
- }
575
- /** Abandon pending changes in this iModel. */
576
- abandonChanges() {
577
- this.nativeDb.abandonChanges();
578
- }
579
- /**
580
- * Save all changes and perform a [checkpoint](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) on this IModelDb.
581
- * This ensures that all changes to the database since it was opened are saved to its file and the WAL file is truncated.
582
- * @note Checkpoint automatically happens when IModelDbs are closed. However, the checkpoint
583
- * operation itself can take some time. It may be useful to call this method prior to closing so that the checkpoint "penalty" is paid earlier.
584
- * @note Another use for this function is to permit the file to be copied while it is open for write. iModel files should
585
- * rarely be copied, and even less so while they're opened. But this scenario is sometimes encountered for tests.
586
- */
587
- performCheckpoint() {
588
- if (!this.isReadonly) {
589
- this.saveChanges();
590
- this.nativeDb.performCheckpoint();
591
- }
592
- }
593
- /** @internal */
594
- reverseTxns(numOperations) {
595
- return this.nativeDb.reverseTxns(numOperations);
596
- }
597
- /** @internal */
598
- reinstateTxn() {
599
- return this.nativeDb.reinstateTxn();
600
- }
601
- /** @internal */
602
- restartTxnSession() {
603
- return this.nativeDb.restartTxnSession();
604
- }
605
- /** Import an ECSchema. On success, the schema definition is stored in the iModel.
606
- * This method is asynchronous (must be awaited) because, in the case where this IModelDb is a briefcase, this method first obtains the schema lock from the iModel server.
607
- * You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
608
- * @param schemaFileName array of Full paths to ECSchema.xml files to be imported.
609
- * @param {SchemaImportOptions} options - options during schema import.
610
- * @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
611
- * @note Changes are saved if importSchemas is successful and abandoned if not successful.
612
- * @see querySchemaVersion
613
- */
614
- async importSchemas(schemaFileNames, options) {
615
- if (this.nativeDb.getITwinId() !== core_bentley_1.Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
616
- await this.acquireSchemaLock();
617
- const maybeCustomNativeContext = options?.ecSchemaXmlContext?.nativeContext;
618
- const nativeImportOptions = {
619
- schemaLockHeld: true,
620
- ecSchemaXmlContext: maybeCustomNativeContext,
621
- };
622
- const stat = this.nativeDb.importSchemas(schemaFileNames, nativeImportOptions);
623
- if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat) {
624
- throw new core_common_1.IModelError(stat, "Error importing schema");
625
- }
626
- this.clearCaches();
627
- }
628
- /** Import ECSchema(s) serialized to XML. On success, the schema definition is stored in the iModel.
629
- * This method is asynchronous (must be awaited) because, in the case where this IModelDb is a briefcase, this method first obtains the schema lock from the iModel server.
630
- * You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
631
- * @param serializedXmlSchemas The xml string(s) created from a serialized ECSchema.
632
- * @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
633
- * @note Changes are saved if importSchemaStrings is successful and abandoned if not successful.
634
- * @see querySchemaVersion
635
- * @alpha
636
- */
637
- async importSchemaStrings(serializedXmlSchemas) {
638
- if (this.iTwinId && this.iTwinId !== core_bentley_1.Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
639
- await this.acquireSchemaLock();
640
- const stat = this.nativeDb.importXmlSchemas(serializedXmlSchemas, { schemaLockHeld: true });
641
- if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat)
642
- throw new core_common_1.IModelError(stat, "Error importing schema");
643
- this.clearCaches();
644
- }
645
- /** Find an opened instance of any subclass of IModelDb, by filename
646
- * @note this method returns an IModelDb if the filename is open for *any* subclass of IModelDb
647
- */
648
- static findByFilename(fileName) {
649
- for (const entry of this._openDbs) {
650
- if (entry[1].pathName === fileName)
651
- return entry[1];
652
- }
653
- return undefined;
654
- }
655
- /** Find an open IModelDb by its key.
656
- * @note This method is mainly for use by RPC implementations.
657
- * @throws [[IModelNotFoundResponse]] if an open IModelDb matching the key is not found.
658
- * @see [IModel.key]($common)
659
- */
660
- static findByKey(key) {
661
- const iModelDb = this.tryFindByKey(key);
662
- if (undefined === iModelDb)
663
- throw new core_common_1.IModelNotFoundResponse(); // a very specific status for the RpcManager
664
- return iModelDb;
665
- }
666
- /** Attempt to find an open IModelDb by key.
667
- * @returns The matching IModelDb or `undefined`.
668
- */
669
- static tryFindByKey(key) {
670
- return this._openDbs.get(key);
671
- }
672
- /** @internal */
673
- static openDgnDb(file, openMode, upgradeOptions, props) {
674
- file.key = file.key ?? core_bentley_1.Guid.createValue();
675
- if (this.tryFindByKey(file.key))
676
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.AlreadyOpen, `key [${file.key}] for file [${file.path}] is already in use`);
677
- const isUpgradeRequested = upgradeOptions?.domain === core_common_1.DomainOptions.Upgrade || upgradeOptions?.profile === core_common_1.ProfileOptions.Upgrade;
678
- if (isUpgradeRequested && openMode !== core_bentley_1.OpenMode.ReadWrite)
679
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.UpgradeFailed, "Cannot upgrade a Readonly Db");
680
- try {
681
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
682
- nativeDb.openIModel(file.path, openMode, upgradeOptions, props, props?.container);
683
- return nativeDb;
684
- }
685
- catch (err) {
686
- throw new core_common_1.IModelError(err.errorNumber, `${err.message}, ${file.path}`);
687
- }
688
- }
689
- /**
690
- * Determines if the schemas in the Db must or can be upgraded by comparing them with those included in the
691
- * current version of the software.
692
- * @param filePath Full name of the briefcase including path
693
- * @param forReadWrite Pass true if validating for read-write scenarios - note that the schema version requirements
694
- * for opening the DgnDb read-write is more stringent than when opening the database read-only
695
- * @throws [[IModelError]] If the Db was in an invalid state and that causes a problem with validating schemas
696
- * @see [[BriefcaseDb.upgradeSchemas]] or [[StandaloneDb.upgradeSchemas]]
697
- * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
698
- */
699
- static validateSchemas(filePath, forReadWrite) {
700
- const openMode = forReadWrite ? core_bentley_1.OpenMode.ReadWrite : core_bentley_1.OpenMode.Readonly;
701
- const file = { path: filePath };
702
- let result = core_bentley_1.DbResult.BE_SQLITE_OK;
703
- try {
704
- const upgradeOptions = {
705
- domain: core_common_1.DomainOptions.CheckRecommendedUpgrades,
706
- };
707
- const nativeDb = this.openDgnDb(file, openMode, upgradeOptions);
708
- nativeDb.closeIModel();
709
- }
710
- catch (err) {
711
- result = err.errorNumber;
712
- }
713
- let schemaState = core_common_1.SchemaState.UpToDate;
714
- switch (result) {
715
- case core_bentley_1.DbResult.BE_SQLITE_OK:
716
- schemaState = core_common_1.SchemaState.UpToDate;
717
- break;
718
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooOld:
719
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooOldForReadWrite:
720
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaTooOld:
721
- schemaState = core_common_1.SchemaState.TooOld;
722
- break;
723
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooNew:
724
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooNewForReadWrite:
725
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaTooNew:
726
- schemaState = core_common_1.SchemaState.TooNew;
727
- break;
728
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaUpgradeRecommended:
729
- schemaState = core_common_1.SchemaState.UpgradeRecommended;
730
- break;
731
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaUpgradeRequired:
732
- schemaState = core_common_1.SchemaState.UpgradeRequired;
733
- break;
734
- case core_bentley_1.DbResult.BE_SQLITE_ERROR_InvalidProfileVersion:
735
- throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR_InvalidProfileVersion, "The profile of the Db is invalid. Cannot upgrade or open the Db.");
736
- default:
737
- throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "Error validating schemas. Cannot upgrade or open the Db.");
738
- }
739
- return schemaState;
740
- }
741
- /** Get the ClassMetaDataRegistry for this iModel.
742
- * @internal
743
- */
744
- get classMetaDataRegistry() {
745
- if (this._classMetaDataRegistry === undefined)
746
- this._classMetaDataRegistry = new ClassRegistry_1.MetaDataRegistry();
747
- return this._classMetaDataRegistry;
748
- }
749
- /** Get the linkTableRelationships for this IModel */
750
- get relationships() {
751
- return this._relationships || (this._relationships = new Relationship_1.Relationships(this));
752
- }
753
- /** Get the CodeSpecs in this IModel. */
754
- get codeSpecs() {
755
- return (this._codeSpecs !== undefined) ? this._codeSpecs : (this._codeSpecs = new CodeSpecs_1.CodeSpecs(this));
756
- }
757
- /** @internal */
758
- insertCodeSpec(codeSpec) {
759
- return this.nativeDb.insertCodeSpec(codeSpec.name, codeSpec.properties); // TODO: Remove "as any" when NativeLibrary.ts is updated so "spec" isn't marked as required
760
- }
761
- /** Prepare an ECSQL statement.
762
- * @param sql The ECSQL statement to prepare
763
- * @param logErrors Determines if error will be logged if statement fail to prepare
764
- * @throws [[IModelError]] if there is a problem preparing the statement.
765
- */
766
- prepareStatement(sql, logErrors = true) {
767
- const stmt = new ECSqlStatement_1.ECSqlStatement();
768
- stmt.prepare(this.nativeDb, sql, logErrors);
769
- return stmt;
770
- }
771
- /** Prepare an ECSQL statement.
772
- * @param sql The ECSQL statement to prepare
773
- * @returns `undefined` if there is a problem preparing the statement.
774
- */
775
- tryPrepareStatement(sql) {
776
- const statement = new ECSqlStatement_1.ECSqlStatement();
777
- const result = statement.tryPrepare(this.nativeDb, sql);
778
- return core_bentley_1.DbResult.BE_SQLITE_OK === result.status ? statement : undefined;
779
- }
780
- /** Construct an entity (Element or Model) from an iModel.
781
- * @throws [[IModelError]] if the entity cannot be constructed.
782
- */
783
- constructEntity(props) {
784
- const jsClass = this.getJsClass(props.classFullName);
785
- return new jsClass(props, this);
786
- }
787
- /** Get the JavaScript class that handles a given entity class. */
788
- getJsClass(classFullName) {
789
- try {
790
- return ClassRegistry_1.ClassRegistry.getClass(classFullName, this);
791
- }
792
- catch (err) {
793
- if (!ClassRegistry_1.ClassRegistry.isNotFoundError(err)) {
794
- throw err;
795
- }
796
- this.loadMetaData(classFullName);
797
- return ClassRegistry_1.ClassRegistry.getClass(classFullName, this);
798
- }
799
- }
800
- /** Get metadata for a class. This method will load the metadata from the iModel into the cache as a side-effect, if necessary.
801
- * @throws [[IModelError]] if the metadata cannot be found nor loaded.
802
- */
803
- getMetaData(classFullName) {
804
- let metadata = this.classMetaDataRegistry.find(classFullName);
805
- if (metadata === undefined) {
806
- this.loadMetaData(classFullName);
807
- metadata = this.classMetaDataRegistry.find(classFullName);
808
- if (metadata === undefined)
809
- throw ClassRegistry_1.ClassRegistry.makeMetaDataNotFoundError(classFullName); // do not log
810
- }
811
- return metadata;
812
- }
813
- /** Invoke a callback on each property of the specified class, optionally including superclass properties.
814
- * @param iModel The IModel that contains the schema
815
- * @param classFullName The full class name to load the metadata, if necessary
816
- * @param wantSuper If true, superclass properties will also be processed
817
- * @param func The callback to be invoked on each property
818
- * @param includeCustom If true (default), include custom-handled properties in the iteration. Otherwise, skip custom-handled properties.
819
- * @note Custom-handled properties are core properties that have behavior enforced by C++ handlers.
820
- */
821
- static forEachMetaData(iModel, classFullName, wantSuper, func, includeCustom = true) {
822
- const meta = iModel.getMetaData(classFullName); // will load if necessary
823
- for (const propName in meta.properties) { // eslint-disable-line guard-for-in
824
- const propMeta = meta.properties[propName];
825
- if (includeCustom || !propMeta.isCustomHandled || propMeta.isCustomHandledOrphan)
826
- func(propName, propMeta);
827
- }
828
- if (wantSuper && meta.baseClasses && meta.baseClasses.length > 0)
829
- meta.baseClasses.forEach((baseClass) => this.forEachMetaData(iModel, baseClass, true, func, includeCustom));
830
- }
831
- /** @internal */
832
- loadMetaData(classFullName) {
833
- if (this.classMetaDataRegistry.find(classFullName))
834
- return;
835
- const className = classFullName.split(":");
836
- if (className.length !== 2)
837
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadArg, `Invalid classFullName: ${classFullName}`);
838
- const val = this.nativeDb.getECClassMetaData(className[0], className[1]);
839
- if (val.error)
840
- throw new core_common_1.IModelError(val.error.status, `Error getting class meta data for: ${classFullName}`);
841
- (0, core_bentley_1.assert)(undefined !== val.result);
842
- const metaData = new core_common_1.EntityMetaData(JSON.parse(val.result));
843
- this.classMetaDataRegistry.add(classFullName, metaData);
844
- // Recursive, to make sure that base classes are cached.
845
- if (metaData.baseClasses !== undefined && metaData.baseClasses.length > 0)
846
- metaData.baseClasses.forEach((baseClassName) => this.loadMetaData(baseClassName));
847
- }
848
- /** Returns the full schema for the input name.
849
- * @param name The name of the schema e.g. 'BisCore'
850
- * @returns The SchemaProps for the requested schema
851
- * @throws if the schema can not be found or loaded.
852
- */
853
- getSchemaProps(name) {
854
- return this.nativeDb.getSchemaProps(name);
855
- }
856
- /** Query if this iModel contains the definition of the specified class.
857
- * @param classFullName The full name of the class, for example, SomeSchema:SomeClass
858
- * @returns true if the iModel contains the class definition or false if not.
859
- * @see querySchemaVersion
860
- * @see importSchema
861
- */
862
- containsClass(classFullName) {
863
- const classNameParts = classFullName.replace(".", ":").split(":");
864
- return classNameParts.length === 2 && this.nativeDb.getECClassMetaData(classNameParts[0], classNameParts[1]).error === undefined;
865
- }
866
- /** Query for a schema of the specified name in this iModel.
867
- * @returns The schema version as a semver-compatible string or `undefined` if the schema has not been imported.
868
- */
869
- querySchemaVersion(schemaName) {
870
- const sql = `SELECT VersionMajor,VersionWrite,VersionMinor FROM ECDbMeta.ECSchemaDef WHERE Name=:schemaName LIMIT 1`;
871
- return this.withPreparedStatement(sql, (statement) => {
872
- statement.bindString("schemaName", schemaName);
873
- if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
874
- const versionMajor = statement.getValue(0).getInteger(); // ECSchemaDef.VersionMajor --> semver.major
875
- const versionWrite = statement.getValue(1).getInteger(); // ECSchemaDef.VersionWrite --> semver.minor
876
- const versionMinor = statement.getValue(2).getInteger(); // ECSchemaDef.VersionMinor --> semver.patch
877
- return `${versionMajor}.${versionWrite}.${versionMinor}`;
878
- }
879
- return undefined;
880
- });
881
- }
882
- /** Retrieve a named texture image from this iModel, as a TextureData.
883
- * @param props the texture load properties which must include the name of the texture to load
884
- * @returns the TextureData or undefined if the texture image is not present.
885
- * @alpha
886
- */
887
- async queryTextureData(props) {
888
- return this.nativeDb.queryTextureData(props);
889
- }
890
- /** Query a "file property" from this iModel, as a string.
891
- * @returns the property string or undefined if the property is not present.
892
- */
893
- queryFilePropertyString(prop) {
894
- return this.nativeDb.queryFileProperty(prop, true);
895
- }
896
- /** Query a "file property" from this iModel, as a blob.
897
- * @returns the property blob or undefined if the property is not present.
898
- */
899
- queryFilePropertyBlob(prop) {
900
- return this.nativeDb.queryFileProperty(prop, false);
901
- }
902
- /** Save a "file property" to this iModel
903
- * @param prop the FilePropertyProps that describes the new property
904
- * @param value either a string or a blob to save as the file property
905
- */
906
- saveFileProperty(prop, strValue, blobVal) {
907
- this.nativeDb.saveFileProperty(prop, strValue, blobVal);
908
- }
909
- /** delete a "file property" from this iModel
910
- * @param prop the FilePropertyProps that describes the property
911
- */
912
- deleteFileProperty(prop) {
913
- this.nativeDb.saveFileProperty(prop, undefined, undefined);
914
- }
915
- /** Query for the next available major id for a "file property" from this iModel.
916
- * @param prop the FilePropertyProps that describes the property
917
- * @returns the next available (that is, an unused) id for prop. If none are present, will return 0.
918
- */
919
- queryNextAvailableFileProperty(prop) { return this.nativeDb.queryNextAvailableFileProperty(prop); }
920
- /** @internal */
921
- async requestSnap(sessionId, props) {
922
- let request = this._snaps.get(sessionId);
923
- if (undefined === request) {
924
- request = new IModelHost_1.IModelHost.platform.SnapRequest();
925
- this._snaps.set(sessionId, request);
926
- }
927
- else
928
- request.cancelSnap();
929
- try {
930
- return await request.doSnap(this.nativeDb, core_bentley_1.JsonUtils.toObject(props));
931
- }
932
- finally {
933
- this._snaps.delete(sessionId);
934
- }
935
- }
936
- /** Cancel a previously requested snap.
937
- * @internal
938
- */
939
- cancelSnap(sessionId) {
940
- const request = this._snaps.get(sessionId);
941
- if (undefined !== request) {
942
- request.cancelSnap();
943
- this._snaps.delete(sessionId);
944
- }
945
- }
946
- /** Get the clip containment status for the supplied elements. */
947
- async getGeometryContainment(props) {
948
- return this.nativeDb.getGeometryContainment(core_bentley_1.JsonUtils.toObject(props));
949
- }
950
- /** Get the mass properties for the supplied elements. */
951
- async getMassProperties(props) {
952
- return this.nativeDb.getMassProperties(core_bentley_1.JsonUtils.toObject(props));
953
- }
954
- /** Get the IModel coordinate corresponding to each GeoCoordinate point in the input */
955
- async getIModelCoordinatesFromGeoCoordinates(props) {
956
- return this.nativeDb.getIModelCoordinatesFromGeoCoordinates(props);
957
- }
958
- /** Get the GeoCoordinate (longitude, latitude, elevation) corresponding to each IModel Coordinate point in the input */
959
- async getGeoCoordinatesFromIModelCoordinates(props) {
960
- return this.nativeDb.getGeoCoordinatesFromIModelCoordinates(props);
961
- }
962
- /** Export meshes suitable for graphics APIs from arbitrary geometry in elements in this IModelDb.
963
- * * Requests can be slow when processing many elements so it is expected that this function be used on a dedicated backend,
964
- * or that shared backends export a limited number of elements at a time.
965
- * * Vertices are exported in the IModelDb's world coordinate system, which is right-handed with Z pointing up.
966
- * * The results of changing [ExportGraphicsOptions]($core-backend) during the [ExportGraphicsOptions.onGraphics]($core-backend) callback are not defined.
967
- *
968
- * Example that prints the mesh for element 1 to stdout in [OBJ format](https://en.wikipedia.org/wiki/Wavefront_.obj_file)
969
- * ```ts
970
- * const onGraphics: ExportGraphicsFunction = (info: ExportGraphicsInfo) => {
971
- * const mesh: ExportGraphicsMesh = info.mesh;
972
- * for (let i = 0; i < mesh.points.length; i += 3) {
973
- * process.stdout.write(`v ${mesh.points[i]} ${mesh.points[i + 1]} ${mesh.points[i + 2]}\n`);
974
- * process.stdout.write(`vn ${mesh.normals[i]} ${mesh.normals[i + 1]} ${mesh.normals[i + 2]}\n`);
975
- * }
976
- *
977
- * for (let i = 0; i < mesh.params.length; i += 2) {
978
- * process.stdout.write(`vt ${mesh.params[i]} ${mesh.params[i + 1]}\n`);
979
- * }
980
- *
981
- * for (let i = 0; i < mesh.indices.length; i += 3) {
982
- * const p1 = mesh.indices[i];
983
- * const p2 = mesh.indices[i + 1];
984
- * const p3 = mesh.indices[i + 2];
985
- * process.stdout.write(`f ${p1}/${p1}/${p1} ${p2}/${p2}/${p2} ${p3}/${p3}/${p3}\n`);
986
- * }
987
- * };
988
- *
989
- * iModel.exportGraphics(({ onGraphics, elementIdArray: ["0x1"] }));
990
- * ```
991
- * @returns 0 if successful, status otherwise
992
- * @public
993
- */
994
- exportGraphics(exportProps) {
995
- return this.nativeDb.exportGraphics(exportProps);
996
- }
997
- /**
998
- * Exports meshes suitable for graphics APIs from a specified [GeometryPart]($core-backend)
999
- * in this IModelDb.
1000
- * The expected use case is to call [IModelDb.exportGraphics]($core-backend) and supply the
1001
- * optional partInstanceArray argument, then call this function for each unique GeometryPart from
1002
- * that list.
1003
- * * The results of changing [ExportPartGraphicsOptions]($core-backend) during the
1004
- * [ExportPartGraphicsOptions.onPartGraphics]($core-backend) callback are not defined.
1005
- * * See export-gltf under test-apps in the iTwin.js monorepo for a working reference.
1006
- * @returns 0 is successful, status otherwise
1007
- * @public
1008
- */
1009
- exportPartGraphics(exportProps) {
1010
- return this.nativeDb.exportPartGraphics(exportProps);
1011
- }
1012
- /** Request geometry stream information from an element in binary format instead of json.
1013
- * @returns IModelStatus.Success if successful
1014
- * @alpha
1015
- */
1016
- elementGeometryRequest(requestProps) {
1017
- return this.nativeDb.processGeometryStream(requestProps);
1018
- }
1019
- /** Create brep geometry for inclusion in an element's geometry stream.
1020
- * @returns IModelStatus.Success if successful
1021
- * @throws [[IModelError]] to report issues with input geometry or parameters
1022
- * @alpha
1023
- */
1024
- createBRepGeometry(createProps) {
1025
- return this.nativeDb.createBRepGeometry(createProps);
1026
- }
1027
- /** Generate graphics for an element or geometry stream.
1028
- * @see [readElementGraphics]($frontend) to convert the result to a [RenderGraphic]($frontend) for display.
1029
- */
1030
- async generateElementGraphics(request) {
1031
- return (0, ElementGraphics_1.generateElementGraphics)(request, this);
1032
- }
1033
- /** Save a `SettingDictionary` in this iModel that will be loaded into [[workspace.settings]] every time this iModel is opened in future sessions.
1034
- * @param name The name for the SettingDictionary. If a dictionary by that name already exists in the iModel, its value is replaced.
1035
- * @param dict The SettingDictionary object to stringify and save.
1036
- * @note All saved `SettingDictionary`s are loaded into [[workspace.settings]] every time an iModel is opened.
1037
- * @beta
1038
- */
1039
- saveSettingDictionary(name, dict) {
1040
- this.withSqliteStatement("REPLACE INTO be_Prop(id,SubId,TxnMode,Namespace,Name,strData) VALUES(0,0,0,?,?,?)", (stmt) => {
1041
- stmt.bindString(1, IModelDb._settingPropNamespace);
1042
- stmt.bindString(2, name);
1043
- stmt.bindString(3, JSON.stringify(dict));
1044
- const rc = stmt.step();
1045
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
1046
- throw new core_common_1.IModelError(rc, "cannot save setting");
1047
- });
1048
- this.saveChanges("add settings");
1049
- }
1050
- /** Delete a SettingDictionary, previously added with [[saveSettingDictionary]], from this iModel.
1051
- * @param name The name of the dictionary to delete.
1052
- * @beta
1053
- */
1054
- deleteSettingDictionary(name) {
1055
- this.withSqliteStatement("DELETE FROM be_Prop WHERE Namespace=? AND Name=?", (stmt) => {
1056
- stmt.bindString(1, IModelDb._settingPropNamespace);
1057
- stmt.bindString(2, name);
1058
- const rc = stmt.step();
1059
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
1060
- throw new core_common_1.IModelError(rc, "cannot delete setting");
1061
- });
1062
- this.saveChanges("delete settings");
1063
- }
1064
- /** Load all setting dictionaries in this iModel into `this.workspace.settings` */
1065
- loadSettingDictionaries() {
1066
- if (!this.nativeDb.isOpen())
1067
- return;
1068
- this.withSqliteStatement("SELECT Name,StrData FROM be_Prop WHERE Namespace=?", (stmt) => {
1069
- stmt.bindString(1, IModelDb._settingPropNamespace);
1070
- while (stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW) {
1071
- try {
1072
- const dict = JSON.parse(stmt.getValueString(1));
1073
- this.workspace.settings.addDictionary(stmt.getValueString(0), Settings_1.SettingsPriority.iModel, dict);
1074
- }
1075
- catch (e) {
1076
- core_bentley_1.UnexpectedErrors.handle(e);
1077
- }
1078
- }
1079
- });
1080
- }
1081
- }
1082
- exports.IModelDb = IModelDb;
1083
- /** Keep track of open imodels to support `tryFind` for RPC purposes */
1084
- IModelDb._openDbs = new Map();
1085
- IModelDb.defaultLimit = 1000; // default limit for batching queries
1086
- IModelDb.maxLimit = 10000; // maximum limit for batching queries
1087
- IModelDb._settingPropNamespace = "settings";
1088
- /** @public */
1089
- (function (IModelDb) {
1090
- /** The collection of models in an [[IModelDb]].
1091
- * @public
1092
- */
1093
- class Models {
1094
- /** @internal */
1095
- constructor(_iModel) {
1096
- this._iModel = _iModel;
1097
- }
1098
- /** Get the ModelProps with the specified identifier.
1099
- * @param modelId The Model identifier.
1100
- * @throws [[IModelError]] if the model is not found or cannot be loaded.
1101
- * @see tryGetModelProps
1102
- */
1103
- getModelProps(id) {
1104
- return this.getModelJson({ id });
1105
- }
1106
- /** Get the ModelProps with the specified identifier.
1107
- * @param modelId The Model identifier.
1108
- * @returns The ModelProps or `undefined` if the model is not found.
1109
- * @throws [[IModelError]] if the model cannot be loaded.
1110
- * @note Useful for cases when a model may or may not exist and throwing an `Error` would be overkill.
1111
- * @see getModelProps
1112
- */
1113
- tryGetModelProps(id) {
1114
- return this.tryGetModelJson({ id });
1115
- }
1116
- /** Query for the last modified time of the specified Model.
1117
- * @internal
1118
- */
1119
- queryLastModifiedTime(modelId) {
1120
- const sql = `SELECT LastMod FROM ${Model_1.Model.classFullName} WHERE ECInstanceId=:modelId`;
1121
- return this._iModel.withPreparedStatement(sql, (statement) => {
1122
- statement.bindId("modelId", modelId);
1123
- if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1124
- return statement.getValue(0).getDateTime();
1125
- }
1126
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Can't get lastMod time for Model ${modelId}`);
1127
- });
1128
- }
1129
- /** Get the Model with the specified identifier.
1130
- * @param modelId The Model identifier.
1131
- * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1132
- * @throws [[IModelError]] if the model is not found, cannot be loaded, or fails validation when `modelClass` is specified.
1133
- * @see tryGetModel
1134
- */
1135
- getModel(modelId, modelClass) {
1136
- const model = this.tryGetModel(modelId, modelClass);
1137
- if (undefined === model) {
1138
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Model=${modelId}`);
1139
- }
1140
- return model;
1141
- }
1142
- /** Get the Model with the specified identifier.
1143
- * @param modelId The Model identifier.
1144
- * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1145
- * @returns The Model or `undefined` if the model is not found or fails validation when `modelClass` is specified.
1146
- * @throws [[IModelError]] if the model cannot be loaded.
1147
- * @note Useful for cases when a model may or may not exist and throwing an `Error` would be overkill.
1148
- * @see getModel
1149
- */
1150
- tryGetModel(modelId, modelClass) {
1151
- const modelProps = this.tryGetModelProps(modelId);
1152
- if (undefined === modelProps)
1153
- return undefined; // no Model with that modelId found
1154
- const model = this._iModel.constructEntity(modelProps);
1155
- if (undefined === modelClass)
1156
- return model; // modelClass was not specified, cannot call instanceof to validate
1157
- return model instanceof modelClass ? model : undefined;
1158
- }
1159
- /** Read the properties for a Model as a json string.
1160
- * @param modelIdArg a json string with the identity of the model to load. Must have either "id" or "code".
1161
- * @returns a json string with the properties of the model.
1162
- * @throws [[IModelError]] if the model is not found or cannot be loaded.
1163
- * @see tryGetModelJson
1164
- * @internal
1165
- */
1166
- getModelJson(modelIdArg) {
1167
- const modelJson = this.tryGetModelJson(modelIdArg);
1168
- if (undefined === modelJson) {
1169
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Model=${modelIdArg}`);
1170
- }
1171
- return modelJson;
1172
- }
1173
- /** Read the properties for a Model as a json string.
1174
- * @param modelIdArg a json string with the identity of the model to load. Must have either "id" or "code".
1175
- * @returns a json string with the properties of the model or `undefined` if the model is not found.
1176
- * @see getModelJson
1177
- */
1178
- tryGetModelJson(modelIdArg) {
1179
- try {
1180
- return this._iModel.nativeDb.getModel(modelIdArg);
1181
- }
1182
- catch (err) {
1183
- return undefined;
1184
- }
1185
- }
1186
- /** Get the sub-model of the specified Element.
1187
- * See [[IModelDb.Elements.queryElementIdByCode]] for more on how to find an element by Code.
1188
- * @param modeledElementId Identifies the modeled element.
1189
- * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1190
- * @throws [[IModelError]] if the sub-model is not found, cannot be loaded, or fails validation when `modelClass` is specified.
1191
- * @see tryGetSubModel
1192
- */
1193
- getSubModel(modeledElementId, modelClass) {
1194
- const modeledElementProps = this._iModel.elements.getElementProps(modeledElementId);
1195
- if (undefined === modeledElementProps.id || modeledElementProps.id === core_common_1.IModel.rootSubjectId)
1196
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "Root subject does not have a sub-model");
1197
- return this.getModel(modeledElementProps.id, modelClass);
1198
- }
1199
- /** Get the sub-model of the specified Element.
1200
- * See [[IModelDb.Elements.queryElementIdByCode]] for more on how to find an element by Code.
1201
- * @param modeledElementId Identifies the modeled element.
1202
- * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1203
- * @returns The sub-model or `undefined` if the specified element does not have a sub-model or fails validation when `modelClass` is specified.
1204
- * @see getSubModel
1205
- */
1206
- tryGetSubModel(modeledElementId, modelClass) {
1207
- const modeledElementProps = this._iModel.elements.tryGetElementProps(modeledElementId);
1208
- if (undefined === modeledElementProps?.id || (core_common_1.IModel.rootSubjectId === modeledElementProps.id))
1209
- return undefined;
1210
- return this.tryGetModel(modeledElementProps.id, modelClass);
1211
- }
1212
- /** Create a new model in memory.
1213
- * See the example in [[InformationPartitionElement]].
1214
- * @param modelProps The properties to use when creating the model.
1215
- * @throws [[IModelError]] if there is a problem creating the model.
1216
- */
1217
- createModel(modelProps) { return this._iModel.constructEntity(modelProps); }
1218
- /** Insert a new model.
1219
- * @param props The data for the new model.
1220
- * @returns The newly inserted model's Id.
1221
- * @throws [[IModelError]] if unable to insert the model.
1222
- */
1223
- insertModel(props) {
1224
- try {
1225
- return props.id = this._iModel.nativeDb.insertModel(props);
1226
- }
1227
- catch (err) {
1228
- throw new core_common_1.IModelError(err.errorNumber, `Error inserting model [${err.message}], class=${props.classFullName}`);
1229
- }
1230
- }
1231
- /** Update an existing model.
1232
- * @param props the properties of the model to change
1233
- * @throws [[IModelError]] if unable to update the model.
1234
- */
1235
- updateModel(props) {
1236
- try {
1237
- this._iModel.nativeDb.updateModel(props);
1238
- }
1239
- catch (err) {
1240
- throw new core_common_1.IModelError(err.errorNumber, `error updating model [${err.message}] id=${props.id}`);
1241
- }
1242
- }
1243
- /** Mark the geometry of [[GeometricModel]] as having changed, by recording an indirect change to its GeometryGuid property.
1244
- * Typically the GeometryGuid changes automatically when [[GeometricElement]]s within the model are modified, but
1245
- * explicitly updating it is occasionally useful after modifying definition elements like line styles or materials that indirectly affect the appearance of
1246
- * [[GeometricElement]]s that reference those definition elements in their geometry streams.
1247
- * Cached [Tile]($frontend)s are only invalidated after the geometry guid of the model changes.
1248
- * @note This will throw IModelError with [IModelStatus.VersionTooOld]($core-bentley) if a version of the BisCore schema older than 1.0.11 is present in the iModel.
1249
- * @throws IModelError if unable to update the geometry guid.
1250
- * @see [[TxnManager.onModelGeometryChanged]] for the event emitted in response to such a change.
1251
- */
1252
- updateGeometryGuid(modelId) {
1253
- const error = this._iModel.nativeDb.updateModelGeometryGuid(modelId);
1254
- if (error !== core_bentley_1.IModelStatus.Success)
1255
- throw new core_common_1.IModelError(error, `updating geometry guid for model ${modelId}`);
1256
- }
1257
- /** Delete one or more existing models.
1258
- * @param ids The Ids of the models to be deleted
1259
- * @throws [[IModelError]]
1260
- */
1261
- deleteModel(ids) {
1262
- core_bentley_1.Id64.toIdSet(ids).forEach((id) => {
1263
- try {
1264
- this._iModel.nativeDb.deleteModel(id);
1265
- }
1266
- catch (err) {
1267
- throw new core_common_1.IModelError(err.errorNumber, `error deleting model [${err.message}] id ${id}`);
1268
- }
1269
- });
1270
- }
1271
- /** For each specified [[GeometricModel]], attempts to obtain the union of the volumes of all geometric elements within that model.
1272
- * @param ids The Id or Ids of the [[GeometricModel]]s for which to obtain the extents.
1273
- * @returns An array of results, one per supplied Id, in the order in which the Ids were supplied. If the extents could not be obtained, the
1274
- * corresponding results entry's `extents` will be a "null" range (@see [Range3d.isNull]($geometry)) and its `status` will indicate
1275
- * why the extents could not be obtained (e.g., because the Id did not identify a [[GeometricModel]]).
1276
- * @see [[queryRange]] to obtain the union of all of the models' extents.
1277
- */
1278
- async queryExtents(ids) {
1279
- ids = typeof ids === "string" ? [ids] : ids;
1280
- if (ids.length === 0)
1281
- return [];
1282
- return this._iModel.nativeDb.queryModelExtentsAsync(ids);
1283
- }
1284
- /** Computes the union of the volumes of all geoemtric elements within any number of [[GeometricModel]]s, specified by model Id.
1285
- * @see [[queryExtents]] to obtain discrete volumes for each model.
1286
- */
1287
- async queryRange(ids) {
1288
- const results = await this.queryExtents(ids);
1289
- const range = new core_geometry_1.Range3d();
1290
- for (const result of results)
1291
- range.union(core_geometry_1.Range3d.fromJSON(result.extents), range);
1292
- return range;
1293
- }
1294
- }
1295
- IModelDb.Models = Models;
1296
- /** The collection of elements in an [[IModelDb]].
1297
- * @public
1298
- */
1299
- class Elements {
1300
- /** @internal */
1301
- constructor(_iModel) {
1302
- this._iModel = _iModel;
1303
- }
1304
- /** Read element data from the iModel as JSON
1305
- * @param elementIdArg a json string with the identity of the element to load. Must have one of "id", "federationGuid", or "code".
1306
- * @returns The JSON properties of the element.
1307
- * @throws [[IModelError]] if the element is not found or cannot be loaded.
1308
- * @see tryGetElementJson
1309
- * @internal
1310
- */
1311
- getElementJson(elementId) {
1312
- const elementProps = this.tryGetElementJson(elementId);
1313
- if (undefined === elementProps)
1314
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `reading element=${elementId}`);
1315
- return elementProps;
1316
- }
1317
- /** Read element data from the iModel as JSON
1318
- * @param loadProps - a json string with the identity of the element to load. Must have one of "id", "federationGuid", or "code".
1319
- * @returns The JSON properties of the element or `undefined` if the element is not found.
1320
- * @throws [[IModelError]] if the element exists, but cannot be loaded.
1321
- * @see getElementJson
1322
- */
1323
- tryGetElementJson(loadProps) {
1324
- try {
1325
- return this._iModel.nativeDb.getElement(loadProps);
1326
- }
1327
- catch (err) {
1328
- return undefined;
1329
- }
1330
- }
1331
- /** Get properties of an Element by Id, FederationGuid, or Code
1332
- * @throws [[IModelError]] if the element is not found or cannot be loaded.
1333
- * @see tryGetElementProps
1334
- */
1335
- getElementProps(props) {
1336
- if (typeof props === "string") {
1337
- props = core_bentley_1.Id64.isId64(props) ? { id: props } : { federationGuid: props };
1338
- }
1339
- else if (props instanceof core_common_1.Code) {
1340
- props = { code: props };
1341
- }
1342
- try {
1343
- return this._iModel.nativeDb.getElement(props);
1344
- }
1345
- catch (err) {
1346
- throw new core_common_1.IModelError(err.errorNumber, err.message);
1347
- }
1348
- }
1349
- /** Get properties of an Element by Id, FederationGuid, or Code
1350
- * @returns The properties of the element or `undefined` if the element is not found.
1351
- * @throws [[IModelError]] if the element exists, but cannot be loaded.
1352
- * @note Useful for cases when an element may or may not exist and throwing an `Error` would be overkill.
1353
- * @see getElementProps
1354
- */
1355
- tryGetElementProps(elementId) {
1356
- if (typeof elementId === "string") {
1357
- elementId = core_bentley_1.Id64.isId64(elementId) ? { id: elementId } : { federationGuid: elementId };
1358
- }
1359
- else if (elementId instanceof core_common_1.Code) {
1360
- elementId = { code: elementId };
1361
- }
1362
- return this.tryGetElementJson(elementId);
1363
- }
1364
- /** Get an element by Id, FederationGuid, or Code
1365
- * @param elementId either the element's Id, Code, or FederationGuid, or an ElementLoadProps
1366
- * @param elementClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1367
- * @throws [[IModelError]] if the element is not found, cannot be loaded, or fails validation when `elementClass` is specified.
1368
- * @see tryGetElement
1369
- */
1370
- getElement(elementId, elementClass) {
1371
- const element = this.tryGetElement(elementId, elementClass);
1372
- if (undefined === element)
1373
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Element=${elementId}`);
1374
- return element;
1375
- }
1376
- /** Get an element by Id, FederationGuid, or Code
1377
- * @param elementId either the element's Id, Code, or FederationGuid, or an ElementLoadProps
1378
- * @param elementClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1379
- * @returns The element or `undefined` if the element is not found or fails validation when `elementClass` is specified.
1380
- * @throws [[IModelError]] if the element exists, but cannot be loaded.
1381
- * @note Useful for cases when an element may or may not exist and throwing an `Error` would be overkill.
1382
- * @see getElement
1383
- */
1384
- tryGetElement(elementId, elementClass) {
1385
- if (typeof elementId === "string")
1386
- elementId = core_bentley_1.Id64.isId64(elementId) ? { id: elementId } : { federationGuid: elementId };
1387
- else if (elementId instanceof core_common_1.Code)
1388
- elementId = { code: elementId };
1389
- else
1390
- elementId.onlyBaseProperties = false; // we must load all properties to construct the element.
1391
- const elementProps = this.tryGetElementJson(elementId);
1392
- if (undefined === elementProps)
1393
- return undefined; // no Element with that elementId found
1394
- const element = this._iModel.constructEntity(elementProps);
1395
- if (undefined === elementClass)
1396
- return element; // elementClass was not specified, cannot call instanceof to validate
1397
- return element instanceof elementClass ? element : undefined;
1398
- }
1399
- /** Query for the Id of the element that has a specified code.
1400
- * This method is for the case where you know the element's Code.
1401
- * If you only know the code *value*, then in the simplest case, you can query on that
1402
- * and filter the results.
1403
- * In the simple case, call [[IModelDb.queryEntityIds]], specifying the code value in the where clause of the query params.
1404
- * Or, you can execute an ECSQL select statement. See
1405
- * [frequently used ECSQL queries]($docs/learning/backend/ECSQL-queries.md) for an example.
1406
- * @param code The code to look for
1407
- * @returns The element that uses the code or undefined if the code is not used.
1408
- * @throws IModelError if the code is invalid
1409
- */
1410
- queryElementIdByCode(code) {
1411
- if (core_bentley_1.Id64.isInvalid(code.spec))
1412
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidCodeSpec, "Invalid CodeSpec");
1413
- if (code.value === undefined)
1414
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidCode, "Invalid Code");
1415
- return this._iModel.withPreparedStatement("SELECT ECInstanceId FROM BisCore:Element WHERE CodeSpec.Id=? AND CodeScope.Id=? AND CodeValue=?", (stmt) => {
1416
- stmt.bindId(1, code.spec);
1417
- stmt.bindId(2, core_bentley_1.Id64.fromString(code.scope));
1418
- stmt.bindString(3, code.value);
1419
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== stmt.step())
1420
- return undefined;
1421
- return stmt.getValue(0).getId();
1422
- });
1423
- }
1424
- /** Query for the last modified time of the specified element.
1425
- * @internal
1426
- */
1427
- queryLastModifiedTime(elementId) {
1428
- const sql = "SELECT LastMod FROM BisCore:Element WHERE ECInstanceId=:elementId";
1429
- return this._iModel.withPreparedStatement(sql, (statement) => {
1430
- statement.bindId("elementId", elementId);
1431
- if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step())
1432
- return statement.getValue(0).getDateTime();
1433
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Can't get lastMod time for Element ${elementId}`);
1434
- });
1435
- }
1436
- /** Create a new instance of an element.
1437
- * @param elProps The properties of the new element.
1438
- * @throws [[IModelError]] if there is a problem creating the element.
1439
- */
1440
- createElement(elProps) { return this._iModel.constructEntity(elProps); }
1441
- /** Insert a new element into the iModel.
1442
- * @param elProps The properties of the new element.
1443
- * @returns The newly inserted element's Id.
1444
- * @throws [[IModelError]] if unable to insert the element.
1445
- * @note For convenience, the value of `elProps.id` is updated to reflect the resultant element's id.
1446
- * However when `elProps.federationGuid` is not present or undefined, a new Guid will be generated and stored on the resultant element. But
1447
- * the value of `elProps.federationGuid` is *not* updated. Generally, it is best to re-read the element after inserting (e.g. via [[getElementProps]])
1448
- * if you intend to continue working with it. That will ensure its values reflect the persistent state.
1449
- */
1450
- insertElement(elProps) {
1451
- try {
1452
- return elProps.id = this._iModel.nativeDb.insertElement(elProps);
1453
- }
1454
- catch (err) {
1455
- err.message = `error inserting element: ${err.message}`;
1456
- throw err;
1457
- }
1458
- }
1459
- /** Update some properties of an existing element.
1460
- * To support clearing a property value, every property name that is present in the `elProps` object will be updated even if the value is `undefined`.
1461
- * To keep an individual element property unchanged, it should either be excluded from the `elProps` parameter or set to its current value.
1462
- * @param elProps the properties of the element to update.
1463
- * @note As described above, this is a special case where there is a difference between a property being excluded and a property being present in `elProps` but set to `undefined`.
1464
- * @throws [[IModelError]] if unable to update the element.
1465
- */
1466
- updateElement(elProps) {
1467
- try {
1468
- this._iModel.nativeDb.updateElement(elProps);
1469
- }
1470
- catch (err) {
1471
- err.message = `error updating element: ${err.message}`;
1472
- throw err;
1473
- }
1474
- }
1475
- /** Delete one or more elements from this iModel.
1476
- * @param ids The set of Ids of the element(s) to be deleted
1477
- * @throws [[IModelError]]
1478
- * @see deleteDefinitionElements
1479
- */
1480
- deleteElement(ids) {
1481
- const iModel = this._iModel;
1482
- core_bentley_1.Id64.toIdSet(ids).forEach((id) => {
1483
- try {
1484
- iModel.nativeDb.deleteElement(id);
1485
- }
1486
- catch (err) {
1487
- err.message = `error deleting element: ${err.message}`;
1488
- throw err;
1489
- }
1490
- });
1491
- }
1492
- /** DefinitionElements can only be deleted if it can be determined that they are not referenced by other Elements.
1493
- * This *usage query* can be expensive since it may involve scanning the GeometryStreams of all GeometricElements.
1494
- * Since [[deleteElement]] does not perform these additional checks, it fails in order to prevent potentially referenced DefinitionElements from being deleted.
1495
- * This method performs those expensive checks and then calls *delete* if not referenced.
1496
- * @param ids The Ids of the DefinitionElements to attempt to delete. To prevent multiple passes over the same GeometricElements, it is best to pass in the entire array of
1497
- * DefinitionElements rather than calling this method separately for each one. Ids that are not valid DefinitionElements will be ignored.
1498
- * @returns An IdSet of the DefinitionElements that are used and were therefore not deleted.
1499
- * @see deleteElement
1500
- * @beta
1501
- */
1502
- deleteDefinitionElements(definitionElementIds) {
1503
- const usageInfo = this._iModel.nativeDb.queryDefinitionElementUsage(definitionElementIds);
1504
- if (!usageInfo) {
1505
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Error querying for DefinitionElement usage");
1506
- }
1507
- const usedIdSet = usageInfo.usedIds ? core_bentley_1.Id64.toIdSet(usageInfo.usedIds) : new Set();
1508
- const deleteIfUnused = (ids, used) => {
1509
- if (ids) {
1510
- ids.forEach((id) => {
1511
- if (!used.has(id))
1512
- this._iModel.elements.deleteElement(id);
1513
- });
1514
- }
1515
- };
1516
- try {
1517
- this._iModel.nativeDb.beginPurgeOperation();
1518
- deleteIfUnused(usageInfo.spatialCategoryIds, usedIdSet);
1519
- deleteIfUnused(usageInfo.drawingCategoryIds, usedIdSet);
1520
- deleteIfUnused(usageInfo.viewDefinitionIds, usedIdSet);
1521
- deleteIfUnused(usageInfo.geometryPartIds, usedIdSet);
1522
- deleteIfUnused(usageInfo.lineStyleIds, usedIdSet);
1523
- deleteIfUnused(usageInfo.renderMaterialIds, usedIdSet);
1524
- deleteIfUnused(usageInfo.subCategoryIds, usedIdSet);
1525
- deleteIfUnused(usageInfo.textureIds, usedIdSet);
1526
- deleteIfUnused(usageInfo.displayStyleIds, usedIdSet);
1527
- deleteIfUnused(usageInfo.categorySelectorIds, usedIdSet);
1528
- deleteIfUnused(usageInfo.modelSelectorIds, usedIdSet);
1529
- if (usageInfo.otherDefinitionElementIds) {
1530
- this._iModel.elements.deleteElement(usageInfo.otherDefinitionElementIds);
1531
- }
1532
- }
1533
- finally {
1534
- this._iModel.nativeDb.endPurgeOperation();
1535
- }
1536
- if (usageInfo.viewDefinitionIds) {
1537
- // take another pass in case a deleted ViewDefinition was the only usage of these view-related DefinitionElements
1538
- let viewRelatedIds = [];
1539
- if (usageInfo.displayStyleIds)
1540
- viewRelatedIds = viewRelatedIds.concat(usageInfo.displayStyleIds.filter((id) => usedIdSet.has(id)));
1541
- if (usageInfo.categorySelectorIds)
1542
- viewRelatedIds = viewRelatedIds.concat(usageInfo.categorySelectorIds.filter((id) => usedIdSet.has(id)));
1543
- if (usageInfo.modelSelectorIds)
1544
- viewRelatedIds = viewRelatedIds.concat(usageInfo.modelSelectorIds.filter((id) => usedIdSet.has(id)));
1545
- if (viewRelatedIds.length > 0) {
1546
- const viewRelatedUsageInfo = this._iModel.nativeDb.queryDefinitionElementUsage(viewRelatedIds);
1547
- if (viewRelatedUsageInfo) {
1548
- const usedViewRelatedIdSet = viewRelatedUsageInfo.usedIds ? core_bentley_1.Id64.toIdSet(viewRelatedUsageInfo.usedIds) : new Set();
1549
- try {
1550
- this._iModel.nativeDb.beginPurgeOperation();
1551
- deleteIfUnused(viewRelatedUsageInfo.displayStyleIds, usedViewRelatedIdSet);
1552
- deleteIfUnused(viewRelatedUsageInfo.categorySelectorIds, usedViewRelatedIdSet);
1553
- deleteIfUnused(viewRelatedUsageInfo.modelSelectorIds, usedViewRelatedIdSet);
1554
- }
1555
- finally {
1556
- this._iModel.nativeDb.endPurgeOperation();
1557
- }
1558
- viewRelatedIds.forEach((id) => {
1559
- if (!usedViewRelatedIdSet.has(id))
1560
- usedIdSet.delete(id);
1561
- });
1562
- }
1563
- }
1564
- }
1565
- return usedIdSet;
1566
- }
1567
- /** Query for the child elements of the specified element.
1568
- * @returns Returns an array of child element identifiers.
1569
- * @throws [[IModelError]]
1570
- */
1571
- queryChildren(elementId) {
1572
- const sql = "SELECT ECInstanceId FROM BisCore:Element WHERE Parent.Id=:elementId";
1573
- return this._iModel.withPreparedStatement(sql, (statement) => {
1574
- statement.bindId("elementId", elementId);
1575
- const childIds = [];
1576
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1577
- childIds.push(statement.getValue(0).getId());
1578
- }
1579
- return childIds;
1580
- });
1581
- }
1582
- /** Query for the parent of the specified element.
1583
- * @param elementId The element to check for a parent
1584
- * @returns The identifier of the element's parent or undefined if the element has no parent
1585
- * @throws [[IModelError]] if the element does not exist
1586
- */
1587
- queryParent(elementId) {
1588
- return this._iModel.withPreparedStatement(`select parent.id from ${Element_1.Element.classFullName} where ecinstanceid=?`, (stmt) => {
1589
- stmt.bindId(1, elementId);
1590
- if (stmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
1591
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Element=${elementId}`);
1592
- const value = stmt.getValue(0);
1593
- return value.isNull ? undefined : value.getId();
1594
- });
1595
- }
1596
- /** Returns true if the specified Element has a sub-model.
1597
- * @see [[IModelDb.Models.getSubModel]]
1598
- */
1599
- hasSubModel(elementId) {
1600
- if (core_common_1.IModel.rootSubjectId === elementId)
1601
- return false; // Special case since the RepositoryModel does not sub-model the root Subject
1602
- // A sub-model will have the same Id value as the element it is describing
1603
- const sql = "SELECT ECInstanceId FROM BisCore:Model WHERE ECInstanceId=:elementId";
1604
- return this._iModel.withPreparedStatement(sql, (statement) => {
1605
- statement.bindId("elementId", elementId);
1606
- return core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step();
1607
- });
1608
- }
1609
- /** Get the root subject element. */
1610
- getRootSubject() { return this.getElement(core_common_1.IModel.rootSubjectId); }
1611
- /** Query for aspects of a particular class (polymorphically) associated with this element.
1612
- * @throws [[IModelError]]
1613
- * @note Most cases should use the [[getAspects]] wrapper rather than calling this method directly.
1614
- * @internal
1615
- */
1616
- _queryAspects(elementId, fromClassFullName, excludedClassFullNames) {
1617
- const sql = `SELECT ECInstanceId,ECClassId FROM ${fromClassFullName} WHERE Element.Id=:elementId ORDER BY ECClassId,ECInstanceId`; // ORDER BY to maximize statement reuse
1618
- return this._iModel.withPreparedStatement(sql, (statement) => {
1619
- statement.bindId("elementId", elementId);
1620
- const aspects = [];
1621
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1622
- const aspectInstanceId = statement.getValue(0).getId();
1623
- const aspectClassFullName = statement.getValue(1).getClassNameForClassId().replace(".", ":");
1624
- if ((undefined === excludedClassFullNames) || (!excludedClassFullNames.has(aspectClassFullName))) {
1625
- aspects.push(this._queryAspect(aspectInstanceId, aspectClassFullName));
1626
- }
1627
- }
1628
- return aspects;
1629
- });
1630
- }
1631
- /** Query for aspect by ECInstanceId
1632
- * @throws [[IModelError]]
1633
- */
1634
- _queryAspect(aspectInstanceId, aspectClassName) {
1635
- const sql = `SELECT * FROM ${aspectClassName} WHERE ECInstanceId=:aspectInstanceId`;
1636
- const aspect = this._iModel.withPreparedStatement(sql, (statement) => {
1637
- statement.bindId("aspectInstanceId", aspectInstanceId);
1638
- if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1639
- const aspectProps = statement.getRow(); // start with everything that SELECT * returned
1640
- aspectProps.classFullName = aspectProps.className.replace(".", ":"); // add in property required by EntityProps
1641
- aspectProps.className = undefined; // clear property from SELECT * that we don't want in the final instance
1642
- return aspectProps;
1643
- }
1644
- return undefined;
1645
- });
1646
- if (undefined === aspect) {
1647
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `ElementAspect not found ${aspectInstanceId}, ${aspectClassName}`);
1648
- }
1649
- return this._iModel.constructEntity(aspect);
1650
- }
1651
- /** Get a single ElementAspect by its instance Id.
1652
- * @throws [[IModelError]]
1653
- */
1654
- getAspect(aspectInstanceId) {
1655
- const sql = "SELECT ECClassId FROM BisCore:ElementAspect WHERE ECInstanceId=:aspectInstanceId";
1656
- const aspectClassFullName = this._iModel.withPreparedStatement(sql, (statement) => {
1657
- statement.bindId("aspectInstanceId", aspectInstanceId);
1658
- return (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getClassNameForClassId().replace(".", ":") : undefined;
1659
- });
1660
- if (undefined === aspectClassFullName) {
1661
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `ElementAspect not found ${aspectInstanceId}`);
1662
- }
1663
- return this._queryAspect(aspectInstanceId, aspectClassFullName);
1664
- }
1665
- /** Get the ElementAspect instances that are owned by the specified element.
1666
- * @param elementId Get ElementAspects associated with this Element
1667
- * @param aspectClassFullName Optionally filter ElementAspects polymorphically by this class name
1668
- * @throws [[IModelError]]
1669
- */
1670
- getAspects(elementId, aspectClassFullName) {
1671
- if (undefined === aspectClassFullName) {
1672
- const uniqueAspects = this._queryAspects(elementId, ElementAspect_1.ElementUniqueAspect.classFullName);
1673
- const multiAspects = this._queryAspects(elementId, ElementAspect_1.ElementMultiAspect.classFullName);
1674
- return uniqueAspects.concat(multiAspects);
1675
- }
1676
- const aspects = this._queryAspects(elementId, aspectClassFullName);
1677
- return aspects;
1678
- }
1679
- /** Insert a new ElementAspect into the iModel.
1680
- * @param aspectProps The properties of the new ElementAspect.
1681
- * @throws [[IModelError]] if unable to insert the ElementAspect.
1682
- * @returns the id of the newly inserted aspect.
1683
- * @note Aspect Ids may collide with element Ids, so don't put both in a container like Set or Map
1684
- * use [EntityReference]($common) for that instead.
1685
- */
1686
- insertAspect(aspectProps) {
1687
- try {
1688
- return this._iModel.nativeDb.insertElementAspect(aspectProps);
1689
- }
1690
- catch (err) {
1691
- throw new core_common_1.IModelError(err.errorNumber, `Error inserting ElementAspect [${err.message}], class: ${aspectProps.classFullName}`);
1692
- }
1693
- }
1694
- /** Update an exist ElementAspect within the iModel.
1695
- * @param aspectProps The properties to use to update the ElementAspect.
1696
- * @throws [[IModelError]] if unable to update the ElementAspect.
1697
- */
1698
- updateAspect(aspectProps) {
1699
- try {
1700
- this._iModel.nativeDb.updateElementAspect(aspectProps);
1701
- }
1702
- catch (err) {
1703
- throw new core_common_1.IModelError(err.errorNumber, `Error updating ElementAspect [${err.message}], id: ${aspectProps.id}`);
1704
- }
1705
- }
1706
- /** Delete one or more ElementAspects from this iModel.
1707
- * @param aspectInstanceIds The set of instance Ids of the ElementAspect(s) to be deleted
1708
- * @throws [[IModelError]] if unable to delete the ElementAspect.
1709
- */
1710
- deleteAspect(aspectInstanceIds) {
1711
- const iModel = this._iModel;
1712
- core_bentley_1.Id64.toIdSet(aspectInstanceIds).forEach((aspectInstanceId) => {
1713
- try {
1714
- iModel.nativeDb.deleteElementAspect(aspectInstanceId);
1715
- }
1716
- catch (err) {
1717
- throw new core_common_1.IModelError(err.errorNumber, `Error deleting ElementAspect [${err.message}], id: ${aspectInstanceId}`);
1718
- }
1719
- });
1720
- }
1721
- }
1722
- IModelDb.Elements = Elements;
1723
- /** The collection of views in an [[IModelDb]].
1724
- * @public
1725
- */
1726
- class Views {
1727
- /** @internal */
1728
- constructor(_iModel) {
1729
- this._iModel = _iModel;
1730
- }
1731
- /** Query for the array of ViewDefinitionProps of the specified class and matching the specified IsPrivate setting.
1732
- * @param className Query for view definitions of this class.
1733
- * @param wantPrivate If true, include private view definitions.
1734
- */
1735
- queryViewDefinitionProps(className = "BisCore.ViewDefinition", limit = IModelDb.defaultLimit, offset = 0, wantPrivate = false) {
1736
- const where = (wantPrivate === false) ? "IsPrivate=FALSE" : "";
1737
- const ids = this._iModel.queryEntityIds({ from: className, limit, offset, where });
1738
- const props = [];
1739
- const imodel = this._iModel;
1740
- ids.forEach((id) => {
1741
- try {
1742
- props.push(imodel.elements.getElementProps(id));
1743
- }
1744
- catch (err) { }
1745
- });
1746
- return props;
1747
- }
1748
- /** Iterate all ViewDefinitions matching the supplied query.
1749
- * @param params Specifies the query by which views are selected.
1750
- * @param callback Function invoked for each ViewDefinition matching the query. Return false to terminate iteration, true to continue.
1751
- * @returns true if all views were iterated, false if iteration was terminated early due to callback returning false.
1752
- *
1753
- * **Example: Finding all views of a specific DrawingModel**
1754
- * ``` ts
1755
- * [[include:IModelDb.Views.iterateViews]]
1756
- * ```
1757
- */
1758
- iterateViews(params, callback) {
1759
- const ids = this._iModel.queryEntityIds(params);
1760
- let finished = true;
1761
- for (const id of ids) {
1762
- try {
1763
- const view = this._iModel.elements.getElement(id);
1764
- if (undefined !== view && view instanceof ViewDefinition_1.ViewDefinition) {
1765
- finished = callback(view);
1766
- if (!finished)
1767
- break;
1768
- }
1769
- }
1770
- catch (err) { }
1771
- }
1772
- return finished;
1773
- }
1774
- loadViewStateProps(viewDefinitionElement, options, drawingExtents) {
1775
- const elements = this._iModel.elements;
1776
- const viewDefinitionProps = viewDefinitionElement.toJSON();
1777
- const categorySelectorProps = elements.getElementProps(viewDefinitionProps.categorySelectorId);
1778
- const displayStyleProps = elements.getElementProps({
1779
- id: viewDefinitionProps.displayStyleId,
1780
- displayStyle: options?.displayStyle,
1781
- });
1782
- const viewStateData = {
1783
- viewDefinitionProps,
1784
- displayStyleProps,
1785
- categorySelectorProps,
1786
- };
1787
- const modelSelectorId = viewDefinitionProps.modelSelectorId;
1788
- if (modelSelectorId !== undefined) {
1789
- viewStateData.modelSelectorProps = elements.getElementProps(modelSelectorId);
1790
- }
1791
- else if (viewDefinitionElement instanceof ViewDefinition_1.SheetViewDefinition) {
1792
- viewStateData.sheetProps = elements.getElementProps(viewDefinitionElement.baseModelId);
1793
- viewStateData.sheetAttachments = Array.from(this._iModel.queryEntityIds({
1794
- from: "BisCore.ViewAttachment",
1795
- where: `Model.Id=${viewDefinitionElement.baseModelId}`,
1796
- }));
1797
- }
1798
- else if (viewDefinitionElement instanceof ViewDefinition_1.DrawingViewDefinition) {
1799
- // Ensure view has known extents
1800
- if (drawingExtents && !drawingExtents.isNull)
1801
- viewStateData.modelExtents = drawingExtents.toJSON();
1802
- // Include information about the associated [[SectionDrawing]], if any.
1803
- // NB: The SectionDrawing ECClass may not exist in the iModel's version of the BisCore ECSchema.
1804
- try {
1805
- const sectionDrawing = this._iModel.elements.tryGetElement(viewDefinitionElement.baseModelId);
1806
- if (sectionDrawing && sectionDrawing.spatialView && core_bentley_1.Id64.isValidId64(sectionDrawing.spatialView.id)) {
1807
- viewStateData.sectionDrawing = {
1808
- spatialView: sectionDrawing.spatialView.id,
1809
- displaySpatialView: true === sectionDrawing.jsonProperties.displaySpatialView,
1810
- drawingToSpatialTransform: sectionDrawing.jsonProperties.drawingToSpatialTransform,
1811
- };
1812
- }
1813
- }
1814
- catch {
1815
- //
1816
- }
1817
- }
1818
- return viewStateData;
1819
- }
1820
- /** @deprecated in 3.x. use [[getViewStateProps]]. */
1821
- getViewStateData(viewDefinitionId, options) {
1822
- const view = this._iModel.elements.getElement(viewDefinitionId);
1823
- let drawingExtents;
1824
- if (view instanceof ViewDefinition_1.DrawingViewDefinition) {
1825
- try {
1826
- drawingExtents = core_geometry_1.Range3d.fromJSON(this._iModel.nativeDb.queryModelExtents({ id: view.baseModelId }).modelExtents);
1827
- }
1828
- catch {
1829
- //
1830
- }
1831
- }
1832
- return this.loadViewStateProps(view, options, drawingExtents);
1833
- }
1834
- /** Obtain a [ViewStateProps]($common) for a [[ViewDefinition]] specified by element Id. */
1835
- async getViewStateProps(viewDefinitionId, options) {
1836
- const view = this._iModel.elements.getElement(viewDefinitionId);
1837
- let drawingExtents;
1838
- if (view instanceof ViewDefinition_1.DrawingViewDefinition)
1839
- drawingExtents = (await this._iModel.models.queryRange(view.baseModelId));
1840
- return this.loadViewStateProps(view, options, drawingExtents);
1841
- }
1842
- getViewThumbnailArg(viewDefinitionId) {
1843
- return { namespace: "dgn_View", name: "Thumbnail", id: viewDefinitionId };
1844
- }
1845
- /** Get the thumbnail for a view.
1846
- * @param viewDefinitionId The Id of the view for thumbnail
1847
- * @returns the ThumbnailProps, or undefined if no thumbnail exists.
1848
- */
1849
- getThumbnail(viewDefinitionId) {
1850
- const viewArg = this.getViewThumbnailArg(viewDefinitionId);
1851
- const sizeProps = this._iModel.nativeDb.queryFileProperty(viewArg, true);
1852
- if (undefined === sizeProps)
1853
- return undefined;
1854
- const out = JSON.parse(sizeProps);
1855
- out.image = this._iModel.nativeDb.queryFileProperty(viewArg, false);
1856
- return out;
1857
- }
1858
- /** Save a thumbnail for a view.
1859
- * @param viewDefinitionId The Id of the view for thumbnail
1860
- * @param thumbnail The thumbnail data.
1861
- * @returns 0 if successful
1862
- */
1863
- saveThumbnail(viewDefinitionId, thumbnail) {
1864
- const viewArg = this.getViewThumbnailArg(viewDefinitionId);
1865
- const props = { format: thumbnail.format, height: thumbnail.height, width: thumbnail.width };
1866
- this._iModel.nativeDb.saveFileProperty(viewArg, JSON.stringify(props), thumbnail.image);
1867
- return 0;
1868
- }
1869
- /** Set the default view property the iModel
1870
- * @param viewId The Id of the ViewDefinition to use as the default
1871
- */
1872
- setDefaultViewId(viewId) {
1873
- const spec = { namespace: "dgn_View", name: "DefaultView" };
1874
- const blob32 = new Uint32Array(2);
1875
- blob32[0] = core_bentley_1.Id64.getLowerUint32(viewId);
1876
- blob32[1] = core_bentley_1.Id64.getUpperUint32(viewId);
1877
- const blob8 = new Uint8Array(blob32.buffer);
1878
- this._iModel.saveFileProperty(spec, undefined, blob8);
1879
- }
1880
- }
1881
- /** Default parameters for iterating/querying ViewDefinitions. Includes all subclasses of ViewDefinition, excluding only those marked 'private'. */
1882
- Views.defaultQueryParams = { from: "BisCore.ViewDefinition", where: "IsPrivate=FALSE" };
1883
- IModelDb.Views = Views;
1884
- /** Represents the current state of a pollable tile content request.
1885
- * Note: lack of a "completed" state because polling a completed request returns the content as a Uint8Array.
1886
- * @internal
1887
- */
1888
- let TileContentState;
1889
- (function (TileContentState) {
1890
- TileContentState[TileContentState["New"] = 0] = "New";
1891
- TileContentState[TileContentState["Pending"] = 1] = "Pending";
1892
- TileContentState[TileContentState["Loading"] = 2] = "Loading";
1893
- })(TileContentState = IModelDb.TileContentState || (IModelDb.TileContentState = {}));
1894
- /** @internal */
1895
- class Tiles {
1896
- /** @internal */
1897
- constructor(_iModel) {
1898
- this._iModel = _iModel;
1899
- }
1900
- /** @internal */
1901
- async requestTileTreeProps(id) {
1902
- return new Promise((resolve, reject) => {
1903
- this._iModel.nativeDb.getTileTree(id, (ret) => {
1904
- if (undefined !== ret.error)
1905
- reject(new core_common_1.IModelError(ret.error.status, `TreeId=${id}`));
1906
- else
1907
- resolve(ret.result);
1908
- });
1909
- });
1910
- }
1911
- pollTileContent(resolve, reject, treeId, tileId) {
1912
- let ret;
1913
- try {
1914
- ret = this._iModel.nativeDb.pollTileContent(treeId, tileId);
1915
- }
1916
- catch (err) {
1917
- // Typically "imodel not open".
1918
- reject(err);
1919
- return;
1920
- }
1921
- if (ret.error) {
1922
- reject(new core_common_1.IModelError(ret.error.status, `TreeId=${treeId} TileId=${tileId}`));
1923
- }
1924
- else if (ret.result && typeof ret.result !== "number") { // if type is not a number, it's the TileContent interface
1925
- const res = ret.result;
1926
- const iModelId = this._iModel.iModelId;
1927
- const tileSizeThreshold = IModelHost_1.IModelHost.logTileSizeThreshold;
1928
- const tileSize = res.content.length;
1929
- if (tileSize > tileSizeThreshold) {
1930
- core_bentley_1.Logger.logWarning(loggerCategory, "Tile size (in bytes) larger than specified threshold", () => ({ tileSize, tileSizeThreshold, treeId, tileId, iModelId }));
1931
- }
1932
- const loadTimeThreshold = IModelHost_1.IModelHost.logTileLoadTimeThreshold;
1933
- const loadTime = res.elapsedSeconds;
1934
- if (loadTime > loadTimeThreshold) {
1935
- core_bentley_1.Logger.logWarning(loggerCategory, "Tile load time (in seconds) greater than specified threshold", () => ({ loadTime, loadTimeThreshold, treeId, tileId, iModelId }));
1936
- }
1937
- resolve(res);
1938
- }
1939
- else { // if the type is a number, it's the TileContentState enum
1940
- // ###TODO: Decide appropriate timeout interval. May want to switch on state (new vs loading vs pending)
1941
- setTimeout(() => this.pollTileContent(resolve, reject, treeId, tileId), 10);
1942
- }
1943
- }
1944
- /** @internal */
1945
- async requestTileContent(treeId, tileId) {
1946
- return new Promise((resolve, reject) => {
1947
- this.pollTileContent(resolve, reject, treeId, tileId);
1948
- });
1949
- }
1950
- /** @internal */
1951
- async getTileContent(treeId, tileId) {
1952
- const ret = await new Promise((resolve) => {
1953
- this._iModel.nativeDb.getTileContent(treeId, tileId, resolve);
1954
- });
1955
- if (undefined !== ret.error) {
1956
- throw new core_common_1.IModelError(ret.error.status, `TreeId=${treeId} TileId=${tileId}`);
1957
- }
1958
- (0, core_bentley_1.assert)(undefined !== ret.result);
1959
- return ret.result;
1960
- }
1961
- }
1962
- IModelDb.Tiles = Tiles;
1963
- })(IModelDb = exports.IModelDb || (exports.IModelDb = {}));
1964
- /**
1965
- * A local copy of an iModel from iModelHub that can pull and potentially push changesets.
1966
- * BriefcaseDb raises a set of events to allow apps and subsystems to track its object life cycle, including [[onOpen]] and [[onOpened]].
1967
- * @public
1968
- */
1969
- class BriefcaseDb extends IModelDb {
1970
- constructor(args) {
1971
- super({ ...args, changeset: args.nativeDb.getCurrentChangeset() });
1972
- /** Manages local changes to this briefcase. */
1973
- this.txns = new TxnManager_1.TxnManager(this);
1974
- this._openMode = args.openMode;
1975
- this.briefcaseId = args.briefcaseId;
1976
- if (this.useLockServer) // if the iModel uses a lock server, create a ServerBasedLocks LockControl for this BriefcaseDb.
1977
- this._locks = new ServerBasedLocks_1.ServerBasedLocks(this);
1978
- }
1979
- /** override superclass method */
1980
- get isBriefcase() { return true; }
1981
- static findByKey(key) {
1982
- return super.findByKey(key);
1983
- }
1984
- static tryFindByKey(key) {
1985
- const db = super.tryFindByKey(key);
1986
- return db?.isBriefcaseDb() ? db : undefined;
1987
- }
1988
- /**
1989
- * The Guid that identifies the *context* that owns this iModel.
1990
- * GuidString | undefined for the superclass, but required for BriefcaseDb
1991
- * */
1992
- get iTwinId() { return super.iTwinId; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
1993
- /**
1994
- * Determine whether this BriefcaseDb should use a lock server.
1995
- * All must be true:
1996
- * - file is open for write
1997
- * - has an assigned briefcaseId
1998
- * - the "no locking" flag is not present. This is a property of an iModel, established when the iModel is created in IModelHub.
1999
- */
2000
- get useLockServer() {
2001
- return !this.isReadonly && (this.briefcaseId !== core_common_1.BriefcaseIdValue.Unassigned) && (undefined === this.nativeDb.queryLocalValue(BriefcaseLocalValue.NoLocking));
2002
- }
2003
- /** Upgrades the profile or domain schemas. File must be closed before this call and is always left closed. */
2004
- static async doUpgrade(briefcase, upgradeOptions, description) {
2005
- const nativeDb = this.openDgnDb({ path: briefcase.fileName }, core_bentley_1.OpenMode.ReadWrite, upgradeOptions); // performs the upgrade
2006
- const wasChanges = nativeDb.hasPendingTxns();
2007
- nativeDb.closeIModel();
2008
- if (wasChanges)
2009
- await withBriefcaseDb(briefcase, async (db) => db.pushChanges({ ...briefcase, description, retainLocks: true }));
2010
- }
2011
- /** Upgrades the schemas in the iModel based on the current version of the software. Follows a sequence of operations -
2012
- * * Acquires a schema lock to prevent other users from making any other changes while upgrade is happening
2013
- * * Updates the local briefcase with the schema changes.
2014
- * * Pushes the resulting changeset(s) to iModelHub.
2015
- * Note that the upgrade requires that the local briefcase be closed, and may result in one or two change sets depending on whether both
2016
- * profile and domain schemas need to get upgraded.
2017
- * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
2018
- */
2019
- static async upgradeSchemas(briefcase) {
2020
- // upgrading schemas involves closing and reopening the file repeatedly. That's because the process of upgrading
2021
- // happens on a file open. We have to open-and-close the file at *each* of these steps:
2022
- // - acquire schema lock
2023
- // - upgrade profile
2024
- // - push changes
2025
- // - upgrade domain
2026
- // - push changes
2027
- // - release schema lock
2028
- // good thing computers are fast. Fortunately upgrading should be rare (and the push time will dominate anyway.) Don't try to optimize any of this away.
2029
- await withBriefcaseDb(briefcase, async (db) => db.acquireSchemaLock()); // may not really acquire lock if iModel uses "noLocks" mode.
2030
- try {
2031
- await this.doUpgrade(briefcase, { profile: core_common_1.ProfileOptions.Upgrade, schemaLockHeld: true }, "Upgraded profile");
2032
- await this.doUpgrade(briefcase, { domain: core_common_1.DomainOptions.Upgrade, schemaLockHeld: true }, "Upgraded domain schemas");
2033
- }
2034
- finally {
2035
- await withBriefcaseDb(briefcase, async (db) => db.locks.releaseAllLocks());
2036
- }
2037
- }
2038
- /** Open a briefcase file and return a new BriefcaseDb to interact with it.
2039
- * @param args parameters that specify the file name, and options for opening the briefcase file
2040
- */
2041
- static async open(args) {
2042
- this.onOpen.raiseEvent(args);
2043
- const file = { path: args.fileName, key: args.key };
2044
- const openMode = args.readonly ? core_bentley_1.OpenMode.Readonly : core_bentley_1.OpenMode.ReadWrite;
2045
- const nativeDb = this.openDgnDb(file, openMode, undefined, args);
2046
- const briefcaseDb = new BriefcaseDb({ nativeDb, key: file.key ?? core_bentley_1.Guid.createValue(), openMode, briefcaseId: nativeDb.getBriefcaseId() });
2047
- if (openMode === core_bentley_1.OpenMode.ReadWrite && CodeService_1.CodeService.createForIModel) {
2048
- try {
2049
- const codeService = CodeService_1.CodeService.createForIModel(briefcaseDb);
2050
- briefcaseDb._codeService = codeService;
2051
- this.onCodeServiceCreated.raiseEvent(codeService);
2052
- }
2053
- catch (e) {
2054
- if (e.errorId !== "NoCodeIndex") // no code index means iModel isn't enforcing codes.
2055
- throw e;
2056
- }
2057
- }
2058
- BriefcaseManager_1.BriefcaseManager.logUsage(briefcaseDb);
2059
- this.onOpened.raiseEvent(briefcaseDb, args);
2060
- return briefcaseDb;
2061
- }
2062
- closeAndReopen(openMode) {
2063
- const fileName = this.pathName;
2064
- this.nativeDb.closeIModel();
2065
- this.nativeDb.openIModel(fileName, openMode);
2066
- }
2067
- /** Pull and apply changesets from iModelHub */
2068
- async pullChanges(arg) {
2069
- if (this.isReadonly) // we allow pulling changes into a briefcase that is readonly - close and reopen it writeable
2070
- this.closeAndReopen(core_bentley_1.OpenMode.ReadWrite);
2071
- try {
2072
- await BriefcaseManager_1.BriefcaseManager.pullAndApplyChangesets(this, arg ?? {});
2073
- this.initializeIModelDb();
2074
- }
2075
- finally {
2076
- if (this.isReadonly) // if the briefcase was opened readonly - close and reopen it readonly
2077
- this.closeAndReopen(core_bentley_1.OpenMode.Readonly);
2078
- }
2079
- IpcHost_1.IpcHost.notifyTxns(this, "notifyPulledChanges", this.changeset);
2080
- }
2081
- /** Push changes to iModelHub. */
2082
- async pushChanges(arg) {
2083
- if (this.briefcaseId === core_common_1.BriefcaseIdValue.Unassigned)
2084
- return;
2085
- if (this.nativeDb.hasUnsavedChanges())
2086
- throw new core_common_1.IModelError(core_bentley_1.ChangeSetStatus.HasUncommittedChanges, "Cannot push with unsaved changes");
2087
- if (!this.nativeDb.hasPendingTxns())
2088
- return; // nothing to push
2089
- await BriefcaseManager_1.BriefcaseManager.pullMergePush(this, arg);
2090
- this.initializeIModelDb();
2091
- const changeset = this.changeset;
2092
- IpcHost_1.IpcHost.notifyTxns(this, "notifyPushedChanges", changeset);
2093
- }
2094
- }
2095
- exports.BriefcaseDb = BriefcaseDb;
2096
- /**
2097
- * Event raised just before a BriefcaseDb is opened. Supplies the arguments that will be used to open the BriefcaseDb.
2098
- * Throw an exception to stop the open.
2099
- *
2100
- * **Example:**
2101
- * ``` ts
2102
- * [[include:BriefcaseDb.onOpen]]
2103
- * ```
2104
- */
2105
- BriefcaseDb.onOpen = new core_bentley_1.BeEvent();
2106
- /**
2107
- * Event raised just after a BriefcaseDb is opened. Supplies the newly opened BriefcaseDb and the arguments that were used to open it.
2108
- *
2109
- * **Example:**
2110
- * ``` ts
2111
- * [[include:BriefcaseDb.onOpened]]
2112
- * ```
2113
- */
2114
- BriefcaseDb.onOpened = new core_bentley_1.BeEvent();
2115
- /** @alpha */
2116
- BriefcaseDb.onCodeServiceCreated = new core_bentley_1.BeEvent();
2117
- /** Used to reattach Daemon from a user's accessToken for V2 checkpoints.
2118
- * @note Reattach only happens if the previous access token either has expired or is about to expire within an application-supplied safety duration.
2119
- */
2120
- class RefreshV2CheckpointSas {
2121
- constructor(sasToken, safetySeconds) {
2122
- /** the time at which the current token should be refreshed (its expiry minus safetySeconds) */
2123
- this._timestamp = 0;
2124
- this._safetySeconds = safetySeconds ?? 60 * 60; // default to 1 hour
2125
- this.setTimestamp(sasToken);
2126
- }
2127
- async performRefresh(accessToken, iModel) {
2128
- this._timestamp = 0; // everyone needs to wait until token is valid
2129
- // we're going to request that the checkpoint manager use this user's accessToken to obtain a new access token for this checkpoint's storage account.
2130
- core_bentley_1.Logger.logInfo(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "attempting to refresh sasToken for checkpoint");
2131
- try {
2132
- // this exchanges the supplied user accessToken for an expiring blob-store token to read the checkpoint.
2133
- const container = iModel.nativeDb.cloudContainer;
2134
- if (!container)
2135
- throw new Error("checkpoint is not from a cloud container");
2136
- (0, core_bentley_1.assert)(undefined !== iModel.iTwinId);
2137
- const props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint({ accessToken, iTwinId: iModel.iTwinId, iModelId: iModel.iModelId, changeset: iModel.changeset });
2138
- if (!props)
2139
- throw new Error("can't reset checkpoint sas token");
2140
- container.accessToken = props.sasToken;
2141
- this.setTimestamp(props.sasToken);
2142
- core_bentley_1.Logger.logInfo(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "refreshed checkpoint sasToken successfully");
2143
- }
2144
- finally {
2145
- this._promise = undefined;
2146
- }
2147
- }
2148
- setTimestamp(sasToken) {
2149
- const exp = new URLSearchParams(sasToken).get("se");
2150
- const sasTokenExpiry = exp ? Date.parse(exp) : 0;
2151
- this._timestamp = sasTokenExpiry - (this._safetySeconds * 1000);
2152
- if (this._timestamp < Date.now())
2153
- core_bentley_1.Logger.logError(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "attached with timestamp that expires before safety interval");
2154
- }
2155
- async refreshSas(accessToken, iModel) {
2156
- if (this._timestamp > Date.now())
2157
- return; // current token is fine
2158
- if (undefined === this._promise) // has reattach already begun?
2159
- this._promise = this.performRefresh(accessToken, iModel); // no, start it
2160
- return this._promise;
2161
- }
2162
- }
2163
- /** A *snapshot* iModel database file that is used for archival and data transfer purposes.
2164
- * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2165
- * @see [About IModelDb]($docs/learning/backend/IModelDb.md)
2166
- * @public
2167
- */
2168
- class SnapshotDb extends IModelDb {
2169
- constructor(nativeDb, key) {
2170
- super({ nativeDb, key, changeset: nativeDb.getCurrentChangeset() });
2171
- this._openMode = nativeDb.isReadonly() ? core_bentley_1.OpenMode.Readonly : core_bentley_1.OpenMode.ReadWrite;
2172
- }
2173
- get isSnapshot() { return true; }
2174
- static findByKey(key) {
2175
- return super.findByKey(key);
2176
- }
2177
- static tryFindByKey(key) {
2178
- const db = super.tryFindByKey(key);
2179
- return db?.isSnapshotDb() ? db : undefined;
2180
- }
2181
- /** Create an *empty* local [Snapshot]($docs/learning/backend/AccessingIModels.md#snapshot-imodels) iModel file.
2182
- * Snapshots are not synchronized with iModelHub, so do not have a change timeline.
2183
- * > Note: A *snapshot* cannot be modified after [[close]] is called.
2184
- * @param filePath The file that will contain the new iModel *snapshot*
2185
- * @param options The parameters that define the new iModel *snapshot*
2186
- * @returns A writeable SnapshotDb
2187
- * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2188
- */
2189
- static createEmpty(filePath, options) {
2190
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2191
- nativeDb.createIModel(filePath, options);
2192
- nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2193
- const snapshotDb = new SnapshotDb(nativeDb, core_bentley_1.Guid.createValue());
2194
- if (options.createClassViews)
2195
- snapshotDb._createClassViewsOnClose = true; // save flag that will be checked when close() is called
2196
- return snapshotDb;
2197
- }
2198
- /** Create a local [Snapshot]($docs/learning/backend/AccessingIModels.md#snapshot-imodels) iModel file, using this iModel as a *seed* or starting point.
2199
- * Snapshots are not synchronized with iModelHub, so do not have a change timeline.
2200
- * > Note: A *snapshot* cannot be modified after [[close]] is called.
2201
- * @param iModelDb The snapshot will be initialized from the current contents of this iModelDb
2202
- * @param snapshotFile The file that will contain the new iModel *snapshot*
2203
- * @param options Optional properties that determine how the snapshot iModel is created.
2204
- * @returns A writeable SnapshotDb
2205
- * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2206
- */
2207
- static createFrom(iModelDb, snapshotFile, options) {
2208
- iModelDb.performCheckpoint();
2209
- IModelJsFs_1.IModelJsFs.copySync(iModelDb.pathName, snapshotFile);
2210
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2211
- nativeDb.openIModel(snapshotFile, core_bentley_1.OpenMode.ReadWrite, undefined, options);
2212
- nativeDb.vacuum();
2213
- // Replace iModelId if seedFile is a snapshot, preserve iModelId if seedFile is an iModelHub-managed briefcase
2214
- if (!BriefcaseManager_1.BriefcaseManager.isValidBriefcaseId(nativeDb.getBriefcaseId()))
2215
- nativeDb.setIModelId(core_bentley_1.Guid.createValue());
2216
- nativeDb.deleteLocalValue(BriefcaseLocalValue.StandaloneEdit);
2217
- nativeDb.saveChanges();
2218
- nativeDb.deleteAllTxns();
2219
- nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2220
- const snapshotDb = new SnapshotDb(nativeDb, core_bentley_1.Guid.createValue());
2221
- if (options?.createClassViews)
2222
- snapshotDb._createClassViewsOnClose = true; // save flag that will be checked when close() is called
2223
- return snapshotDb;
2224
- }
2225
- /** open this SnapshotDb read/write, strictly to apply incoming changesets. Used for creating new checkpoints.
2226
- * @internal
2227
- */
2228
- static openForApplyChangesets(path, props) {
2229
- const file = { path, key: props?.key };
2230
- const nativeDb = this.openDgnDb(file, core_bentley_1.OpenMode.ReadWrite, undefined, props);
2231
- (0, core_bentley_1.assert)(undefined !== file.key);
2232
- return new SnapshotDb(nativeDb, file.key);
2233
- }
2234
- /** Open a read-only iModel *snapshot*.
2235
- * @param path the full path of the snapshot iModel file to open.
2236
- * @param props options for opening snapshot
2237
- * @see [[close]]
2238
- * @throws [[IModelError]] If the file is not found or is not a valid *snapshot*.
2239
- */
2240
- static openFile(path, opts) {
2241
- const file = { path, key: opts?.key };
2242
- const nativeDb = this.openDgnDb(file, core_bentley_1.OpenMode.Readonly, undefined, opts);
2243
- (0, core_bentley_1.assert)(undefined !== file.key);
2244
- return new SnapshotDb(nativeDb, file.key);
2245
- }
2246
- /** Open a previously downloaded V1 checkpoint file.
2247
- * @note The key is generated by this call is predictable and is formed from the IModelId and ChangeSetId.
2248
- * This is so every backend working on the same checkpoint will use the same key, to permit multiple backends
2249
- * servicing the same checkpoint.
2250
- * @internal
2251
- */
2252
- static openCheckpointV1(fileName, checkpoint) {
2253
- const snapshot = this.openFile(fileName, { key: CheckpointManager_1.CheckpointManager.getKey(checkpoint) });
2254
- snapshot._iTwinId = checkpoint.iTwinId;
2255
- return snapshot;
2256
- }
2257
- /** Open a V2 *checkpoint*, a special form of snapshot iModel that represents a read-only snapshot of an iModel from iModelHub at a particular point in time.
2258
- * > Note: The checkpoint daemon must already be running and a checkpoint must already exist in iModelHub's storage *before* this function is called.
2259
- * @param checkpoint The checkpoint to open
2260
- * @note The key generated by this call is predictable and is formed from the IModelId and ChangeSetId.
2261
- * This is so every backend working on the same checkpoint will use the same key, to permit multiple backends
2262
- * servicing the same checkpoint.
2263
- * @throws [[IModelError]] If the checkpoint is not found in iModelHub or the checkpoint daemon is not supported in the current environment.
2264
- * @internal
2265
- */
2266
- static async openCheckpointV2(checkpoint) {
2267
- const { dbName, container } = await CheckpointManager_1.V2CheckpointManager.attach(checkpoint);
2268
- const key = CheckpointManager_1.CheckpointManager.getKey(checkpoint);
2269
- const tempFileBase = (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, `${checkpoint.iModelId}\$${checkpoint.changeset.id}`); // temp files for this checkpoint should go in the cacheDir.
2270
- const snapshot = SnapshotDb.openFile(dbName, { key, tempFileBase, container });
2271
- snapshot._iTwinId = checkpoint.iTwinId;
2272
- try {
2273
- CheckpointManager_1.CheckpointManager.validateCheckpointGuids(checkpoint, snapshot);
2274
- }
2275
- catch (err) {
2276
- snapshot.close();
2277
- throw err;
2278
- }
2279
- snapshot._refreshSas = new RefreshV2CheckpointSas(container.accessToken, checkpoint.reattachSafetySeconds);
2280
- return snapshot;
2281
- }
2282
- /** Used to refresh the container sasToken using the current user's accessToken
2283
- * @internal
2284
- */
2285
- async refreshContainerSas(userAccessToken) {
2286
- return this._refreshSas?.refreshSas(userAccessToken, this);
2287
- }
2288
- /** @internal */
2289
- beforeClose() {
2290
- super.beforeClose();
2291
- if (this._createClassViewsOnClose) { // check for flag set during create
2292
- if (core_bentley_1.BentleyStatus.SUCCESS !== this.nativeDb.createClassViewsInDb()) {
2293
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.SQLiteError, "Error creating class views");
2294
- }
2295
- else {
2296
- this.saveChanges();
2297
- }
2298
- }
2299
- }
2300
- }
2301
- exports.SnapshotDb = SnapshotDb;
2302
- /**
2303
- * Standalone iModels are read/write files that are not associated with an iTwin or managed by iModelHub.
2304
- * They are relevant only for testing, or for small-scale single-user scenarios.
2305
- * Standalone iModels are designed such that the API for Standalone iModels and Briefcase
2306
- * iModels (those synchronized with iModelHub) are as similar and consistent as possible.
2307
- * This leads to a straightforward process where the a user starts with StandaloneDb and can
2308
- * optionally choose to upgrade to an iTwin.
2309
- *
2310
- * Some additional details. Standalone iModels:
2311
- * - always have [Guid.empty]($bentley) for their iTwinId (they are "unassociated" files)
2312
- * - always have BriefcaseId === [BriefcaseIdValue.Unassigned]($common)
2313
- * - are connected to the frontend via [BriefcaseConnection.openStandalone]($frontend)
2314
- * - may be opened without supplying any user credentials
2315
- * - may be opened read/write
2316
- * - cannot apply a changeset to nor generate a changesets (since there is no timeline from which to get/push changesets)
2317
- * @public
2318
- */
2319
- class StandaloneDb extends BriefcaseDb {
2320
- get isStandalone() { return true; }
2321
- get useLockServer() { return false; } // standalone iModels have no lock server
2322
- static findByKey(key) {
2323
- return super.findByKey(key);
2324
- }
2325
- static tryFindByKey(key) {
2326
- const db = super.tryFindByKey(key);
2327
- return db?.isStandaloneDb() ? db : undefined;
2328
- }
2329
- /** Create an *empty* standalone iModel.
2330
- * @param filePath The file path for the iModel
2331
- * @param args The parameters that define the new iModel
2332
- */
2333
- static createEmpty(filePath, args) {
2334
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2335
- nativeDb.createIModel(filePath, args);
2336
- nativeDb.saveLocalValue(BriefcaseLocalValue.StandaloneEdit, args.allowEdit);
2337
- nativeDb.setITwinId(core_bentley_1.Guid.empty);
2338
- nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2339
- nativeDb.saveChanges();
2340
- return new StandaloneDb({ nativeDb, key: core_bentley_1.Guid.createValue(), briefcaseId: core_common_1.BriefcaseIdValue.Unassigned, openMode: core_bentley_1.OpenMode.ReadWrite });
2341
- }
2342
- /**
2343
- * Upgrades the schemas in the standalone iModel file.
2344
- * Note that the upgrade requires that the file be closed, and will leave it back in the closed state.
2345
- * @param filePath Full path name of the standalone iModel file.
2346
- * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
2347
- * @see [[StandaloneDb.validateSchemas]]
2348
- */
2349
- static upgradeStandaloneSchemas(filePath) {
2350
- let nativeDb = this.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.ReadWrite, { profile: core_common_1.ProfileOptions.Upgrade, schemaLockHeld: true });
2351
- nativeDb.closeIModel();
2352
- nativeDb = this.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.ReadWrite, { domain: core_common_1.DomainOptions.Upgrade, schemaLockHeld: true });
2353
- nativeDb.closeIModel();
2354
- }
2355
- /** Open a standalone iModel file.
2356
- * @param filePath The path of the standalone iModel file.
2357
- * @param openMode Optional open mode for the standalone iModel. The default is read/write.
2358
- * @throws [[IModelError]] if the file is not a standalone iModel.
2359
- * @see [BriefcaseConnection.openStandalone]($frontend) to open a StandaloneDb from the frontend
2360
- */
2361
- static openFile(filePath, openMode = core_bentley_1.OpenMode.ReadWrite, options) {
2362
- const file = { path: filePath, key: options?.key };
2363
- const nativeDb = this.openDgnDb(file, openMode, undefined, options);
2364
- try {
2365
- const iTwinId = nativeDb.getITwinId();
2366
- if (iTwinId !== core_bentley_1.Guid.empty) // a "standalone" iModel means it is not associated with an iTwin
2367
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.WrongIModel, `${filePath} is not a Standalone iModel. iTwinId=${iTwinId}`);
2368
- (0, core_bentley_1.assert)(undefined !== file.key);
2369
- return new StandaloneDb({ nativeDb, key: file.key, openMode, briefcaseId: core_common_1.BriefcaseIdValue.Unassigned });
2370
- }
2371
- catch (error) {
2372
- nativeDb.closeIModel();
2373
- throw error;
2374
- }
2375
- }
2376
- }
2377
- exports.StandaloneDb = StandaloneDb;
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
+ * See LICENSE.md in the project root for license terms and full copyright notice.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ /** @packageDocumentation
7
+ * @module iModels
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.StandaloneDb = exports.SnapshotDb = exports.BriefcaseDb = exports.IModelDb = exports.BriefcaseLocalValue = void 0;
11
+ const path_1 = require("path");
12
+ const core_bentley_1 = require("@itwin/core-bentley");
13
+ const core_common_1 = require("@itwin/core-common");
14
+ const core_geometry_1 = require("@itwin/core-geometry");
15
+ const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
16
+ const BriefcaseManager_1 = require("./BriefcaseManager");
17
+ const CheckpointManager_1 = require("./CheckpointManager");
18
+ const ClassRegistry_1 = require("./ClassRegistry");
19
+ const CodeService_1 = require("./CodeService");
20
+ const CodeSpecs_1 = require("./CodeSpecs");
21
+ const ConcurrentQuery_1 = require("./ConcurrentQuery");
22
+ const ECSqlStatement_1 = require("./ECSqlStatement");
23
+ const Element_1 = require("./Element");
24
+ const ElementAspect_1 = require("./ElementAspect");
25
+ const ElementGraphics_1 = require("./ElementGraphics");
26
+ const GeoCoordConfig_1 = require("./GeoCoordConfig");
27
+ const IModelHost_1 = require("./IModelHost");
28
+ const IModelJsFs_1 = require("./IModelJsFs");
29
+ const IpcHost_1 = require("./IpcHost");
30
+ const Model_1 = require("./Model");
31
+ const Relationship_1 = require("./Relationship");
32
+ const ServerBasedLocks_1 = require("./ServerBasedLocks");
33
+ const SqliteStatement_1 = require("./SqliteStatement");
34
+ const TxnManager_1 = require("./TxnManager");
35
+ const ViewDefinition_1 = require("./ViewDefinition");
36
+ const Settings_1 = require("./workspace/Settings");
37
+ const Workspace_1 = require("./workspace/Workspace");
38
+ // spell:ignore fontid fontmap
39
+ const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
40
+ /** A null-implementation of LockControl that does not attempt to limit access between briefcases. This relies on change-merging to resolve conflicts. */
41
+ class NoLocks {
42
+ get isServerBased() { return false; }
43
+ close() { }
44
+ clearAllLocks() { }
45
+ holdsExclusiveLock() { return false; }
46
+ holdsSharedLock() { return false; }
47
+ checkExclusiveLock() { }
48
+ checkSharedLock() { }
49
+ elementWasCreated() { }
50
+ async acquireLocks() { }
51
+ async releaseAllLocks() { }
52
+ }
53
+ /** @internal */
54
+ var BriefcaseLocalValue;
55
+ (function (BriefcaseLocalValue) {
56
+ BriefcaseLocalValue["StandaloneEdit"] = "StandaloneEdit";
57
+ BriefcaseLocalValue["NoLocking"] = "NoLocking";
58
+ })(BriefcaseLocalValue = exports.BriefcaseLocalValue || (exports.BriefcaseLocalValue = {}));
59
+ // function to open an briefcaseDb, perform an operation, and then close it.
60
+ const withBriefcaseDb = async (briefcase, fn) => {
61
+ const db = await BriefcaseDb.open(briefcase);
62
+ try {
63
+ return await fn(db);
64
+ }
65
+ finally {
66
+ db.close();
67
+ }
68
+ };
69
+ /**
70
+ * Settings for an individual iModel. May only include settings priority for iModel, iTwin and organization.
71
+ * @note if there is more than one iModel for an iTwin or organization, they will *each* hold a copy of the settings for those priorities.
72
+ */
73
+ class IModelSettings extends Settings_1.BaseSettings {
74
+ verifyPriority(priority) {
75
+ if (priority <= Settings_1.SettingsPriority.application)
76
+ throw new Error("Use IModelHost.appSettings");
77
+ }
78
+ // attempt to resolve a setting from this iModel's settings, otherwise use appWorkspace's settings, otherwise defaultValue.
79
+ resolveSetting(name, resolver, defaultValue) {
80
+ return super.resolveSetting(name, resolver) ?? IModelHost_1.IModelHost.appWorkspace.settings.resolveSetting(name, resolver, defaultValue);
81
+ }
82
+ }
83
+ /** An iModel database file. The database file can either be a briefcase or a snapshot.
84
+ * @see [Accessing iModels]($docs/learning/backend/AccessingIModels.md)
85
+ * @see [About IModelDb]($docs/learning/backend/IModelDb.md)
86
+ * @public
87
+ */
88
+ class IModelDb extends core_common_1.IModel {
89
+ /** @internal */
90
+ constructor(args) {
91
+ super({ ...args, iTwinId: args.nativeDb.getITwinId(), iModelId: args.nativeDb.getIModelId() });
92
+ this._initialized = false;
93
+ this.models = new IModelDb.Models(this);
94
+ this.elements = new IModelDb.Elements(this);
95
+ this.views = new IModelDb.Views(this);
96
+ this.tiles = new IModelDb.Tiles(this);
97
+ this._statementCache = new SqliteStatement_1.StatementCache();
98
+ this._sqliteStatementCache = new SqliteStatement_1.StatementCache();
99
+ this._snaps = new Map();
100
+ /** @internal */
101
+ this._locks = new NoLocks();
102
+ /** Event called after a changeset is applied to this IModelDb. */
103
+ this.onChangesetApplied = new core_bentley_1.BeEvent();
104
+ /** Event called when the iModel is about to be closed. */
105
+ this.onBeforeClose = new core_bentley_1.BeEvent();
106
+ this._nativeDb = args.nativeDb;
107
+ this.nativeDb.setIModelDb(this);
108
+ this.loadSettingDictionaries();
109
+ GeoCoordConfig_1.GeoCoordConfig.loadForImodel(this.workspace.settings); // load gcs data specified by iModel's settings dictionaries, must be done before calling initializeIModelDb
110
+ this.initializeIModelDb();
111
+ IModelDb._openDbs.set(this._fileKey, this);
112
+ if (undefined === IModelDb._shutdownListener) { // the first time we create an IModelDb, add a listener to close any orphan files at shutdown.
113
+ IModelDb._shutdownListener = IModelHost_1.IModelHost.onBeforeShutdown.addListener(() => {
114
+ IModelDb._openDbs.forEach((db) => {
115
+ try {
116
+ db.abandonChanges();
117
+ db.close();
118
+ }
119
+ catch { }
120
+ });
121
+ });
122
+ }
123
+ }
124
+ /** @alpha */
125
+ get codeService() { return this._codeService; }
126
+ /**
127
+ * Get the [[LockControl]] for this iModel.
128
+ * @beta
129
+ */
130
+ get locks() { return this._locks; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
131
+ /**
132
+ * Get the [[Workspace]] for this iModel.
133
+ * @beta
134
+ */
135
+ get workspace() {
136
+ if (undefined === this._workspace)
137
+ this._workspace = new Workspace_1.ITwinWorkspace(new IModelSettings());
138
+ return this._workspace;
139
+ }
140
+ /** Acquire the exclusive schema lock on this iModel.
141
+ * > Note: To acquire the schema lock, all other briefcases must first release *all* their locks. No other briefcases
142
+ * will be able to acquire *any* locks while the schema lock is held.
143
+ */
144
+ async acquireSchemaLock() {
145
+ return this.locks.acquireLocks({ exclusive: core_common_1.IModel.repositoryModelId });
146
+ }
147
+ /** determine whether the schema lock is currently held for this iModel. */
148
+ get holdsSchemaLock() {
149
+ return this.locks.holdsExclusiveLock(core_common_1.IModel.repositoryModelId);
150
+ }
151
+ /** @internal */
152
+ notifyChangesetApplied() {
153
+ this.changeset = this.nativeDb.getCurrentChangeset();
154
+ this.onChangesetApplied.raiseEvent();
155
+ }
156
+ get fontMap() {
157
+ return this._fontMap ?? (this._fontMap = new core_common_1.FontMap(this.nativeDb.readFontMap()));
158
+ }
159
+ /** @internal */
160
+ clearFontMap() {
161
+ this._fontMap = undefined;
162
+ }
163
+ /**
164
+ * Add a new font name/type to the FontMap for this iModel and return its FontId.
165
+ * @param name The name of the font to add
166
+ * @param type The type of the font. Default is TrueType.
167
+ * @returns The FontId for the newly added font. If a font by that name/type already exists, this method does not fail, it returns the existing Id.
168
+ * @see [FontId and FontMap]($docs/learning/backend/Fonts.md#fontid-and-fontmap)
169
+ * @beta
170
+ */
171
+ addNewFont(name, type) {
172
+ this.locks.checkExclusiveLock(core_common_1.IModel.repositoryModelId, "schema", "addNewFont");
173
+ this.clearFontMap();
174
+ return this.nativeDb.addNewFont({ name, type: type ?? core_common_1.FontType.TrueType });
175
+ }
176
+ /** Check if this iModel has been opened read-only or not. */
177
+ get isReadonly() { return this.openMode === core_bentley_1.OpenMode.Readonly; }
178
+ /** The Guid that identifies this iModel. */
179
+ get iModelId() {
180
+ (0, core_bentley_1.assert)(undefined !== super.iModelId);
181
+ return super.iModelId;
182
+ } // GuidString | undefined for the IModel superclass, but required for all IModelDb subclasses
183
+ /** @internal*/
184
+ get nativeDb() { return this._nativeDb; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
185
+ /** Get the full path fileName of this iModelDb
186
+ * @note this member is only valid while the iModel is opened.
187
+ */
188
+ get pathName() { return this.nativeDb.getFilePath(); }
189
+ /** Close this IModel, if it is currently open. */
190
+ close() {
191
+ if (!this.isOpen)
192
+ return; // don't continue if already closed
193
+ this.beforeClose();
194
+ IModelDb._openDbs.delete(this._fileKey);
195
+ this._workspace?.close();
196
+ this.locks.close();
197
+ this._locks = undefined;
198
+ this._codeService?.close();
199
+ this._codeService = undefined;
200
+ this.nativeDb.closeIModel();
201
+ this._nativeDb = undefined; // the underlying nativeDb has been freed by closeIModel
202
+ }
203
+ /** @internal */
204
+ async refreshContainerSas(_userAccessToken) { }
205
+ /**
206
+ * Called by derived classes before closing the connection
207
+ * @internal
208
+ */
209
+ beforeClose() {
210
+ this.onBeforeClose.raiseEvent();
211
+ this.clearCaches();
212
+ }
213
+ /** @internal */
214
+ initializeIModelDb() {
215
+ const props = this.nativeDb.getIModelProps();
216
+ super.initialize(props.rootSubject.name, props);
217
+ if (this._initialized)
218
+ return;
219
+ this._initialized = true;
220
+ const db = this.isBriefcaseDb() ? this : undefined;
221
+ if (!db || !IpcHost_1.IpcHost.isValid)
222
+ return;
223
+ db.onNameChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyIModelNameChanged", db.name));
224
+ db.onRootSubjectChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyRootSubjectChanged", db.rootSubject));
225
+ db.onProjectExtentsChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyProjectExtentsChanged", db.projectExtents.toJSON()));
226
+ db.onGlobalOriginChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyGlobalOriginChanged", db.globalOrigin.toJSON()));
227
+ db.onEcefLocationChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyEcefLocationChanged", db.ecefLocation?.toJSON()));
228
+ db.onGeographicCoordinateSystemChanged.addListener(() => IpcHost_1.IpcHost.notifyTxns(db, "notifyGeographicCoordinateSystemChanged", db.geographicCoordinateSystem?.toJSON()));
229
+ }
230
+ /** Returns true if this is a BriefcaseDb
231
+ * @see [[BriefcaseDb.open]]
232
+ */
233
+ get isBriefcase() { return false; }
234
+ /** Type guard for instanceof [[BriefcaseDb]] */
235
+ isBriefcaseDb() { return this.isBriefcase; }
236
+ /** Returns true if this is a SnapshotDb
237
+ * @see [[SnapshotDb.open]]
238
+ */
239
+ get isSnapshot() { return false; }
240
+ /** Type guard for instanceof [[SnapshotDb]] */
241
+ isSnapshotDb() { return this.isSnapshot; }
242
+ /** Returns true if this is a *standalone* iModel
243
+ * @see [[StandaloneDb.open]]
244
+ * @internal
245
+ */
246
+ get isStandalone() { return false; }
247
+ /** Type guard for instanceof [[StandaloneDb]]
248
+ * @internal
249
+ */
250
+ isStandaloneDb() { return this.isStandalone; }
251
+ /** Return `true` if the underlying nativeDb is open and valid.
252
+ * @internal
253
+ */
254
+ get isOpen() { return undefined !== this.nativeDb; }
255
+ /** Get the briefcase Id of this iModel */
256
+ getBriefcaseId() { return this.isOpen ? this.nativeDb.getBriefcaseId() : core_common_1.BriefcaseIdValue.Illegal; }
257
+ /**
258
+ * Use a prepared ECSQL statement, potentially from the statement cache. If the requested statement doesn't exist
259
+ * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
260
+ * in the statement cache so it can be reused in the future. Use this method for ECSQL statements that will be
261
+ * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
262
+ * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withStatement]].
263
+ * @param sql The SQLite SQL statement to execute
264
+ * @param callback the callback to invoke on the prepared statement
265
+ * @param logErrors Determines if error will be logged if statement fail to prepare
266
+ * @returns the value returned by `callback`.
267
+ * @see [[withStatement]]
268
+ * @public
269
+ */
270
+ withPreparedStatement(ecsql, callback, logErrors = true) {
271
+ const stmt = this._statementCache.findAndRemove(ecsql) ?? this.prepareStatement(ecsql, logErrors);
272
+ const release = () => this._statementCache.addOrDispose(stmt);
273
+ try {
274
+ const val = callback(stmt);
275
+ if (val instanceof Promise) {
276
+ val.then(release, release);
277
+ }
278
+ else {
279
+ release();
280
+ }
281
+ return val;
282
+ }
283
+ catch (err) {
284
+ release();
285
+ throw err;
286
+ }
287
+ }
288
+ /**
289
+ * Prepared and execute a callback on an ECSQL statement. After the callback completes the statement is disposed.
290
+ * Use this method for ECSQL statements are either not expected to be reused, or are not expensive to prepare.
291
+ * For statements that will be reused often, instead use [[withPreparedStatement]].
292
+ * @param sql The SQLite SQL statement to execute
293
+ * @param callback the callback to invoke on the prepared statement
294
+ * @param logErrors Determines if error will be logged if statement fail to prepare
295
+ * @returns the value returned by `callback`.
296
+ * @see [[withPreparedStatement]]
297
+ * @public
298
+ */
299
+ withStatement(ecsql, callback, logErrors = true) {
300
+ const stmt = this.prepareStatement(ecsql, logErrors);
301
+ const release = () => stmt.dispose();
302
+ try {
303
+ const val = callback(stmt);
304
+ if (val instanceof Promise) {
305
+ val.then(release, release);
306
+ }
307
+ else {
308
+ release();
309
+ }
310
+ return val;
311
+ }
312
+ catch (err) {
313
+ release();
314
+ throw err;
315
+ }
316
+ }
317
+ /** Allow to execute query and read results along with meta data. The result are streamed.
318
+ * @param params The values to bind to the parameters (if the ECSQL has any).
319
+ * @param config Allow to specify certain flags which control how query is executed.
320
+ * @returns Returns *ECSqlQueryReader* which help iterate over result set and also give access to meta data.
321
+ * @beta
322
+ * */
323
+ createQueryReader(ecsql, params, config) {
324
+ if (!this._nativeDb || !this._nativeDb.isOpen()) {
325
+ throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "db not open");
326
+ }
327
+ const executor = {
328
+ execute: async (request) => {
329
+ return ConcurrentQuery_1.ConcurrentQuery.executeQueryRequest(this.nativeDb, request);
330
+ },
331
+ };
332
+ return new core_common_1.ECSqlReader(executor, ecsql, params, config);
333
+ }
334
+ /** Execute a query and stream its results
335
+ * The result of the query is async iterator over the rows. The iterator will get next page automatically once rows in current page has been read.
336
+ * [ECSQL row]($docs/learning/ECSQLRowFormat).
337
+ *
338
+ * See also:
339
+ * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
340
+ * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
341
+ *
342
+ * @param ecsql The ECSQL statement to execute
343
+ * @param params The values to bind to the parameters (if the ECSQL has any).
344
+ * @param options Allow to specify certain flags which control how query is executed.
345
+ * @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
346
+ * See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
347
+ * @throws [IModelError]($common) If there was any error while submitting, preparing or stepping into query
348
+ */
349
+ async *query(ecsql, params, options) {
350
+ const builder = new core_common_1.QueryOptionsBuilder(options);
351
+ const reader = this.createQueryReader(ecsql, params, builder.getOptions());
352
+ while (await reader.step())
353
+ yield reader.formatCurrentRow();
354
+ }
355
+ /** Compute number of rows that would be returned by the ECSQL.
356
+ *
357
+ * See also:
358
+ * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
359
+ * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
360
+ *
361
+ * @param ecsql The ECSQL statement to execute
362
+ * @param params The values to bind to the parameters (if the ECSQL has any).
363
+ * See "[iTwin.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
364
+ * @returns Return row count.
365
+ * @throws [IModelError]($common) If the statement is invalid
366
+ */
367
+ async queryRowCount(ecsql, params) {
368
+ for await (const row of this.query(`select count(*) from (${ecsql})`, params)) {
369
+ return row[0];
370
+ }
371
+ throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "Failed to get row count");
372
+ }
373
+ /** Cancel any previous query with same token and run execute the current specified query.
374
+ * The result of the query is async iterator over the rows. The iterator will get next page automatically once rows in current page has been read.
375
+ * [ECSQL row]($docs/learning/ECSQLRowFormat).
376
+ *
377
+ * See also:
378
+ * - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
379
+ * - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
380
+ *
381
+ * @param ecsql The ECSQL statement to execute
382
+ * @param token None empty restart token. The previous query with same token would be cancelled. This would cause
383
+ * exception which user code must handle.
384
+ * @param params The values to bind to the parameters (if the ECSQL has any).
385
+ * @param options Allow to specify certain flags which control how query is executed.
386
+ * @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
387
+ * See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
388
+ * @throws [IModelError]($common) If there was any error while submitting, preparing or stepping into query
389
+ */
390
+ async *restartQuery(token, ecsql, params, options) {
391
+ for await (const row of this.query(ecsql, params, new core_common_1.QueryOptionsBuilder(options).setRestartToken(token).getOptions())) {
392
+ yield row;
393
+ }
394
+ }
395
+ /**
396
+ * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist
397
+ * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
398
+ * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be
399
+ * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
400
+ * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].
401
+ * @param sql The SQLite SQL statement to execute
402
+ * @param callback the callback to invoke on the prepared statement
403
+ * @param logErrors Determine if errors are logged or not
404
+ * @returns the value returned by `callback`.
405
+ * @see [[withPreparedStatement]]
406
+ * @public
407
+ */
408
+ withPreparedSqliteStatement(sql, callback, logErrors = true) {
409
+ const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql, logErrors);
410
+ const release = () => this._sqliteStatementCache.addOrDispose(stmt);
411
+ try {
412
+ const val = callback(stmt);
413
+ if (val instanceof Promise) {
414
+ val.then(release, release);
415
+ }
416
+ else {
417
+ release();
418
+ }
419
+ return val;
420
+ }
421
+ catch (err) {
422
+ release();
423
+ throw err;
424
+ }
425
+ }
426
+ /**
427
+ * Prepared and execute a callback on a SQL statement. After the callback completes the statement is disposed.
428
+ * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.
429
+ * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].
430
+ * @param sql The SQLite SQL statement to execute
431
+ * @param callback the callback to invoke on the prepared statement
432
+ * @param logErrors Determine if errors are logged or not
433
+ * @returns the value returned by `callback`.
434
+ * @public
435
+ */
436
+ withSqliteStatement(sql, callback, logErrors = true) {
437
+ const stmt = this.prepareSqliteStatement(sql, logErrors);
438
+ const release = () => stmt.dispose();
439
+ try {
440
+ const val = callback(stmt);
441
+ if (val instanceof Promise) {
442
+ val.then(release, release);
443
+ }
444
+ else {
445
+ release();
446
+ }
447
+ return val;
448
+ }
449
+ catch (err) {
450
+ release();
451
+ throw err;
452
+ }
453
+ }
454
+ /** Prepare an SQL statement.
455
+ * @param sql The SQL statement to prepare
456
+ * @throws [[IModelError]] if there is a problem preparing the statement.
457
+ * @internal
458
+ */
459
+ prepareSqliteStatement(sql, logErrors = true) {
460
+ const stmt = new SqliteStatement_1.SqliteStatement(sql);
461
+ stmt.prepare(this.nativeDb, logErrors);
462
+ return stmt;
463
+ }
464
+ /**
465
+ * queries the BisCore.SubCategory table for the entries that are children of the passed categoryIds
466
+ * @param categoryIds categoryIds to query
467
+ * @returns array of SubCategoryResultRow
468
+ * @internal
469
+ */
470
+ async querySubCategories(categoryIds) {
471
+ const result = [];
472
+ const where = [...categoryIds].join(",");
473
+ const query = `SELECT ECInstanceId as id, Parent.Id as parentId, Properties as appearance FROM BisCore.SubCategory WHERE Parent.Id IN (${where})`;
474
+ try {
475
+ for await (const row of this.query(query, undefined, { rowFormat: core_common_1.QueryRowFormat.UseJsPropertyNames })) {
476
+ result.push(row);
477
+ }
478
+ }
479
+ catch {
480
+ // We can ignore the error here, and just return whatever we were able to query.
481
+ }
482
+ return result;
483
+ }
484
+ /** Query for a set of entity ids, given an EntityQueryParams
485
+ * @param params The query parameters. The `limit` and `offset` members should be used to page results.
486
+ * @returns an Id64Set with results of query
487
+ * @throws [[IModelError]] if the generated statement is invalid or [IModelDb.maxLimit]($backend) exceeded when collecting ids.
488
+ *
489
+ * *Example:*
490
+ * ``` ts
491
+ * [[include:ECSQL-backend-queries.select-element-by-code-value-using-queryEntityIds]]
492
+ * ```
493
+ */
494
+ queryEntityIds(params) {
495
+ let sql = "SELECT ECInstanceId FROM ";
496
+ if (params.only)
497
+ sql += "ONLY ";
498
+ sql += params.from;
499
+ if (params.where)
500
+ sql += ` WHERE ${params.where}`;
501
+ if (params.orderBy)
502
+ sql += ` ORDER BY ${params.orderBy}`;
503
+ if (typeof params.limit === "number" && params.limit > 0)
504
+ sql += ` LIMIT ${params.limit}`;
505
+ if (typeof params.offset === "number" && params.offset > 0)
506
+ sql += ` OFFSET ${params.offset}`;
507
+ const ids = new Set();
508
+ this.withPreparedStatement(sql, (stmt) => {
509
+ if (params.bindings)
510
+ stmt.bindValues(params.bindings);
511
+ for (const row of stmt) {
512
+ if (row.id !== undefined) {
513
+ ids.add(row.id);
514
+ if (ids.size > IModelDb.maxLimit) {
515
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Max LIMIT exceeded in SELECT statement");
516
+ }
517
+ }
518
+ }
519
+ });
520
+ return ids;
521
+ }
522
+ /** Clear all in-memory caches held in this IModelDb. */
523
+ clearCaches() {
524
+ this._statementCache.clear();
525
+ this._sqliteStatementCache.clear();
526
+ }
527
+ /** Update the project extents for this iModel.
528
+ * <p><em>Example:</em>
529
+ * ``` ts
530
+ * [[include:IModelDb.updateProjectExtents]]
531
+ * ```
532
+ */
533
+ updateProjectExtents(newExtents) {
534
+ this.projectExtents = newExtents;
535
+ this.updateIModelProps();
536
+ }
537
+ /** Compute an appropriate project extents for this iModel based on the ranges of all spatial elements.
538
+ * Typically, the result is simply the union of the ranges of all spatial elements. However, the algorithm also detects "outlier elements",
539
+ * whose placements locate them so far from the rest of the spatial geometry that they are considered statistically insignificant. The
540
+ * range of an outlier element does not contribute to the computed extents.
541
+ * @param options Specifies the level of detail desired in the return value.
542
+ * @returns the computed extents.
543
+ * @note This method does not modify the IModel's stored project extents. @see [[updateProjectExtents]].
544
+ */
545
+ computeProjectExtents(options) {
546
+ const wantFullExtents = true === options?.reportExtentsWithOutliers;
547
+ const wantOutliers = true === options?.reportOutliers;
548
+ const result = this.nativeDb.computeProjectExtents(wantFullExtents, wantOutliers);
549
+ return {
550
+ extents: core_geometry_1.Range3d.fromJSON(result.extents),
551
+ extentsWithOutliers: result.fullExtents ? core_geometry_1.Range3d.fromJSON(result.fullExtents) : undefined,
552
+ outliers: result.outliers,
553
+ };
554
+ }
555
+ /** Update the [EcefLocation]($docs/learning/glossary#eceflocation) of this iModel. */
556
+ updateEcefLocation(ecef) {
557
+ this.setEcefLocation(ecef);
558
+ this.updateIModelProps();
559
+ }
560
+ /** Update the IModelProps of this iModel in the database. */
561
+ updateIModelProps() {
562
+ this.nativeDb.updateIModelProps(this.toJSON());
563
+ }
564
+ /** Commit pending changes to this iModel.
565
+ * @param description Optional description of the changes
566
+ * @throws [[IModelError]] if there is a problem saving changes or if there are pending, un-processed lock or code requests.
567
+ */
568
+ saveChanges(description) {
569
+ if (this.openMode === core_bentley_1.OpenMode.Readonly)
570
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ReadOnly, "IModelDb was opened read-only");
571
+ const stat = this.nativeDb.saveChanges(description);
572
+ if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat)
573
+ throw new core_common_1.IModelError(stat, `Could not save changes (${description})`);
574
+ }
575
+ /** Abandon pending changes in this iModel. */
576
+ abandonChanges() {
577
+ this.nativeDb.abandonChanges();
578
+ }
579
+ /**
580
+ * Save all changes and perform a [checkpoint](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) on this IModelDb.
581
+ * This ensures that all changes to the database since it was opened are saved to its file and the WAL file is truncated.
582
+ * @note Checkpoint automatically happens when IModelDbs are closed. However, the checkpoint
583
+ * operation itself can take some time. It may be useful to call this method prior to closing so that the checkpoint "penalty" is paid earlier.
584
+ * @note Another use for this function is to permit the file to be copied while it is open for write. iModel files should
585
+ * rarely be copied, and even less so while they're opened. But this scenario is sometimes encountered for tests.
586
+ */
587
+ performCheckpoint() {
588
+ if (!this.isReadonly) {
589
+ this.saveChanges();
590
+ this.nativeDb.performCheckpoint();
591
+ }
592
+ }
593
+ /** @internal */
594
+ reverseTxns(numOperations) {
595
+ return this.nativeDb.reverseTxns(numOperations);
596
+ }
597
+ /** @internal */
598
+ reinstateTxn() {
599
+ return this.nativeDb.reinstateTxn();
600
+ }
601
+ /** @internal */
602
+ restartTxnSession() {
603
+ return this.nativeDb.restartTxnSession();
604
+ }
605
+ /** Import an ECSchema. On success, the schema definition is stored in the iModel.
606
+ * This method is asynchronous (must be awaited) because, in the case where this IModelDb is a briefcase, this method first obtains the schema lock from the iModel server.
607
+ * You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
608
+ * @param schemaFileName array of Full paths to ECSchema.xml files to be imported.
609
+ * @param {SchemaImportOptions} options - options during schema import.
610
+ * @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
611
+ * @note Changes are saved if importSchemas is successful and abandoned if not successful.
612
+ * @see querySchemaVersion
613
+ */
614
+ async importSchemas(schemaFileNames, options) {
615
+ if (this.nativeDb.getITwinId() !== core_bentley_1.Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
616
+ await this.acquireSchemaLock();
617
+ const maybeCustomNativeContext = options?.ecSchemaXmlContext?.nativeContext;
618
+ const nativeImportOptions = {
619
+ schemaLockHeld: true,
620
+ ecSchemaXmlContext: maybeCustomNativeContext,
621
+ };
622
+ const stat = this.nativeDb.importSchemas(schemaFileNames, nativeImportOptions);
623
+ if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat) {
624
+ throw new core_common_1.IModelError(stat, "Error importing schema");
625
+ }
626
+ this.clearCaches();
627
+ }
628
+ /** Import ECSchema(s) serialized to XML. On success, the schema definition is stored in the iModel.
629
+ * This method is asynchronous (must be awaited) because, in the case where this IModelDb is a briefcase, this method first obtains the schema lock from the iModel server.
630
+ * You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
631
+ * @param serializedXmlSchemas The xml string(s) created from a serialized ECSchema.
632
+ * @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
633
+ * @note Changes are saved if importSchemaStrings is successful and abandoned if not successful.
634
+ * @see querySchemaVersion
635
+ * @alpha
636
+ */
637
+ async importSchemaStrings(serializedXmlSchemas) {
638
+ if (this.iTwinId && this.iTwinId !== core_bentley_1.Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
639
+ await this.acquireSchemaLock();
640
+ const stat = this.nativeDb.importXmlSchemas(serializedXmlSchemas, { schemaLockHeld: true });
641
+ if (core_bentley_1.DbResult.BE_SQLITE_OK !== stat)
642
+ throw new core_common_1.IModelError(stat, "Error importing schema");
643
+ this.clearCaches();
644
+ }
645
+ /** Find an opened instance of any subclass of IModelDb, by filename
646
+ * @note this method returns an IModelDb if the filename is open for *any* subclass of IModelDb
647
+ */
648
+ static findByFilename(fileName) {
649
+ for (const entry of this._openDbs) {
650
+ if (entry[1].pathName === fileName)
651
+ return entry[1];
652
+ }
653
+ return undefined;
654
+ }
655
+ /** Find an open IModelDb by its key.
656
+ * @note This method is mainly for use by RPC implementations.
657
+ * @throws [[IModelNotFoundResponse]] if an open IModelDb matching the key is not found.
658
+ * @see [IModel.key]($common)
659
+ */
660
+ static findByKey(key) {
661
+ const iModelDb = this.tryFindByKey(key);
662
+ if (undefined === iModelDb)
663
+ throw new core_common_1.IModelNotFoundResponse(); // a very specific status for the RpcManager
664
+ return iModelDb;
665
+ }
666
+ /** Attempt to find an open IModelDb by key.
667
+ * @returns The matching IModelDb or `undefined`.
668
+ */
669
+ static tryFindByKey(key) {
670
+ return this._openDbs.get(key);
671
+ }
672
+ /** @internal */
673
+ static openDgnDb(file, openMode, upgradeOptions, props) {
674
+ file.key = file.key ?? core_bentley_1.Guid.createValue();
675
+ if (this.tryFindByKey(file.key))
676
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.AlreadyOpen, `key [${file.key}] for file [${file.path}] is already in use`);
677
+ const isUpgradeRequested = upgradeOptions?.domain === core_common_1.DomainOptions.Upgrade || upgradeOptions?.profile === core_common_1.ProfileOptions.Upgrade;
678
+ if (isUpgradeRequested && openMode !== core_bentley_1.OpenMode.ReadWrite)
679
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.UpgradeFailed, "Cannot upgrade a Readonly Db");
680
+ try {
681
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
682
+ nativeDb.openIModel(file.path, openMode, upgradeOptions, props, props?.container);
683
+ return nativeDb;
684
+ }
685
+ catch (err) {
686
+ throw new core_common_1.IModelError(err.errorNumber, `${err.message}, ${file.path}`);
687
+ }
688
+ }
689
+ /**
690
+ * Determines if the schemas in the Db must or can be upgraded by comparing them with those included in the
691
+ * current version of the software.
692
+ * @param filePath Full name of the briefcase including path
693
+ * @param forReadWrite Pass true if validating for read-write scenarios - note that the schema version requirements
694
+ * for opening the DgnDb read-write is more stringent than when opening the database read-only
695
+ * @throws [[IModelError]] If the Db was in an invalid state and that causes a problem with validating schemas
696
+ * @see [[BriefcaseDb.upgradeSchemas]] or [[StandaloneDb.upgradeSchemas]]
697
+ * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
698
+ */
699
+ static validateSchemas(filePath, forReadWrite) {
700
+ const openMode = forReadWrite ? core_bentley_1.OpenMode.ReadWrite : core_bentley_1.OpenMode.Readonly;
701
+ const file = { path: filePath };
702
+ let result = core_bentley_1.DbResult.BE_SQLITE_OK;
703
+ try {
704
+ const upgradeOptions = {
705
+ domain: core_common_1.DomainOptions.CheckRecommendedUpgrades,
706
+ };
707
+ const nativeDb = this.openDgnDb(file, openMode, upgradeOptions);
708
+ nativeDb.closeIModel();
709
+ }
710
+ catch (err) {
711
+ result = err.errorNumber;
712
+ }
713
+ let schemaState = core_common_1.SchemaState.UpToDate;
714
+ switch (result) {
715
+ case core_bentley_1.DbResult.BE_SQLITE_OK:
716
+ schemaState = core_common_1.SchemaState.UpToDate;
717
+ break;
718
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooOld:
719
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooOldForReadWrite:
720
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaTooOld:
721
+ schemaState = core_common_1.SchemaState.TooOld;
722
+ break;
723
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooNew:
724
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_ProfileTooNewForReadWrite:
725
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaTooNew:
726
+ schemaState = core_common_1.SchemaState.TooNew;
727
+ break;
728
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaUpgradeRecommended:
729
+ schemaState = core_common_1.SchemaState.UpgradeRecommended;
730
+ break;
731
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_SchemaUpgradeRequired:
732
+ schemaState = core_common_1.SchemaState.UpgradeRequired;
733
+ break;
734
+ case core_bentley_1.DbResult.BE_SQLITE_ERROR_InvalidProfileVersion:
735
+ throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR_InvalidProfileVersion, "The profile of the Db is invalid. Cannot upgrade or open the Db.");
736
+ default:
737
+ throw new core_common_1.IModelError(core_bentley_1.DbResult.BE_SQLITE_ERROR, "Error validating schemas. Cannot upgrade or open the Db.");
738
+ }
739
+ return schemaState;
740
+ }
741
+ /** Get the ClassMetaDataRegistry for this iModel.
742
+ * @internal
743
+ */
744
+ get classMetaDataRegistry() {
745
+ if (this._classMetaDataRegistry === undefined)
746
+ this._classMetaDataRegistry = new ClassRegistry_1.MetaDataRegistry();
747
+ return this._classMetaDataRegistry;
748
+ }
749
+ /** Get the linkTableRelationships for this IModel */
750
+ get relationships() {
751
+ return this._relationships || (this._relationships = new Relationship_1.Relationships(this));
752
+ }
753
+ /** Get the CodeSpecs in this IModel. */
754
+ get codeSpecs() {
755
+ return (this._codeSpecs !== undefined) ? this._codeSpecs : (this._codeSpecs = new CodeSpecs_1.CodeSpecs(this));
756
+ }
757
+ /** @internal */
758
+ insertCodeSpec(codeSpec) {
759
+ return this.nativeDb.insertCodeSpec(codeSpec.name, codeSpec.properties); // TODO: Remove "as any" when NativeLibrary.ts is updated so "spec" isn't marked as required
760
+ }
761
+ /** Prepare an ECSQL statement.
762
+ * @param sql The ECSQL statement to prepare
763
+ * @param logErrors Determines if error will be logged if statement fail to prepare
764
+ * @throws [[IModelError]] if there is a problem preparing the statement.
765
+ */
766
+ prepareStatement(sql, logErrors = true) {
767
+ const stmt = new ECSqlStatement_1.ECSqlStatement();
768
+ stmt.prepare(this.nativeDb, sql, logErrors);
769
+ return stmt;
770
+ }
771
+ /** Prepare an ECSQL statement.
772
+ * @param sql The ECSQL statement to prepare
773
+ * @returns `undefined` if there is a problem preparing the statement.
774
+ */
775
+ tryPrepareStatement(sql) {
776
+ const statement = new ECSqlStatement_1.ECSqlStatement();
777
+ const result = statement.tryPrepare(this.nativeDb, sql);
778
+ return core_bentley_1.DbResult.BE_SQLITE_OK === result.status ? statement : undefined;
779
+ }
780
+ /** Construct an entity (Element or Model) from an iModel.
781
+ * @throws [[IModelError]] if the entity cannot be constructed.
782
+ */
783
+ constructEntity(props) {
784
+ const jsClass = this.getJsClass(props.classFullName);
785
+ return new jsClass(props, this);
786
+ }
787
+ /** Get the JavaScript class that handles a given entity class. */
788
+ getJsClass(classFullName) {
789
+ try {
790
+ return ClassRegistry_1.ClassRegistry.getClass(classFullName, this);
791
+ }
792
+ catch (err) {
793
+ if (!ClassRegistry_1.ClassRegistry.isNotFoundError(err)) {
794
+ throw err;
795
+ }
796
+ this.loadMetaData(classFullName);
797
+ return ClassRegistry_1.ClassRegistry.getClass(classFullName, this);
798
+ }
799
+ }
800
+ /** Get metadata for a class. This method will load the metadata from the iModel into the cache as a side-effect, if necessary.
801
+ * @throws [[IModelError]] if the metadata cannot be found nor loaded.
802
+ */
803
+ getMetaData(classFullName) {
804
+ let metadata = this.classMetaDataRegistry.find(classFullName);
805
+ if (metadata === undefined) {
806
+ this.loadMetaData(classFullName);
807
+ metadata = this.classMetaDataRegistry.find(classFullName);
808
+ if (metadata === undefined)
809
+ throw ClassRegistry_1.ClassRegistry.makeMetaDataNotFoundError(classFullName); // do not log
810
+ }
811
+ return metadata;
812
+ }
813
+ /** Invoke a callback on each property of the specified class, optionally including superclass properties.
814
+ * @param iModel The IModel that contains the schema
815
+ * @param classFullName The full class name to load the metadata, if necessary
816
+ * @param wantSuper If true, superclass properties will also be processed
817
+ * @param func The callback to be invoked on each property
818
+ * @param includeCustom If true (default), include custom-handled properties in the iteration. Otherwise, skip custom-handled properties.
819
+ * @note Custom-handled properties are core properties that have behavior enforced by C++ handlers.
820
+ */
821
+ static forEachMetaData(iModel, classFullName, wantSuper, func, includeCustom = true) {
822
+ const meta = iModel.getMetaData(classFullName); // will load if necessary
823
+ for (const propName in meta.properties) { // eslint-disable-line guard-for-in
824
+ const propMeta = meta.properties[propName];
825
+ if (includeCustom || !propMeta.isCustomHandled || propMeta.isCustomHandledOrphan)
826
+ func(propName, propMeta);
827
+ }
828
+ if (wantSuper && meta.baseClasses && meta.baseClasses.length > 0)
829
+ meta.baseClasses.forEach((baseClass) => this.forEachMetaData(iModel, baseClass, true, func, includeCustom));
830
+ }
831
+ /** @internal */
832
+ loadMetaData(classFullName) {
833
+ if (this.classMetaDataRegistry.find(classFullName))
834
+ return;
835
+ const className = classFullName.split(":");
836
+ if (className.length !== 2)
837
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadArg, `Invalid classFullName: ${classFullName}`);
838
+ const val = this.nativeDb.getECClassMetaData(className[0], className[1]);
839
+ if (val.error)
840
+ throw new core_common_1.IModelError(val.error.status, `Error getting class meta data for: ${classFullName}`);
841
+ (0, core_bentley_1.assert)(undefined !== val.result);
842
+ const metaData = new core_common_1.EntityMetaData(JSON.parse(val.result));
843
+ this.classMetaDataRegistry.add(classFullName, metaData);
844
+ // Recursive, to make sure that base classes are cached.
845
+ if (metaData.baseClasses !== undefined && metaData.baseClasses.length > 0)
846
+ metaData.baseClasses.forEach((baseClassName) => this.loadMetaData(baseClassName));
847
+ }
848
+ /** Returns the full schema for the input name.
849
+ * @param name The name of the schema e.g. 'BisCore'
850
+ * @returns The SchemaProps for the requested schema
851
+ * @throws if the schema can not be found or loaded.
852
+ */
853
+ getSchemaProps(name) {
854
+ return this.nativeDb.getSchemaProps(name);
855
+ }
856
+ /** Query if this iModel contains the definition of the specified class.
857
+ * @param classFullName The full name of the class, for example, SomeSchema:SomeClass
858
+ * @returns true if the iModel contains the class definition or false if not.
859
+ * @see querySchemaVersion
860
+ * @see importSchema
861
+ */
862
+ containsClass(classFullName) {
863
+ const classNameParts = classFullName.replace(".", ":").split(":");
864
+ return classNameParts.length === 2 && this.nativeDb.getECClassMetaData(classNameParts[0], classNameParts[1]).error === undefined;
865
+ }
866
+ /** Query for a schema of the specified name in this iModel.
867
+ * @returns The schema version as a semver-compatible string or `undefined` if the schema has not been imported.
868
+ */
869
+ querySchemaVersion(schemaName) {
870
+ const sql = `SELECT VersionMajor,VersionWrite,VersionMinor FROM ECDbMeta.ECSchemaDef WHERE Name=:schemaName LIMIT 1`;
871
+ return this.withPreparedStatement(sql, (statement) => {
872
+ statement.bindString("schemaName", schemaName);
873
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
874
+ const versionMajor = statement.getValue(0).getInteger(); // ECSchemaDef.VersionMajor --> semver.major
875
+ const versionWrite = statement.getValue(1).getInteger(); // ECSchemaDef.VersionWrite --> semver.minor
876
+ const versionMinor = statement.getValue(2).getInteger(); // ECSchemaDef.VersionMinor --> semver.patch
877
+ return `${versionMajor}.${versionWrite}.${versionMinor}`;
878
+ }
879
+ return undefined;
880
+ });
881
+ }
882
+ /** Retrieve a named texture image from this iModel, as a TextureData.
883
+ * @param props the texture load properties which must include the name of the texture to load
884
+ * @returns the TextureData or undefined if the texture image is not present.
885
+ * @alpha
886
+ */
887
+ async queryTextureData(props) {
888
+ return this.nativeDb.queryTextureData(props);
889
+ }
890
+ /** Query a "file property" from this iModel, as a string.
891
+ * @returns the property string or undefined if the property is not present.
892
+ */
893
+ queryFilePropertyString(prop) {
894
+ return this.nativeDb.queryFileProperty(prop, true);
895
+ }
896
+ /** Query a "file property" from this iModel, as a blob.
897
+ * @returns the property blob or undefined if the property is not present.
898
+ */
899
+ queryFilePropertyBlob(prop) {
900
+ return this.nativeDb.queryFileProperty(prop, false);
901
+ }
902
+ /** Save a "file property" to this iModel
903
+ * @param prop the FilePropertyProps that describes the new property
904
+ * @param value either a string or a blob to save as the file property
905
+ */
906
+ saveFileProperty(prop, strValue, blobVal) {
907
+ this.nativeDb.saveFileProperty(prop, strValue, blobVal);
908
+ }
909
+ /** delete a "file property" from this iModel
910
+ * @param prop the FilePropertyProps that describes the property
911
+ */
912
+ deleteFileProperty(prop) {
913
+ this.nativeDb.saveFileProperty(prop, undefined, undefined);
914
+ }
915
+ /** Query for the next available major id for a "file property" from this iModel.
916
+ * @param prop the FilePropertyProps that describes the property
917
+ * @returns the next available (that is, an unused) id for prop. If none are present, will return 0.
918
+ */
919
+ queryNextAvailableFileProperty(prop) { return this.nativeDb.queryNextAvailableFileProperty(prop); }
920
+ /** @internal */
921
+ async requestSnap(sessionId, props) {
922
+ let request = this._snaps.get(sessionId);
923
+ if (undefined === request) {
924
+ request = new IModelHost_1.IModelHost.platform.SnapRequest();
925
+ this._snaps.set(sessionId, request);
926
+ }
927
+ else
928
+ request.cancelSnap();
929
+ try {
930
+ return await request.doSnap(this.nativeDb, core_bentley_1.JsonUtils.toObject(props));
931
+ }
932
+ finally {
933
+ this._snaps.delete(sessionId);
934
+ }
935
+ }
936
+ /** Cancel a previously requested snap.
937
+ * @internal
938
+ */
939
+ cancelSnap(sessionId) {
940
+ const request = this._snaps.get(sessionId);
941
+ if (undefined !== request) {
942
+ request.cancelSnap();
943
+ this._snaps.delete(sessionId);
944
+ }
945
+ }
946
+ /** Get the clip containment status for the supplied elements. */
947
+ async getGeometryContainment(props) {
948
+ return this.nativeDb.getGeometryContainment(core_bentley_1.JsonUtils.toObject(props));
949
+ }
950
+ /** Get the mass properties for the supplied elements. */
951
+ async getMassProperties(props) {
952
+ return this.nativeDb.getMassProperties(core_bentley_1.JsonUtils.toObject(props));
953
+ }
954
+ /** Get the IModel coordinate corresponding to each GeoCoordinate point in the input */
955
+ async getIModelCoordinatesFromGeoCoordinates(props) {
956
+ return this.nativeDb.getIModelCoordinatesFromGeoCoordinates(props);
957
+ }
958
+ /** Get the GeoCoordinate (longitude, latitude, elevation) corresponding to each IModel Coordinate point in the input */
959
+ async getGeoCoordinatesFromIModelCoordinates(props) {
960
+ return this.nativeDb.getGeoCoordinatesFromIModelCoordinates(props);
961
+ }
962
+ /** Export meshes suitable for graphics APIs from arbitrary geometry in elements in this IModelDb.
963
+ * * Requests can be slow when processing many elements so it is expected that this function be used on a dedicated backend,
964
+ * or that shared backends export a limited number of elements at a time.
965
+ * * Vertices are exported in the IModelDb's world coordinate system, which is right-handed with Z pointing up.
966
+ * * The results of changing [ExportGraphicsOptions]($core-backend) during the [ExportGraphicsOptions.onGraphics]($core-backend) callback are not defined.
967
+ *
968
+ * Example that prints the mesh for element 1 to stdout in [OBJ format](https://en.wikipedia.org/wiki/Wavefront_.obj_file)
969
+ * ```ts
970
+ * const onGraphics: ExportGraphicsFunction = (info: ExportGraphicsInfo) => {
971
+ * const mesh: ExportGraphicsMesh = info.mesh;
972
+ * for (let i = 0; i < mesh.points.length; i += 3) {
973
+ * process.stdout.write(`v ${mesh.points[i]} ${mesh.points[i + 1]} ${mesh.points[i + 2]}\n`);
974
+ * process.stdout.write(`vn ${mesh.normals[i]} ${mesh.normals[i + 1]} ${mesh.normals[i + 2]}\n`);
975
+ * }
976
+ *
977
+ * for (let i = 0; i < mesh.params.length; i += 2) {
978
+ * process.stdout.write(`vt ${mesh.params[i]} ${mesh.params[i + 1]}\n`);
979
+ * }
980
+ *
981
+ * for (let i = 0; i < mesh.indices.length; i += 3) {
982
+ * const p1 = mesh.indices[i];
983
+ * const p2 = mesh.indices[i + 1];
984
+ * const p3 = mesh.indices[i + 2];
985
+ * process.stdout.write(`f ${p1}/${p1}/${p1} ${p2}/${p2}/${p2} ${p3}/${p3}/${p3}\n`);
986
+ * }
987
+ * };
988
+ *
989
+ * iModel.exportGraphics(({ onGraphics, elementIdArray: ["0x1"] }));
990
+ * ```
991
+ * @returns 0 if successful, status otherwise
992
+ * @public
993
+ */
994
+ exportGraphics(exportProps) {
995
+ return this.nativeDb.exportGraphics(exportProps);
996
+ }
997
+ /**
998
+ * Exports meshes suitable for graphics APIs from a specified [GeometryPart]($core-backend)
999
+ * in this IModelDb.
1000
+ * The expected use case is to call [IModelDb.exportGraphics]($core-backend) and supply the
1001
+ * optional partInstanceArray argument, then call this function for each unique GeometryPart from
1002
+ * that list.
1003
+ * * The results of changing [ExportPartGraphicsOptions]($core-backend) during the
1004
+ * [ExportPartGraphicsOptions.onPartGraphics]($core-backend) callback are not defined.
1005
+ * * See export-gltf under test-apps in the iTwin.js monorepo for a working reference.
1006
+ * @returns 0 is successful, status otherwise
1007
+ * @public
1008
+ */
1009
+ exportPartGraphics(exportProps) {
1010
+ return this.nativeDb.exportPartGraphics(exportProps);
1011
+ }
1012
+ /** Request geometry stream information from an element in binary format instead of json.
1013
+ * @returns IModelStatus.Success if successful
1014
+ * @alpha
1015
+ */
1016
+ elementGeometryRequest(requestProps) {
1017
+ return this.nativeDb.processGeometryStream(requestProps);
1018
+ }
1019
+ /** Create brep geometry for inclusion in an element's geometry stream.
1020
+ * @returns IModelStatus.Success if successful
1021
+ * @throws [[IModelError]] to report issues with input geometry or parameters
1022
+ * @alpha
1023
+ */
1024
+ createBRepGeometry(createProps) {
1025
+ return this.nativeDb.createBRepGeometry(createProps);
1026
+ }
1027
+ /** Generate graphics for an element or geometry stream.
1028
+ * @see [readElementGraphics]($frontend) to convert the result to a [RenderGraphic]($frontend) for display.
1029
+ */
1030
+ async generateElementGraphics(request) {
1031
+ return (0, ElementGraphics_1.generateElementGraphics)(request, this);
1032
+ }
1033
+ /** Save a `SettingDictionary` in this iModel that will be loaded into [[workspace.settings]] every time this iModel is opened in future sessions.
1034
+ * @param name The name for the SettingDictionary. If a dictionary by that name already exists in the iModel, its value is replaced.
1035
+ * @param dict The SettingDictionary object to stringify and save.
1036
+ * @note All saved `SettingDictionary`s are loaded into [[workspace.settings]] every time an iModel is opened.
1037
+ * @beta
1038
+ */
1039
+ saveSettingDictionary(name, dict) {
1040
+ this.withSqliteStatement("REPLACE INTO be_Prop(id,SubId,TxnMode,Namespace,Name,strData) VALUES(0,0,0,?,?,?)", (stmt) => {
1041
+ stmt.bindString(1, IModelDb._settingPropNamespace);
1042
+ stmt.bindString(2, name);
1043
+ stmt.bindString(3, JSON.stringify(dict));
1044
+ const rc = stmt.step();
1045
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
1046
+ throw new core_common_1.IModelError(rc, "cannot save setting");
1047
+ });
1048
+ this.saveChanges("add settings");
1049
+ }
1050
+ /** Delete a SettingDictionary, previously added with [[saveSettingDictionary]], from this iModel.
1051
+ * @param name The name of the dictionary to delete.
1052
+ * @beta
1053
+ */
1054
+ deleteSettingDictionary(name) {
1055
+ this.withSqliteStatement("DELETE FROM be_Prop WHERE Namespace=? AND Name=?", (stmt) => {
1056
+ stmt.bindString(1, IModelDb._settingPropNamespace);
1057
+ stmt.bindString(2, name);
1058
+ const rc = stmt.step();
1059
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
1060
+ throw new core_common_1.IModelError(rc, "cannot delete setting");
1061
+ });
1062
+ this.saveChanges("delete settings");
1063
+ }
1064
+ /** Load all setting dictionaries in this iModel into `this.workspace.settings` */
1065
+ loadSettingDictionaries() {
1066
+ if (!this.nativeDb.isOpen())
1067
+ return;
1068
+ this.withSqliteStatement("SELECT Name,StrData FROM be_Prop WHERE Namespace=?", (stmt) => {
1069
+ stmt.bindString(1, IModelDb._settingPropNamespace);
1070
+ while (stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW) {
1071
+ try {
1072
+ const dict = JSON.parse(stmt.getValueString(1));
1073
+ this.workspace.settings.addDictionary(stmt.getValueString(0), Settings_1.SettingsPriority.iModel, dict);
1074
+ }
1075
+ catch (e) {
1076
+ core_bentley_1.UnexpectedErrors.handle(e);
1077
+ }
1078
+ }
1079
+ });
1080
+ }
1081
+ }
1082
+ exports.IModelDb = IModelDb;
1083
+ /** Keep track of open imodels to support `tryFind` for RPC purposes */
1084
+ IModelDb._openDbs = new Map();
1085
+ IModelDb.defaultLimit = 1000; // default limit for batching queries
1086
+ IModelDb.maxLimit = 10000; // maximum limit for batching queries
1087
+ IModelDb._settingPropNamespace = "settings";
1088
+ /** @public */
1089
+ (function (IModelDb) {
1090
+ /** The collection of models in an [[IModelDb]].
1091
+ * @public
1092
+ */
1093
+ class Models {
1094
+ /** @internal */
1095
+ constructor(_iModel) {
1096
+ this._iModel = _iModel;
1097
+ }
1098
+ /** Get the ModelProps with the specified identifier.
1099
+ * @param modelId The Model identifier.
1100
+ * @throws [[IModelError]] if the model is not found or cannot be loaded.
1101
+ * @see tryGetModelProps
1102
+ */
1103
+ getModelProps(id) {
1104
+ return this.getModelJson({ id });
1105
+ }
1106
+ /** Get the ModelProps with the specified identifier.
1107
+ * @param modelId The Model identifier.
1108
+ * @returns The ModelProps or `undefined` if the model is not found.
1109
+ * @throws [[IModelError]] if the model cannot be loaded.
1110
+ * @note Useful for cases when a model may or may not exist and throwing an `Error` would be overkill.
1111
+ * @see getModelProps
1112
+ */
1113
+ tryGetModelProps(id) {
1114
+ return this.tryGetModelJson({ id });
1115
+ }
1116
+ /** Query for the last modified time of the specified Model.
1117
+ * @internal
1118
+ */
1119
+ queryLastModifiedTime(modelId) {
1120
+ const sql = `SELECT LastMod FROM ${Model_1.Model.classFullName} WHERE ECInstanceId=:modelId`;
1121
+ return this._iModel.withPreparedStatement(sql, (statement) => {
1122
+ statement.bindId("modelId", modelId);
1123
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1124
+ return statement.getValue(0).getDateTime();
1125
+ }
1126
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Can't get lastMod time for Model ${modelId}`);
1127
+ });
1128
+ }
1129
+ /** Get the Model with the specified identifier.
1130
+ * @param modelId The Model identifier.
1131
+ * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1132
+ * @throws [[IModelError]] if the model is not found, cannot be loaded, or fails validation when `modelClass` is specified.
1133
+ * @see tryGetModel
1134
+ */
1135
+ getModel(modelId, modelClass) {
1136
+ const model = this.tryGetModel(modelId, modelClass);
1137
+ if (undefined === model) {
1138
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Model=${modelId}`);
1139
+ }
1140
+ return model;
1141
+ }
1142
+ /** Get the Model with the specified identifier.
1143
+ * @param modelId The Model identifier.
1144
+ * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1145
+ * @returns The Model or `undefined` if the model is not found or fails validation when `modelClass` is specified.
1146
+ * @throws [[IModelError]] if the model cannot be loaded.
1147
+ * @note Useful for cases when a model may or may not exist and throwing an `Error` would be overkill.
1148
+ * @see getModel
1149
+ */
1150
+ tryGetModel(modelId, modelClass) {
1151
+ const modelProps = this.tryGetModelProps(modelId);
1152
+ if (undefined === modelProps)
1153
+ return undefined; // no Model with that modelId found
1154
+ const model = this._iModel.constructEntity(modelProps);
1155
+ if (undefined === modelClass)
1156
+ return model; // modelClass was not specified, cannot call instanceof to validate
1157
+ return model instanceof modelClass ? model : undefined;
1158
+ }
1159
+ /** Read the properties for a Model as a json string.
1160
+ * @param modelIdArg a json string with the identity of the model to load. Must have either "id" or "code".
1161
+ * @returns a json string with the properties of the model.
1162
+ * @throws [[IModelError]] if the model is not found or cannot be loaded.
1163
+ * @see tryGetModelJson
1164
+ * @internal
1165
+ */
1166
+ getModelJson(modelIdArg) {
1167
+ const modelJson = this.tryGetModelJson(modelIdArg);
1168
+ if (undefined === modelJson) {
1169
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Model=${modelIdArg}`);
1170
+ }
1171
+ return modelJson;
1172
+ }
1173
+ /** Read the properties for a Model as a json string.
1174
+ * @param modelIdArg a json string with the identity of the model to load. Must have either "id" or "code".
1175
+ * @returns a json string with the properties of the model or `undefined` if the model is not found.
1176
+ * @see getModelJson
1177
+ */
1178
+ tryGetModelJson(modelIdArg) {
1179
+ try {
1180
+ return this._iModel.nativeDb.getModel(modelIdArg);
1181
+ }
1182
+ catch (err) {
1183
+ return undefined;
1184
+ }
1185
+ }
1186
+ /** Get the sub-model of the specified Element.
1187
+ * See [[IModelDb.Elements.queryElementIdByCode]] for more on how to find an element by Code.
1188
+ * @param modeledElementId Identifies the modeled element.
1189
+ * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1190
+ * @throws [[IModelError]] if the sub-model is not found, cannot be loaded, or fails validation when `modelClass` is specified.
1191
+ * @see tryGetSubModel
1192
+ */
1193
+ getSubModel(modeledElementId, modelClass) {
1194
+ const modeledElementProps = this._iModel.elements.getElementProps(modeledElementId);
1195
+ if (undefined === modeledElementProps.id || modeledElementProps.id === core_common_1.IModel.rootSubjectId)
1196
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "Root subject does not have a sub-model");
1197
+ return this.getModel(modeledElementProps.id, modelClass);
1198
+ }
1199
+ /** Get the sub-model of the specified Element.
1200
+ * See [[IModelDb.Elements.queryElementIdByCode]] for more on how to find an element by Code.
1201
+ * @param modeledElementId Identifies the modeled element.
1202
+ * @param modelClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1203
+ * @returns The sub-model or `undefined` if the specified element does not have a sub-model or fails validation when `modelClass` is specified.
1204
+ * @see getSubModel
1205
+ */
1206
+ tryGetSubModel(modeledElementId, modelClass) {
1207
+ const modeledElementProps = this._iModel.elements.tryGetElementProps(modeledElementId);
1208
+ if (undefined === modeledElementProps?.id || (core_common_1.IModel.rootSubjectId === modeledElementProps.id))
1209
+ return undefined;
1210
+ return this.tryGetModel(modeledElementProps.id, modelClass);
1211
+ }
1212
+ /** Create a new model in memory.
1213
+ * See the example in [[InformationPartitionElement]].
1214
+ * @param modelProps The properties to use when creating the model.
1215
+ * @throws [[IModelError]] if there is a problem creating the model.
1216
+ */
1217
+ createModel(modelProps) { return this._iModel.constructEntity(modelProps); }
1218
+ /** Insert a new model.
1219
+ * @param props The data for the new model.
1220
+ * @returns The newly inserted model's Id.
1221
+ * @throws [[IModelError]] if unable to insert the model.
1222
+ */
1223
+ insertModel(props) {
1224
+ try {
1225
+ return props.id = this._iModel.nativeDb.insertModel(props);
1226
+ }
1227
+ catch (err) {
1228
+ throw new core_common_1.IModelError(err.errorNumber, `Error inserting model [${err.message}], class=${props.classFullName}`);
1229
+ }
1230
+ }
1231
+ /** Update an existing model.
1232
+ * @param props the properties of the model to change
1233
+ * @throws [[IModelError]] if unable to update the model.
1234
+ */
1235
+ updateModel(props) {
1236
+ try {
1237
+ this._iModel.nativeDb.updateModel(props);
1238
+ }
1239
+ catch (err) {
1240
+ throw new core_common_1.IModelError(err.errorNumber, `error updating model [${err.message}] id=${props.id}`);
1241
+ }
1242
+ }
1243
+ /** Mark the geometry of [[GeometricModel]] as having changed, by recording an indirect change to its GeometryGuid property.
1244
+ * Typically the GeometryGuid changes automatically when [[GeometricElement]]s within the model are modified, but
1245
+ * explicitly updating it is occasionally useful after modifying definition elements like line styles or materials that indirectly affect the appearance of
1246
+ * [[GeometricElement]]s that reference those definition elements in their geometry streams.
1247
+ * Cached [Tile]($frontend)s are only invalidated after the geometry guid of the model changes.
1248
+ * @note This will throw IModelError with [IModelStatus.VersionTooOld]($core-bentley) if a version of the BisCore schema older than 1.0.11 is present in the iModel.
1249
+ * @throws IModelError if unable to update the geometry guid.
1250
+ * @see [[TxnManager.onModelGeometryChanged]] for the event emitted in response to such a change.
1251
+ */
1252
+ updateGeometryGuid(modelId) {
1253
+ const error = this._iModel.nativeDb.updateModelGeometryGuid(modelId);
1254
+ if (error !== core_bentley_1.IModelStatus.Success)
1255
+ throw new core_common_1.IModelError(error, `updating geometry guid for model ${modelId}`);
1256
+ }
1257
+ /** Delete one or more existing models.
1258
+ * @param ids The Ids of the models to be deleted
1259
+ * @throws [[IModelError]]
1260
+ */
1261
+ deleteModel(ids) {
1262
+ core_bentley_1.Id64.toIdSet(ids).forEach((id) => {
1263
+ try {
1264
+ this._iModel.nativeDb.deleteModel(id);
1265
+ }
1266
+ catch (err) {
1267
+ throw new core_common_1.IModelError(err.errorNumber, `error deleting model [${err.message}] id ${id}`);
1268
+ }
1269
+ });
1270
+ }
1271
+ /** For each specified [[GeometricModel]], attempts to obtain the union of the volumes of all geometric elements within that model.
1272
+ * @param ids The Id or Ids of the [[GeometricModel]]s for which to obtain the extents.
1273
+ * @returns An array of results, one per supplied Id, in the order in which the Ids were supplied. If the extents could not be obtained, the
1274
+ * corresponding results entry's `extents` will be a "null" range (@see [Range3d.isNull]($geometry)) and its `status` will indicate
1275
+ * why the extents could not be obtained (e.g., because the Id did not identify a [[GeometricModel]]).
1276
+ * @see [[queryRange]] to obtain the union of all of the models' extents.
1277
+ */
1278
+ async queryExtents(ids) {
1279
+ ids = typeof ids === "string" ? [ids] : ids;
1280
+ if (ids.length === 0)
1281
+ return [];
1282
+ return this._iModel.nativeDb.queryModelExtentsAsync(ids);
1283
+ }
1284
+ /** Computes the union of the volumes of all geoemtric elements within any number of [[GeometricModel]]s, specified by model Id.
1285
+ * @see [[queryExtents]] to obtain discrete volumes for each model.
1286
+ */
1287
+ async queryRange(ids) {
1288
+ const results = await this.queryExtents(ids);
1289
+ const range = new core_geometry_1.Range3d();
1290
+ for (const result of results)
1291
+ range.union(core_geometry_1.Range3d.fromJSON(result.extents), range);
1292
+ return range;
1293
+ }
1294
+ }
1295
+ IModelDb.Models = Models;
1296
+ /** The collection of elements in an [[IModelDb]].
1297
+ * @public
1298
+ */
1299
+ class Elements {
1300
+ /** @internal */
1301
+ constructor(_iModel) {
1302
+ this._iModel = _iModel;
1303
+ }
1304
+ /** Read element data from the iModel as JSON
1305
+ * @param elementIdArg a json string with the identity of the element to load. Must have one of "id", "federationGuid", or "code".
1306
+ * @returns The JSON properties of the element.
1307
+ * @throws [[IModelError]] if the element is not found or cannot be loaded.
1308
+ * @see tryGetElementJson
1309
+ * @internal
1310
+ */
1311
+ getElementJson(elementId) {
1312
+ const elementProps = this.tryGetElementJson(elementId);
1313
+ if (undefined === elementProps)
1314
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `reading element=${elementId}`);
1315
+ return elementProps;
1316
+ }
1317
+ /** Read element data from the iModel as JSON
1318
+ * @param loadProps - a json string with the identity of the element to load. Must have one of "id", "federationGuid", or "code".
1319
+ * @returns The JSON properties of the element or `undefined` if the element is not found.
1320
+ * @throws [[IModelError]] if the element exists, but cannot be loaded.
1321
+ * @see getElementJson
1322
+ */
1323
+ tryGetElementJson(loadProps) {
1324
+ try {
1325
+ return this._iModel.nativeDb.getElement(loadProps);
1326
+ }
1327
+ catch (err) {
1328
+ return undefined;
1329
+ }
1330
+ }
1331
+ /** Get properties of an Element by Id, FederationGuid, or Code
1332
+ * @throws [[IModelError]] if the element is not found or cannot be loaded.
1333
+ * @see tryGetElementProps
1334
+ */
1335
+ getElementProps(props) {
1336
+ if (typeof props === "string") {
1337
+ props = core_bentley_1.Id64.isId64(props) ? { id: props } : { federationGuid: props };
1338
+ }
1339
+ else if (props instanceof core_common_1.Code) {
1340
+ props = { code: props };
1341
+ }
1342
+ try {
1343
+ return this._iModel.nativeDb.getElement(props);
1344
+ }
1345
+ catch (err) {
1346
+ throw new core_common_1.IModelError(err.errorNumber, err.message);
1347
+ }
1348
+ }
1349
+ /** Get properties of an Element by Id, FederationGuid, or Code
1350
+ * @returns The properties of the element or `undefined` if the element is not found.
1351
+ * @throws [[IModelError]] if the element exists, but cannot be loaded.
1352
+ * @note Useful for cases when an element may or may not exist and throwing an `Error` would be overkill.
1353
+ * @see getElementProps
1354
+ */
1355
+ tryGetElementProps(elementId) {
1356
+ if (typeof elementId === "string") {
1357
+ elementId = core_bentley_1.Id64.isId64(elementId) ? { id: elementId } : { federationGuid: elementId };
1358
+ }
1359
+ else if (elementId instanceof core_common_1.Code) {
1360
+ elementId = { code: elementId };
1361
+ }
1362
+ return this.tryGetElementJson(elementId);
1363
+ }
1364
+ /** Get an element by Id, FederationGuid, or Code
1365
+ * @param elementId either the element's Id, Code, or FederationGuid, or an ElementLoadProps
1366
+ * @param elementClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1367
+ * @throws [[IModelError]] if the element is not found, cannot be loaded, or fails validation when `elementClass` is specified.
1368
+ * @see tryGetElement
1369
+ */
1370
+ getElement(elementId, elementClass) {
1371
+ const element = this.tryGetElement(elementId, elementClass);
1372
+ if (undefined === element)
1373
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Element=${elementId}`);
1374
+ return element;
1375
+ }
1376
+ /** Get an element by Id, FederationGuid, or Code
1377
+ * @param elementId either the element's Id, Code, or FederationGuid, or an ElementLoadProps
1378
+ * @param elementClass Optional class to validate instance against. This parameter can accept abstract or concrete classes, but should be the same as the template (`T`) parameter.
1379
+ * @returns The element or `undefined` if the element is not found or fails validation when `elementClass` is specified.
1380
+ * @throws [[IModelError]] if the element exists, but cannot be loaded.
1381
+ * @note Useful for cases when an element may or may not exist and throwing an `Error` would be overkill.
1382
+ * @see getElement
1383
+ */
1384
+ tryGetElement(elementId, elementClass) {
1385
+ if (typeof elementId === "string")
1386
+ elementId = core_bentley_1.Id64.isId64(elementId) ? { id: elementId } : { federationGuid: elementId };
1387
+ else if (elementId instanceof core_common_1.Code)
1388
+ elementId = { code: elementId };
1389
+ else
1390
+ elementId.onlyBaseProperties = false; // we must load all properties to construct the element.
1391
+ const elementProps = this.tryGetElementJson(elementId);
1392
+ if (undefined === elementProps)
1393
+ return undefined; // no Element with that elementId found
1394
+ const element = this._iModel.constructEntity(elementProps);
1395
+ if (undefined === elementClass)
1396
+ return element; // elementClass was not specified, cannot call instanceof to validate
1397
+ return element instanceof elementClass ? element : undefined;
1398
+ }
1399
+ /** Query for the Id of the element that has a specified code.
1400
+ * This method is for the case where you know the element's Code.
1401
+ * If you only know the code *value*, then in the simplest case, you can query on that
1402
+ * and filter the results.
1403
+ * In the simple case, call [[IModelDb.queryEntityIds]], specifying the code value in the where clause of the query params.
1404
+ * Or, you can execute an ECSQL select statement. See
1405
+ * [frequently used ECSQL queries]($docs/learning/backend/ECSQL-queries.md) for an example.
1406
+ * @param code The code to look for
1407
+ * @returns The element that uses the code or undefined if the code is not used.
1408
+ * @throws IModelError if the code is invalid
1409
+ */
1410
+ queryElementIdByCode(code) {
1411
+ if (core_bentley_1.Id64.isInvalid(code.spec))
1412
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidCodeSpec, "Invalid CodeSpec");
1413
+ if (code.value === undefined)
1414
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidCode, "Invalid Code");
1415
+ return this._iModel.withPreparedStatement("SELECT ECInstanceId FROM BisCore:Element WHERE CodeSpec.Id=? AND CodeScope.Id=? AND CodeValue=?", (stmt) => {
1416
+ stmt.bindId(1, code.spec);
1417
+ stmt.bindId(2, core_bentley_1.Id64.fromString(code.scope));
1418
+ stmt.bindString(3, code.value);
1419
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== stmt.step())
1420
+ return undefined;
1421
+ return stmt.getValue(0).getId();
1422
+ });
1423
+ }
1424
+ /** Query for the last modified time of the specified element.
1425
+ * @internal
1426
+ */
1427
+ queryLastModifiedTime(elementId) {
1428
+ const sql = "SELECT LastMod FROM BisCore:Element WHERE ECInstanceId=:elementId";
1429
+ return this._iModel.withPreparedStatement(sql, (statement) => {
1430
+ statement.bindId("elementId", elementId);
1431
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step())
1432
+ return statement.getValue(0).getDateTime();
1433
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Can't get lastMod time for Element ${elementId}`);
1434
+ });
1435
+ }
1436
+ /** Create a new instance of an element.
1437
+ * @param elProps The properties of the new element.
1438
+ * @throws [[IModelError]] if there is a problem creating the element.
1439
+ */
1440
+ createElement(elProps) { return this._iModel.constructEntity(elProps); }
1441
+ /** Insert a new element into the iModel.
1442
+ * @param elProps The properties of the new element.
1443
+ * @returns The newly inserted element's Id.
1444
+ * @throws [[IModelError]] if unable to insert the element.
1445
+ * @note For convenience, the value of `elProps.id` is updated to reflect the resultant element's id.
1446
+ * However when `elProps.federationGuid` is not present or undefined, a new Guid will be generated and stored on the resultant element. But
1447
+ * the value of `elProps.federationGuid` is *not* updated. Generally, it is best to re-read the element after inserting (e.g. via [[getElementProps]])
1448
+ * if you intend to continue working with it. That will ensure its values reflect the persistent state.
1449
+ */
1450
+ insertElement(elProps) {
1451
+ try {
1452
+ return elProps.id = this._iModel.nativeDb.insertElement(elProps);
1453
+ }
1454
+ catch (err) {
1455
+ err.message = `error inserting element: ${err.message}`;
1456
+ throw err;
1457
+ }
1458
+ }
1459
+ /** Update some properties of an existing element.
1460
+ * To support clearing a property value, every property name that is present in the `elProps` object will be updated even if the value is `undefined`.
1461
+ * To keep an individual element property unchanged, it should either be excluded from the `elProps` parameter or set to its current value.
1462
+ * @param elProps the properties of the element to update.
1463
+ * @note As described above, this is a special case where there is a difference between a property being excluded and a property being present in `elProps` but set to `undefined`.
1464
+ * @throws [[IModelError]] if unable to update the element.
1465
+ */
1466
+ updateElement(elProps) {
1467
+ try {
1468
+ this._iModel.nativeDb.updateElement(elProps);
1469
+ }
1470
+ catch (err) {
1471
+ err.message = `error updating element: ${err.message}`;
1472
+ throw err;
1473
+ }
1474
+ }
1475
+ /** Delete one or more elements from this iModel.
1476
+ * @param ids The set of Ids of the element(s) to be deleted
1477
+ * @throws [[IModelError]]
1478
+ * @see deleteDefinitionElements
1479
+ */
1480
+ deleteElement(ids) {
1481
+ const iModel = this._iModel;
1482
+ core_bentley_1.Id64.toIdSet(ids).forEach((id) => {
1483
+ try {
1484
+ iModel.nativeDb.deleteElement(id);
1485
+ }
1486
+ catch (err) {
1487
+ err.message = `error deleting element: ${err.message}`;
1488
+ throw err;
1489
+ }
1490
+ });
1491
+ }
1492
+ /** DefinitionElements can only be deleted if it can be determined that they are not referenced by other Elements.
1493
+ * This *usage query* can be expensive since it may involve scanning the GeometryStreams of all GeometricElements.
1494
+ * Since [[deleteElement]] does not perform these additional checks, it fails in order to prevent potentially referenced DefinitionElements from being deleted.
1495
+ * This method performs those expensive checks and then calls *delete* if not referenced.
1496
+ * @param ids The Ids of the DefinitionElements to attempt to delete. To prevent multiple passes over the same GeometricElements, it is best to pass in the entire array of
1497
+ * DefinitionElements rather than calling this method separately for each one. Ids that are not valid DefinitionElements will be ignored.
1498
+ * @returns An IdSet of the DefinitionElements that are used and were therefore not deleted.
1499
+ * @see deleteElement
1500
+ * @beta
1501
+ */
1502
+ deleteDefinitionElements(definitionElementIds) {
1503
+ const usageInfo = this._iModel.nativeDb.queryDefinitionElementUsage(definitionElementIds);
1504
+ if (!usageInfo) {
1505
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, "Error querying for DefinitionElement usage");
1506
+ }
1507
+ const usedIdSet = usageInfo.usedIds ? core_bentley_1.Id64.toIdSet(usageInfo.usedIds) : new Set();
1508
+ const deleteIfUnused = (ids, used) => {
1509
+ if (ids) {
1510
+ ids.forEach((id) => {
1511
+ if (!used.has(id))
1512
+ this._iModel.elements.deleteElement(id);
1513
+ });
1514
+ }
1515
+ };
1516
+ try {
1517
+ this._iModel.nativeDb.beginPurgeOperation();
1518
+ deleteIfUnused(usageInfo.spatialCategoryIds, usedIdSet);
1519
+ deleteIfUnused(usageInfo.drawingCategoryIds, usedIdSet);
1520
+ deleteIfUnused(usageInfo.viewDefinitionIds, usedIdSet);
1521
+ deleteIfUnused(usageInfo.geometryPartIds, usedIdSet);
1522
+ deleteIfUnused(usageInfo.lineStyleIds, usedIdSet);
1523
+ deleteIfUnused(usageInfo.renderMaterialIds, usedIdSet);
1524
+ deleteIfUnused(usageInfo.subCategoryIds, usedIdSet);
1525
+ deleteIfUnused(usageInfo.textureIds, usedIdSet);
1526
+ deleteIfUnused(usageInfo.displayStyleIds, usedIdSet);
1527
+ deleteIfUnused(usageInfo.categorySelectorIds, usedIdSet);
1528
+ deleteIfUnused(usageInfo.modelSelectorIds, usedIdSet);
1529
+ if (usageInfo.otherDefinitionElementIds) {
1530
+ this._iModel.elements.deleteElement(usageInfo.otherDefinitionElementIds);
1531
+ }
1532
+ }
1533
+ finally {
1534
+ this._iModel.nativeDb.endPurgeOperation();
1535
+ }
1536
+ if (usageInfo.viewDefinitionIds) {
1537
+ // take another pass in case a deleted ViewDefinition was the only usage of these view-related DefinitionElements
1538
+ let viewRelatedIds = [];
1539
+ if (usageInfo.displayStyleIds)
1540
+ viewRelatedIds = viewRelatedIds.concat(usageInfo.displayStyleIds.filter((id) => usedIdSet.has(id)));
1541
+ if (usageInfo.categorySelectorIds)
1542
+ viewRelatedIds = viewRelatedIds.concat(usageInfo.categorySelectorIds.filter((id) => usedIdSet.has(id)));
1543
+ if (usageInfo.modelSelectorIds)
1544
+ viewRelatedIds = viewRelatedIds.concat(usageInfo.modelSelectorIds.filter((id) => usedIdSet.has(id)));
1545
+ if (viewRelatedIds.length > 0) {
1546
+ const viewRelatedUsageInfo = this._iModel.nativeDb.queryDefinitionElementUsage(viewRelatedIds);
1547
+ if (viewRelatedUsageInfo) {
1548
+ const usedViewRelatedIdSet = viewRelatedUsageInfo.usedIds ? core_bentley_1.Id64.toIdSet(viewRelatedUsageInfo.usedIds) : new Set();
1549
+ try {
1550
+ this._iModel.nativeDb.beginPurgeOperation();
1551
+ deleteIfUnused(viewRelatedUsageInfo.displayStyleIds, usedViewRelatedIdSet);
1552
+ deleteIfUnused(viewRelatedUsageInfo.categorySelectorIds, usedViewRelatedIdSet);
1553
+ deleteIfUnused(viewRelatedUsageInfo.modelSelectorIds, usedViewRelatedIdSet);
1554
+ }
1555
+ finally {
1556
+ this._iModel.nativeDb.endPurgeOperation();
1557
+ }
1558
+ viewRelatedIds.forEach((id) => {
1559
+ if (!usedViewRelatedIdSet.has(id))
1560
+ usedIdSet.delete(id);
1561
+ });
1562
+ }
1563
+ }
1564
+ }
1565
+ return usedIdSet;
1566
+ }
1567
+ /** Query for the child elements of the specified element.
1568
+ * @returns Returns an array of child element identifiers.
1569
+ * @throws [[IModelError]]
1570
+ */
1571
+ queryChildren(elementId) {
1572
+ const sql = "SELECT ECInstanceId FROM BisCore:Element WHERE Parent.Id=:elementId";
1573
+ return this._iModel.withPreparedStatement(sql, (statement) => {
1574
+ statement.bindId("elementId", elementId);
1575
+ const childIds = [];
1576
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1577
+ childIds.push(statement.getValue(0).getId());
1578
+ }
1579
+ return childIds;
1580
+ });
1581
+ }
1582
+ /** Query for the parent of the specified element.
1583
+ * @param elementId The element to check for a parent
1584
+ * @returns The identifier of the element's parent or undefined if the element has no parent
1585
+ * @throws [[IModelError]] if the element does not exist
1586
+ */
1587
+ queryParent(elementId) {
1588
+ return this._iModel.withPreparedStatement(`select parent.id from ${Element_1.Element.classFullName} where ecinstanceid=?`, (stmt) => {
1589
+ stmt.bindId(1, elementId);
1590
+ if (stmt.step() !== core_bentley_1.DbResult.BE_SQLITE_ROW)
1591
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Element=${elementId}`);
1592
+ const value = stmt.getValue(0);
1593
+ return value.isNull ? undefined : value.getId();
1594
+ });
1595
+ }
1596
+ /** Returns true if the specified Element has a sub-model.
1597
+ * @see [[IModelDb.Models.getSubModel]]
1598
+ */
1599
+ hasSubModel(elementId) {
1600
+ if (core_common_1.IModel.rootSubjectId === elementId)
1601
+ return false; // Special case since the RepositoryModel does not sub-model the root Subject
1602
+ // A sub-model will have the same Id value as the element it is describing
1603
+ const sql = "SELECT ECInstanceId FROM BisCore:Model WHERE ECInstanceId=:elementId";
1604
+ return this._iModel.withPreparedStatement(sql, (statement) => {
1605
+ statement.bindId("elementId", elementId);
1606
+ return core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step();
1607
+ });
1608
+ }
1609
+ /** Get the root subject element. */
1610
+ getRootSubject() { return this.getElement(core_common_1.IModel.rootSubjectId); }
1611
+ /** Query for aspects of a particular class (polymorphically) associated with this element.
1612
+ * @throws [[IModelError]]
1613
+ * @note Most cases should use the [[getAspects]] wrapper rather than calling this method directly.
1614
+ * @internal
1615
+ */
1616
+ _queryAspects(elementId, fromClassFullName, excludedClassFullNames) {
1617
+ const sql = `SELECT ECInstanceId,ECClassId FROM ${fromClassFullName} WHERE Element.Id=:elementId ORDER BY ECClassId,ECInstanceId`; // ORDER BY to maximize statement reuse
1618
+ return this._iModel.withPreparedStatement(sql, (statement) => {
1619
+ statement.bindId("elementId", elementId);
1620
+ const aspects = [];
1621
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1622
+ const aspectInstanceId = statement.getValue(0).getId();
1623
+ const aspectClassFullName = statement.getValue(1).getClassNameForClassId().replace(".", ":");
1624
+ if ((undefined === excludedClassFullNames) || (!excludedClassFullNames.has(aspectClassFullName))) {
1625
+ aspects.push(this._queryAspect(aspectInstanceId, aspectClassFullName));
1626
+ }
1627
+ }
1628
+ return aspects;
1629
+ });
1630
+ }
1631
+ /** Query for aspect by ECInstanceId
1632
+ * @throws [[IModelError]]
1633
+ */
1634
+ _queryAspect(aspectInstanceId, aspectClassName) {
1635
+ const sql = `SELECT * FROM ${aspectClassName} WHERE ECInstanceId=:aspectInstanceId`;
1636
+ const aspect = this._iModel.withPreparedStatement(sql, (statement) => {
1637
+ statement.bindId("aspectInstanceId", aspectInstanceId);
1638
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) {
1639
+ const aspectProps = statement.getRow(); // start with everything that SELECT * returned
1640
+ aspectProps.classFullName = aspectProps.className.replace(".", ":"); // add in property required by EntityProps
1641
+ aspectProps.className = undefined; // clear property from SELECT * that we don't want in the final instance
1642
+ return aspectProps;
1643
+ }
1644
+ return undefined;
1645
+ });
1646
+ if (undefined === aspect) {
1647
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `ElementAspect not found ${aspectInstanceId}, ${aspectClassName}`);
1648
+ }
1649
+ return this._iModel.constructEntity(aspect);
1650
+ }
1651
+ /** Get a single ElementAspect by its instance Id.
1652
+ * @throws [[IModelError]]
1653
+ */
1654
+ getAspect(aspectInstanceId) {
1655
+ const sql = "SELECT ECClassId FROM BisCore:ElementAspect WHERE ECInstanceId=:aspectInstanceId";
1656
+ const aspectClassFullName = this._iModel.withPreparedStatement(sql, (statement) => {
1657
+ statement.bindId("aspectInstanceId", aspectInstanceId);
1658
+ return (core_bentley_1.DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getClassNameForClassId().replace(".", ":") : undefined;
1659
+ });
1660
+ if (undefined === aspectClassFullName) {
1661
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `ElementAspect not found ${aspectInstanceId}`);
1662
+ }
1663
+ return this._queryAspect(aspectInstanceId, aspectClassFullName);
1664
+ }
1665
+ /** Get the ElementAspect instances that are owned by the specified element.
1666
+ * @param elementId Get ElementAspects associated with this Element
1667
+ * @param aspectClassFullName Optionally filter ElementAspects polymorphically by this class name
1668
+ * @throws [[IModelError]]
1669
+ */
1670
+ getAspects(elementId, aspectClassFullName) {
1671
+ if (undefined === aspectClassFullName) {
1672
+ const uniqueAspects = this._queryAspects(elementId, ElementAspect_1.ElementUniqueAspect.classFullName);
1673
+ const multiAspects = this._queryAspects(elementId, ElementAspect_1.ElementMultiAspect.classFullName);
1674
+ return uniqueAspects.concat(multiAspects);
1675
+ }
1676
+ const aspects = this._queryAspects(elementId, aspectClassFullName);
1677
+ return aspects;
1678
+ }
1679
+ /** Insert a new ElementAspect into the iModel.
1680
+ * @param aspectProps The properties of the new ElementAspect.
1681
+ * @throws [[IModelError]] if unable to insert the ElementAspect.
1682
+ * @returns the id of the newly inserted aspect.
1683
+ * @note Aspect Ids may collide with element Ids, so don't put both in a container like Set or Map
1684
+ * use [EntityReference]($common) for that instead.
1685
+ */
1686
+ insertAspect(aspectProps) {
1687
+ try {
1688
+ return this._iModel.nativeDb.insertElementAspect(aspectProps);
1689
+ }
1690
+ catch (err) {
1691
+ throw new core_common_1.IModelError(err.errorNumber, `Error inserting ElementAspect [${err.message}], class: ${aspectProps.classFullName}`);
1692
+ }
1693
+ }
1694
+ /** Update an exist ElementAspect within the iModel.
1695
+ * @param aspectProps The properties to use to update the ElementAspect.
1696
+ * @throws [[IModelError]] if unable to update the ElementAspect.
1697
+ */
1698
+ updateAspect(aspectProps) {
1699
+ try {
1700
+ this._iModel.nativeDb.updateElementAspect(aspectProps);
1701
+ }
1702
+ catch (err) {
1703
+ throw new core_common_1.IModelError(err.errorNumber, `Error updating ElementAspect [${err.message}], id: ${aspectProps.id}`);
1704
+ }
1705
+ }
1706
+ /** Delete one or more ElementAspects from this iModel.
1707
+ * @param aspectInstanceIds The set of instance Ids of the ElementAspect(s) to be deleted
1708
+ * @throws [[IModelError]] if unable to delete the ElementAspect.
1709
+ */
1710
+ deleteAspect(aspectInstanceIds) {
1711
+ const iModel = this._iModel;
1712
+ core_bentley_1.Id64.toIdSet(aspectInstanceIds).forEach((aspectInstanceId) => {
1713
+ try {
1714
+ iModel.nativeDb.deleteElementAspect(aspectInstanceId);
1715
+ }
1716
+ catch (err) {
1717
+ throw new core_common_1.IModelError(err.errorNumber, `Error deleting ElementAspect [${err.message}], id: ${aspectInstanceId}`);
1718
+ }
1719
+ });
1720
+ }
1721
+ }
1722
+ IModelDb.Elements = Elements;
1723
+ /** The collection of views in an [[IModelDb]].
1724
+ * @public
1725
+ */
1726
+ class Views {
1727
+ /** @internal */
1728
+ constructor(_iModel) {
1729
+ this._iModel = _iModel;
1730
+ }
1731
+ /** Query for the array of ViewDefinitionProps of the specified class and matching the specified IsPrivate setting.
1732
+ * @param className Query for view definitions of this class.
1733
+ * @param wantPrivate If true, include private view definitions.
1734
+ */
1735
+ queryViewDefinitionProps(className = "BisCore.ViewDefinition", limit = IModelDb.defaultLimit, offset = 0, wantPrivate = false) {
1736
+ const where = (wantPrivate === false) ? "IsPrivate=FALSE" : "";
1737
+ const ids = this._iModel.queryEntityIds({ from: className, limit, offset, where });
1738
+ const props = [];
1739
+ const imodel = this._iModel;
1740
+ ids.forEach((id) => {
1741
+ try {
1742
+ props.push(imodel.elements.getElementProps(id));
1743
+ }
1744
+ catch (err) { }
1745
+ });
1746
+ return props;
1747
+ }
1748
+ /** Iterate all ViewDefinitions matching the supplied query.
1749
+ * @param params Specifies the query by which views are selected.
1750
+ * @param callback Function invoked for each ViewDefinition matching the query. Return false to terminate iteration, true to continue.
1751
+ * @returns true if all views were iterated, false if iteration was terminated early due to callback returning false.
1752
+ *
1753
+ * **Example: Finding all views of a specific DrawingModel**
1754
+ * ``` ts
1755
+ * [[include:IModelDb.Views.iterateViews]]
1756
+ * ```
1757
+ */
1758
+ iterateViews(params, callback) {
1759
+ const ids = this._iModel.queryEntityIds(params);
1760
+ let finished = true;
1761
+ for (const id of ids) {
1762
+ try {
1763
+ const view = this._iModel.elements.getElement(id);
1764
+ if (undefined !== view && view instanceof ViewDefinition_1.ViewDefinition) {
1765
+ finished = callback(view);
1766
+ if (!finished)
1767
+ break;
1768
+ }
1769
+ }
1770
+ catch (err) { }
1771
+ }
1772
+ return finished;
1773
+ }
1774
+ loadViewStateProps(viewDefinitionElement, options, drawingExtents) {
1775
+ const elements = this._iModel.elements;
1776
+ const viewDefinitionProps = viewDefinitionElement.toJSON();
1777
+ const categorySelectorProps = elements.getElementProps(viewDefinitionProps.categorySelectorId);
1778
+ const displayStyleProps = elements.getElementProps({
1779
+ id: viewDefinitionProps.displayStyleId,
1780
+ displayStyle: options?.displayStyle,
1781
+ });
1782
+ const viewStateData = {
1783
+ viewDefinitionProps,
1784
+ displayStyleProps,
1785
+ categorySelectorProps,
1786
+ };
1787
+ const modelSelectorId = viewDefinitionProps.modelSelectorId;
1788
+ if (modelSelectorId !== undefined) {
1789
+ viewStateData.modelSelectorProps = elements.getElementProps(modelSelectorId);
1790
+ }
1791
+ else if (viewDefinitionElement instanceof ViewDefinition_1.SheetViewDefinition) {
1792
+ viewStateData.sheetProps = elements.getElementProps(viewDefinitionElement.baseModelId);
1793
+ viewStateData.sheetAttachments = Array.from(this._iModel.queryEntityIds({
1794
+ from: "BisCore.ViewAttachment",
1795
+ where: `Model.Id=${viewDefinitionElement.baseModelId}`,
1796
+ }));
1797
+ }
1798
+ else if (viewDefinitionElement instanceof ViewDefinition_1.DrawingViewDefinition) {
1799
+ // Ensure view has known extents
1800
+ if (drawingExtents && !drawingExtents.isNull)
1801
+ viewStateData.modelExtents = drawingExtents.toJSON();
1802
+ // Include information about the associated [[SectionDrawing]], if any.
1803
+ // NB: The SectionDrawing ECClass may not exist in the iModel's version of the BisCore ECSchema.
1804
+ try {
1805
+ const sectionDrawing = this._iModel.elements.tryGetElement(viewDefinitionElement.baseModelId);
1806
+ if (sectionDrawing && sectionDrawing.spatialView && core_bentley_1.Id64.isValidId64(sectionDrawing.spatialView.id)) {
1807
+ viewStateData.sectionDrawing = {
1808
+ spatialView: sectionDrawing.spatialView.id,
1809
+ displaySpatialView: true === sectionDrawing.jsonProperties.displaySpatialView,
1810
+ drawingToSpatialTransform: sectionDrawing.jsonProperties.drawingToSpatialTransform,
1811
+ };
1812
+ }
1813
+ }
1814
+ catch {
1815
+ //
1816
+ }
1817
+ }
1818
+ return viewStateData;
1819
+ }
1820
+ /** @deprecated in 3.x. use [[getViewStateProps]]. */
1821
+ getViewStateData(viewDefinitionId, options) {
1822
+ const view = this._iModel.elements.getElement(viewDefinitionId);
1823
+ let drawingExtents;
1824
+ if (view instanceof ViewDefinition_1.DrawingViewDefinition) {
1825
+ try {
1826
+ drawingExtents = core_geometry_1.Range3d.fromJSON(this._iModel.nativeDb.queryModelExtents({ id: view.baseModelId }).modelExtents);
1827
+ }
1828
+ catch {
1829
+ //
1830
+ }
1831
+ }
1832
+ return this.loadViewStateProps(view, options, drawingExtents);
1833
+ }
1834
+ /** Obtain a [ViewStateProps]($common) for a [[ViewDefinition]] specified by element Id. */
1835
+ async getViewStateProps(viewDefinitionId, options) {
1836
+ const view = this._iModel.elements.getElement(viewDefinitionId);
1837
+ let drawingExtents;
1838
+ if (view instanceof ViewDefinition_1.DrawingViewDefinition)
1839
+ drawingExtents = (await this._iModel.models.queryRange(view.baseModelId));
1840
+ return this.loadViewStateProps(view, options, drawingExtents);
1841
+ }
1842
+ getViewThumbnailArg(viewDefinitionId) {
1843
+ return { namespace: "dgn_View", name: "Thumbnail", id: viewDefinitionId };
1844
+ }
1845
+ /** Get the thumbnail for a view.
1846
+ * @param viewDefinitionId The Id of the view for thumbnail
1847
+ * @returns the ThumbnailProps, or undefined if no thumbnail exists.
1848
+ */
1849
+ getThumbnail(viewDefinitionId) {
1850
+ const viewArg = this.getViewThumbnailArg(viewDefinitionId);
1851
+ const sizeProps = this._iModel.nativeDb.queryFileProperty(viewArg, true);
1852
+ if (undefined === sizeProps)
1853
+ return undefined;
1854
+ const out = JSON.parse(sizeProps);
1855
+ out.image = this._iModel.nativeDb.queryFileProperty(viewArg, false);
1856
+ return out;
1857
+ }
1858
+ /** Save a thumbnail for a view.
1859
+ * @param viewDefinitionId The Id of the view for thumbnail
1860
+ * @param thumbnail The thumbnail data.
1861
+ * @returns 0 if successful
1862
+ */
1863
+ saveThumbnail(viewDefinitionId, thumbnail) {
1864
+ const viewArg = this.getViewThumbnailArg(viewDefinitionId);
1865
+ const props = { format: thumbnail.format, height: thumbnail.height, width: thumbnail.width };
1866
+ this._iModel.nativeDb.saveFileProperty(viewArg, JSON.stringify(props), thumbnail.image);
1867
+ return 0;
1868
+ }
1869
+ /** Set the default view property the iModel
1870
+ * @param viewId The Id of the ViewDefinition to use as the default
1871
+ */
1872
+ setDefaultViewId(viewId) {
1873
+ const spec = { namespace: "dgn_View", name: "DefaultView" };
1874
+ const blob32 = new Uint32Array(2);
1875
+ blob32[0] = core_bentley_1.Id64.getLowerUint32(viewId);
1876
+ blob32[1] = core_bentley_1.Id64.getUpperUint32(viewId);
1877
+ const blob8 = new Uint8Array(blob32.buffer);
1878
+ this._iModel.saveFileProperty(spec, undefined, blob8);
1879
+ }
1880
+ }
1881
+ /** Default parameters for iterating/querying ViewDefinitions. Includes all subclasses of ViewDefinition, excluding only those marked 'private'. */
1882
+ Views.defaultQueryParams = { from: "BisCore.ViewDefinition", where: "IsPrivate=FALSE" };
1883
+ IModelDb.Views = Views;
1884
+ /** Represents the current state of a pollable tile content request.
1885
+ * Note: lack of a "completed" state because polling a completed request returns the content as a Uint8Array.
1886
+ * @internal
1887
+ */
1888
+ let TileContentState;
1889
+ (function (TileContentState) {
1890
+ TileContentState[TileContentState["New"] = 0] = "New";
1891
+ TileContentState[TileContentState["Pending"] = 1] = "Pending";
1892
+ TileContentState[TileContentState["Loading"] = 2] = "Loading";
1893
+ })(TileContentState = IModelDb.TileContentState || (IModelDb.TileContentState = {}));
1894
+ /** @internal */
1895
+ class Tiles {
1896
+ /** @internal */
1897
+ constructor(_iModel) {
1898
+ this._iModel = _iModel;
1899
+ }
1900
+ /** @internal */
1901
+ async requestTileTreeProps(id) {
1902
+ return new Promise((resolve, reject) => {
1903
+ this._iModel.nativeDb.getTileTree(id, (ret) => {
1904
+ if (undefined !== ret.error)
1905
+ reject(new core_common_1.IModelError(ret.error.status, `TreeId=${id}`));
1906
+ else
1907
+ resolve(ret.result);
1908
+ });
1909
+ });
1910
+ }
1911
+ pollTileContent(resolve, reject, treeId, tileId) {
1912
+ let ret;
1913
+ try {
1914
+ ret = this._iModel.nativeDb.pollTileContent(treeId, tileId);
1915
+ }
1916
+ catch (err) {
1917
+ // Typically "imodel not open".
1918
+ reject(err);
1919
+ return;
1920
+ }
1921
+ if (ret.error) {
1922
+ reject(new core_common_1.IModelError(ret.error.status, `TreeId=${treeId} TileId=${tileId}`));
1923
+ }
1924
+ else if (ret.result && typeof ret.result !== "number") { // if type is not a number, it's the TileContent interface
1925
+ const res = ret.result;
1926
+ const iModelId = this._iModel.iModelId;
1927
+ const tileSizeThreshold = IModelHost_1.IModelHost.logTileSizeThreshold;
1928
+ const tileSize = res.content.length;
1929
+ if (tileSize > tileSizeThreshold) {
1930
+ core_bentley_1.Logger.logWarning(loggerCategory, "Tile size (in bytes) larger than specified threshold", () => ({ tileSize, tileSizeThreshold, treeId, tileId, iModelId }));
1931
+ }
1932
+ const loadTimeThreshold = IModelHost_1.IModelHost.logTileLoadTimeThreshold;
1933
+ const loadTime = res.elapsedSeconds;
1934
+ if (loadTime > loadTimeThreshold) {
1935
+ core_bentley_1.Logger.logWarning(loggerCategory, "Tile load time (in seconds) greater than specified threshold", () => ({ loadTime, loadTimeThreshold, treeId, tileId, iModelId }));
1936
+ }
1937
+ resolve(res);
1938
+ }
1939
+ else { // if the type is a number, it's the TileContentState enum
1940
+ // ###TODO: Decide appropriate timeout interval. May want to switch on state (new vs loading vs pending)
1941
+ setTimeout(() => this.pollTileContent(resolve, reject, treeId, tileId), 10);
1942
+ }
1943
+ }
1944
+ /** @internal */
1945
+ async requestTileContent(treeId, tileId) {
1946
+ return new Promise((resolve, reject) => {
1947
+ this.pollTileContent(resolve, reject, treeId, tileId);
1948
+ });
1949
+ }
1950
+ /** @internal */
1951
+ async getTileContent(treeId, tileId) {
1952
+ const ret = await new Promise((resolve) => {
1953
+ this._iModel.nativeDb.getTileContent(treeId, tileId, resolve);
1954
+ });
1955
+ if (undefined !== ret.error) {
1956
+ throw new core_common_1.IModelError(ret.error.status, `TreeId=${treeId} TileId=${tileId}`);
1957
+ }
1958
+ (0, core_bentley_1.assert)(undefined !== ret.result);
1959
+ return ret.result;
1960
+ }
1961
+ }
1962
+ IModelDb.Tiles = Tiles;
1963
+ })(IModelDb = exports.IModelDb || (exports.IModelDb = {}));
1964
+ /**
1965
+ * A local copy of an iModel from iModelHub that can pull and potentially push changesets.
1966
+ * BriefcaseDb raises a set of events to allow apps and subsystems to track its object life cycle, including [[onOpen]] and [[onOpened]].
1967
+ * @public
1968
+ */
1969
+ class BriefcaseDb extends IModelDb {
1970
+ constructor(args) {
1971
+ super({ ...args, changeset: args.nativeDb.getCurrentChangeset() });
1972
+ /** Manages local changes to this briefcase. */
1973
+ this.txns = new TxnManager_1.TxnManager(this);
1974
+ this._openMode = args.openMode;
1975
+ this.briefcaseId = args.briefcaseId;
1976
+ if (this.useLockServer) // if the iModel uses a lock server, create a ServerBasedLocks LockControl for this BriefcaseDb.
1977
+ this._locks = new ServerBasedLocks_1.ServerBasedLocks(this);
1978
+ }
1979
+ /** override superclass method */
1980
+ get isBriefcase() { return true; }
1981
+ static findByKey(key) {
1982
+ return super.findByKey(key);
1983
+ }
1984
+ static tryFindByKey(key) {
1985
+ const db = super.tryFindByKey(key);
1986
+ return db?.isBriefcaseDb() ? db : undefined;
1987
+ }
1988
+ /**
1989
+ * The Guid that identifies the *context* that owns this iModel.
1990
+ * GuidString | undefined for the superclass, but required for BriefcaseDb
1991
+ * */
1992
+ get iTwinId() { return super.iTwinId; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
1993
+ /**
1994
+ * Determine whether this BriefcaseDb should use a lock server.
1995
+ * All must be true:
1996
+ * - file is open for write
1997
+ * - has an assigned briefcaseId
1998
+ * - the "no locking" flag is not present. This is a property of an iModel, established when the iModel is created in IModelHub.
1999
+ */
2000
+ get useLockServer() {
2001
+ return !this.isReadonly && (this.briefcaseId !== core_common_1.BriefcaseIdValue.Unassigned) && (undefined === this.nativeDb.queryLocalValue(BriefcaseLocalValue.NoLocking));
2002
+ }
2003
+ /** Upgrades the profile or domain schemas. File must be closed before this call and is always left closed. */
2004
+ static async doUpgrade(briefcase, upgradeOptions, description) {
2005
+ const nativeDb = this.openDgnDb({ path: briefcase.fileName }, core_bentley_1.OpenMode.ReadWrite, upgradeOptions); // performs the upgrade
2006
+ const wasChanges = nativeDb.hasPendingTxns();
2007
+ nativeDb.closeIModel();
2008
+ if (wasChanges)
2009
+ await withBriefcaseDb(briefcase, async (db) => db.pushChanges({ ...briefcase, description, retainLocks: true }));
2010
+ }
2011
+ /** Upgrades the schemas in the iModel based on the current version of the software. Follows a sequence of operations -
2012
+ * * Acquires a schema lock to prevent other users from making any other changes while upgrade is happening
2013
+ * * Updates the local briefcase with the schema changes.
2014
+ * * Pushes the resulting changeset(s) to iModelHub.
2015
+ * Note that the upgrade requires that the local briefcase be closed, and may result in one or two change sets depending on whether both
2016
+ * profile and domain schemas need to get upgraded.
2017
+ * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
2018
+ */
2019
+ static async upgradeSchemas(briefcase) {
2020
+ // upgrading schemas involves closing and reopening the file repeatedly. That's because the process of upgrading
2021
+ // happens on a file open. We have to open-and-close the file at *each* of these steps:
2022
+ // - acquire schema lock
2023
+ // - upgrade profile
2024
+ // - push changes
2025
+ // - upgrade domain
2026
+ // - push changes
2027
+ // - release schema lock
2028
+ // good thing computers are fast. Fortunately upgrading should be rare (and the push time will dominate anyway.) Don't try to optimize any of this away.
2029
+ await withBriefcaseDb(briefcase, async (db) => db.acquireSchemaLock()); // may not really acquire lock if iModel uses "noLocks" mode.
2030
+ try {
2031
+ await this.doUpgrade(briefcase, { profile: core_common_1.ProfileOptions.Upgrade, schemaLockHeld: true }, "Upgraded profile");
2032
+ await this.doUpgrade(briefcase, { domain: core_common_1.DomainOptions.Upgrade, schemaLockHeld: true }, "Upgraded domain schemas");
2033
+ }
2034
+ finally {
2035
+ await withBriefcaseDb(briefcase, async (db) => db.locks.releaseAllLocks());
2036
+ }
2037
+ }
2038
+ /** Open a briefcase file and return a new BriefcaseDb to interact with it.
2039
+ * @param args parameters that specify the file name, and options for opening the briefcase file
2040
+ */
2041
+ static async open(args) {
2042
+ this.onOpen.raiseEvent(args);
2043
+ const file = { path: args.fileName, key: args.key };
2044
+ const openMode = args.readonly ? core_bentley_1.OpenMode.Readonly : core_bentley_1.OpenMode.ReadWrite;
2045
+ const nativeDb = this.openDgnDb(file, openMode, undefined, args);
2046
+ const briefcaseDb = new BriefcaseDb({ nativeDb, key: file.key ?? core_bentley_1.Guid.createValue(), openMode, briefcaseId: nativeDb.getBriefcaseId() });
2047
+ if (openMode === core_bentley_1.OpenMode.ReadWrite && CodeService_1.CodeService.createForIModel) {
2048
+ try {
2049
+ const codeService = CodeService_1.CodeService.createForIModel(briefcaseDb);
2050
+ briefcaseDb._codeService = codeService;
2051
+ this.onCodeServiceCreated.raiseEvent(codeService);
2052
+ }
2053
+ catch (e) {
2054
+ if (e.errorId !== "NoCodeIndex") // no code index means iModel isn't enforcing codes.
2055
+ throw e;
2056
+ }
2057
+ }
2058
+ BriefcaseManager_1.BriefcaseManager.logUsage(briefcaseDb);
2059
+ this.onOpened.raiseEvent(briefcaseDb, args);
2060
+ return briefcaseDb;
2061
+ }
2062
+ closeAndReopen(openMode) {
2063
+ const fileName = this.pathName;
2064
+ this.nativeDb.closeIModel();
2065
+ this.nativeDb.openIModel(fileName, openMode);
2066
+ }
2067
+ /** Pull and apply changesets from iModelHub */
2068
+ async pullChanges(arg) {
2069
+ if (this.isReadonly) // we allow pulling changes into a briefcase that is readonly - close and reopen it writeable
2070
+ this.closeAndReopen(core_bentley_1.OpenMode.ReadWrite);
2071
+ try {
2072
+ await BriefcaseManager_1.BriefcaseManager.pullAndApplyChangesets(this, arg ?? {});
2073
+ this.initializeIModelDb();
2074
+ }
2075
+ finally {
2076
+ if (this.isReadonly) // if the briefcase was opened readonly - close and reopen it readonly
2077
+ this.closeAndReopen(core_bentley_1.OpenMode.Readonly);
2078
+ }
2079
+ IpcHost_1.IpcHost.notifyTxns(this, "notifyPulledChanges", this.changeset);
2080
+ }
2081
+ /** Push changes to iModelHub. */
2082
+ async pushChanges(arg) {
2083
+ if (this.briefcaseId === core_common_1.BriefcaseIdValue.Unassigned)
2084
+ return;
2085
+ if (this.nativeDb.hasUnsavedChanges())
2086
+ throw new core_common_1.IModelError(core_bentley_1.ChangeSetStatus.HasUncommittedChanges, "Cannot push with unsaved changes");
2087
+ if (!this.nativeDb.hasPendingTxns())
2088
+ return; // nothing to push
2089
+ await BriefcaseManager_1.BriefcaseManager.pullMergePush(this, arg);
2090
+ this.initializeIModelDb();
2091
+ const changeset = this.changeset;
2092
+ IpcHost_1.IpcHost.notifyTxns(this, "notifyPushedChanges", changeset);
2093
+ }
2094
+ }
2095
+ exports.BriefcaseDb = BriefcaseDb;
2096
+ /**
2097
+ * Event raised just before a BriefcaseDb is opened. Supplies the arguments that will be used to open the BriefcaseDb.
2098
+ * Throw an exception to stop the open.
2099
+ *
2100
+ * **Example:**
2101
+ * ``` ts
2102
+ * [[include:BriefcaseDb.onOpen]]
2103
+ * ```
2104
+ */
2105
+ BriefcaseDb.onOpen = new core_bentley_1.BeEvent();
2106
+ /**
2107
+ * Event raised just after a BriefcaseDb is opened. Supplies the newly opened BriefcaseDb and the arguments that were used to open it.
2108
+ *
2109
+ * **Example:**
2110
+ * ``` ts
2111
+ * [[include:BriefcaseDb.onOpened]]
2112
+ * ```
2113
+ */
2114
+ BriefcaseDb.onOpened = new core_bentley_1.BeEvent();
2115
+ /** @alpha */
2116
+ BriefcaseDb.onCodeServiceCreated = new core_bentley_1.BeEvent();
2117
+ /** Used to reattach Daemon from a user's accessToken for V2 checkpoints.
2118
+ * @note Reattach only happens if the previous access token either has expired or is about to expire within an application-supplied safety duration.
2119
+ */
2120
+ class RefreshV2CheckpointSas {
2121
+ constructor(sasToken, safetySeconds) {
2122
+ /** the time at which the current token should be refreshed (its expiry minus safetySeconds) */
2123
+ this._timestamp = 0;
2124
+ this._safetySeconds = safetySeconds ?? 60 * 60; // default to 1 hour
2125
+ this.setTimestamp(sasToken);
2126
+ }
2127
+ async performRefresh(accessToken, iModel) {
2128
+ this._timestamp = 0; // everyone needs to wait until token is valid
2129
+ // we're going to request that the checkpoint manager use this user's accessToken to obtain a new access token for this checkpoint's storage account.
2130
+ core_bentley_1.Logger.logInfo(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "attempting to refresh sasToken for checkpoint");
2131
+ try {
2132
+ // this exchanges the supplied user accessToken for an expiring blob-store token to read the checkpoint.
2133
+ const container = iModel.nativeDb.cloudContainer;
2134
+ if (!container)
2135
+ throw new Error("checkpoint is not from a cloud container");
2136
+ (0, core_bentley_1.assert)(undefined !== iModel.iTwinId);
2137
+ const props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint({ accessToken, iTwinId: iModel.iTwinId, iModelId: iModel.iModelId, changeset: iModel.changeset });
2138
+ if (!props)
2139
+ throw new Error("can't reset checkpoint sas token");
2140
+ container.accessToken = props.sasToken;
2141
+ this.setTimestamp(props.sasToken);
2142
+ core_bentley_1.Logger.logInfo(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "refreshed checkpoint sasToken successfully");
2143
+ }
2144
+ finally {
2145
+ this._promise = undefined;
2146
+ }
2147
+ }
2148
+ setTimestamp(sasToken) {
2149
+ const exp = new URLSearchParams(sasToken).get("se");
2150
+ const sasTokenExpiry = exp ? Date.parse(exp) : 0;
2151
+ this._timestamp = sasTokenExpiry - (this._safetySeconds * 1000);
2152
+ if (this._timestamp < Date.now())
2153
+ core_bentley_1.Logger.logError(BackendLoggerCategory_1.BackendLoggerCategory.Authorization, "attached with timestamp that expires before safety interval");
2154
+ }
2155
+ async refreshSas(accessToken, iModel) {
2156
+ if (this._timestamp > Date.now())
2157
+ return; // current token is fine
2158
+ if (undefined === this._promise) // has reattach already begun?
2159
+ this._promise = this.performRefresh(accessToken, iModel); // no, start it
2160
+ return this._promise;
2161
+ }
2162
+ }
2163
+ /** A *snapshot* iModel database file that is used for archival and data transfer purposes.
2164
+ * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2165
+ * @see [About IModelDb]($docs/learning/backend/IModelDb.md)
2166
+ * @public
2167
+ */
2168
+ class SnapshotDb extends IModelDb {
2169
+ constructor(nativeDb, key) {
2170
+ super({ nativeDb, key, changeset: nativeDb.getCurrentChangeset() });
2171
+ this._openMode = nativeDb.isReadonly() ? core_bentley_1.OpenMode.Readonly : core_bentley_1.OpenMode.ReadWrite;
2172
+ }
2173
+ get isSnapshot() { return true; }
2174
+ static findByKey(key) {
2175
+ return super.findByKey(key);
2176
+ }
2177
+ static tryFindByKey(key) {
2178
+ const db = super.tryFindByKey(key);
2179
+ return db?.isSnapshotDb() ? db : undefined;
2180
+ }
2181
+ /** Create an *empty* local [Snapshot]($docs/learning/backend/AccessingIModels.md#snapshot-imodels) iModel file.
2182
+ * Snapshots are not synchronized with iModelHub, so do not have a change timeline.
2183
+ * > Note: A *snapshot* cannot be modified after [[close]] is called.
2184
+ * @param filePath The file that will contain the new iModel *snapshot*
2185
+ * @param options The parameters that define the new iModel *snapshot*
2186
+ * @returns A writeable SnapshotDb
2187
+ * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2188
+ */
2189
+ static createEmpty(filePath, options) {
2190
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2191
+ nativeDb.createIModel(filePath, options);
2192
+ nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2193
+ const snapshotDb = new SnapshotDb(nativeDb, core_bentley_1.Guid.createValue());
2194
+ if (options.createClassViews)
2195
+ snapshotDb._createClassViewsOnClose = true; // save flag that will be checked when close() is called
2196
+ return snapshotDb;
2197
+ }
2198
+ /** Create a local [Snapshot]($docs/learning/backend/AccessingIModels.md#snapshot-imodels) iModel file, using this iModel as a *seed* or starting point.
2199
+ * Snapshots are not synchronized with iModelHub, so do not have a change timeline.
2200
+ * > Note: A *snapshot* cannot be modified after [[close]] is called.
2201
+ * @param iModelDb The snapshot will be initialized from the current contents of this iModelDb
2202
+ * @param snapshotFile The file that will contain the new iModel *snapshot*
2203
+ * @param options Optional properties that determine how the snapshot iModel is created.
2204
+ * @returns A writeable SnapshotDb
2205
+ * @see [Snapshot iModels]($docs/learning/backend/AccessingIModels.md#snapshot-imodels)
2206
+ */
2207
+ static createFrom(iModelDb, snapshotFile, options) {
2208
+ iModelDb.performCheckpoint();
2209
+ IModelJsFs_1.IModelJsFs.copySync(iModelDb.pathName, snapshotFile);
2210
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2211
+ nativeDb.openIModel(snapshotFile, core_bentley_1.OpenMode.ReadWrite, undefined, options);
2212
+ nativeDb.vacuum();
2213
+ // Replace iModelId if seedFile is a snapshot, preserve iModelId if seedFile is an iModelHub-managed briefcase
2214
+ if (!BriefcaseManager_1.BriefcaseManager.isValidBriefcaseId(nativeDb.getBriefcaseId()))
2215
+ nativeDb.setIModelId(core_bentley_1.Guid.createValue());
2216
+ nativeDb.deleteLocalValue(BriefcaseLocalValue.StandaloneEdit);
2217
+ nativeDb.saveChanges();
2218
+ nativeDb.deleteAllTxns();
2219
+ nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2220
+ const snapshotDb = new SnapshotDb(nativeDb, core_bentley_1.Guid.createValue());
2221
+ if (options?.createClassViews)
2222
+ snapshotDb._createClassViewsOnClose = true; // save flag that will be checked when close() is called
2223
+ return snapshotDb;
2224
+ }
2225
+ /** open this SnapshotDb read/write, strictly to apply incoming changesets. Used for creating new checkpoints.
2226
+ * @internal
2227
+ */
2228
+ static openForApplyChangesets(path, props) {
2229
+ const file = { path, key: props?.key };
2230
+ const nativeDb = this.openDgnDb(file, core_bentley_1.OpenMode.ReadWrite, undefined, props);
2231
+ (0, core_bentley_1.assert)(undefined !== file.key);
2232
+ return new SnapshotDb(nativeDb, file.key);
2233
+ }
2234
+ /** Open a read-only iModel *snapshot*.
2235
+ * @param path the full path of the snapshot iModel file to open.
2236
+ * @param props options for opening snapshot
2237
+ * @see [[close]]
2238
+ * @throws [[IModelError]] If the file is not found or is not a valid *snapshot*.
2239
+ */
2240
+ static openFile(path, opts) {
2241
+ const file = { path, key: opts?.key };
2242
+ const nativeDb = this.openDgnDb(file, core_bentley_1.OpenMode.Readonly, undefined, opts);
2243
+ (0, core_bentley_1.assert)(undefined !== file.key);
2244
+ return new SnapshotDb(nativeDb, file.key);
2245
+ }
2246
+ /** Open a previously downloaded V1 checkpoint file.
2247
+ * @note The key is generated by this call is predictable and is formed from the IModelId and ChangeSetId.
2248
+ * This is so every backend working on the same checkpoint will use the same key, to permit multiple backends
2249
+ * servicing the same checkpoint.
2250
+ * @internal
2251
+ */
2252
+ static openCheckpointV1(fileName, checkpoint) {
2253
+ const snapshot = this.openFile(fileName, { key: CheckpointManager_1.CheckpointManager.getKey(checkpoint) });
2254
+ snapshot._iTwinId = checkpoint.iTwinId;
2255
+ return snapshot;
2256
+ }
2257
+ /** Open a V2 *checkpoint*, a special form of snapshot iModel that represents a read-only snapshot of an iModel from iModelHub at a particular point in time.
2258
+ * > Note: The checkpoint daemon must already be running and a checkpoint must already exist in iModelHub's storage *before* this function is called.
2259
+ * @param checkpoint The checkpoint to open
2260
+ * @note The key generated by this call is predictable and is formed from the IModelId and ChangeSetId.
2261
+ * This is so every backend working on the same checkpoint will use the same key, to permit multiple backends
2262
+ * servicing the same checkpoint.
2263
+ * @throws [[IModelError]] If the checkpoint is not found in iModelHub or the checkpoint daemon is not supported in the current environment.
2264
+ * @internal
2265
+ */
2266
+ static async openCheckpointV2(checkpoint) {
2267
+ const { dbName, container } = await CheckpointManager_1.V2CheckpointManager.attach(checkpoint);
2268
+ const key = CheckpointManager_1.CheckpointManager.getKey(checkpoint);
2269
+ const tempFileBase = (0, path_1.join)(IModelHost_1.IModelHost.cacheDir, `${checkpoint.iModelId}\$${checkpoint.changeset.id}`); // temp files for this checkpoint should go in the cacheDir.
2270
+ const snapshot = SnapshotDb.openFile(dbName, { key, tempFileBase, container });
2271
+ snapshot._iTwinId = checkpoint.iTwinId;
2272
+ try {
2273
+ CheckpointManager_1.CheckpointManager.validateCheckpointGuids(checkpoint, snapshot);
2274
+ }
2275
+ catch (err) {
2276
+ snapshot.close();
2277
+ throw err;
2278
+ }
2279
+ snapshot._refreshSas = new RefreshV2CheckpointSas(container.accessToken, checkpoint.reattachSafetySeconds);
2280
+ return snapshot;
2281
+ }
2282
+ /** Used to refresh the container sasToken using the current user's accessToken
2283
+ * @internal
2284
+ */
2285
+ async refreshContainerSas(userAccessToken) {
2286
+ return this._refreshSas?.refreshSas(userAccessToken, this);
2287
+ }
2288
+ /** @internal */
2289
+ beforeClose() {
2290
+ super.beforeClose();
2291
+ if (this._createClassViewsOnClose) { // check for flag set during create
2292
+ if (core_bentley_1.BentleyStatus.SUCCESS !== this.nativeDb.createClassViewsInDb()) {
2293
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.SQLiteError, "Error creating class views");
2294
+ }
2295
+ else {
2296
+ this.saveChanges();
2297
+ }
2298
+ }
2299
+ }
2300
+ }
2301
+ exports.SnapshotDb = SnapshotDb;
2302
+ /**
2303
+ * Standalone iModels are read/write files that are not associated with an iTwin or managed by iModelHub.
2304
+ * They are relevant only for testing, or for small-scale single-user scenarios.
2305
+ * Standalone iModels are designed such that the API for Standalone iModels and Briefcase
2306
+ * iModels (those synchronized with iModelHub) are as similar and consistent as possible.
2307
+ * This leads to a straightforward process where the a user starts with StandaloneDb and can
2308
+ * optionally choose to upgrade to an iTwin.
2309
+ *
2310
+ * Some additional details. Standalone iModels:
2311
+ * - always have [Guid.empty]($bentley) for their iTwinId (they are "unassociated" files)
2312
+ * - always have BriefcaseId === [BriefcaseIdValue.Unassigned]($common)
2313
+ * - are connected to the frontend via [BriefcaseConnection.openStandalone]($frontend)
2314
+ * - may be opened without supplying any user credentials
2315
+ * - may be opened read/write
2316
+ * - cannot apply a changeset to nor generate a changesets (since there is no timeline from which to get/push changesets)
2317
+ * @public
2318
+ */
2319
+ class StandaloneDb extends BriefcaseDb {
2320
+ get isStandalone() { return true; }
2321
+ get useLockServer() { return false; } // standalone iModels have no lock server
2322
+ static findByKey(key) {
2323
+ return super.findByKey(key);
2324
+ }
2325
+ static tryFindByKey(key) {
2326
+ const db = super.tryFindByKey(key);
2327
+ return db?.isStandaloneDb() ? db : undefined;
2328
+ }
2329
+ /** Create an *empty* standalone iModel.
2330
+ * @param filePath The file path for the iModel
2331
+ * @param args The parameters that define the new iModel
2332
+ */
2333
+ static createEmpty(filePath, args) {
2334
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
2335
+ nativeDb.createIModel(filePath, args);
2336
+ nativeDb.saveLocalValue(BriefcaseLocalValue.StandaloneEdit, args.allowEdit);
2337
+ nativeDb.setITwinId(core_bentley_1.Guid.empty);
2338
+ nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
2339
+ nativeDb.saveChanges();
2340
+ return new StandaloneDb({ nativeDb, key: core_bentley_1.Guid.createValue(), briefcaseId: core_common_1.BriefcaseIdValue.Unassigned, openMode: core_bentley_1.OpenMode.ReadWrite });
2341
+ }
2342
+ /**
2343
+ * Upgrades the schemas in the standalone iModel file.
2344
+ * Note that the upgrade requires that the file be closed, and will leave it back in the closed state.
2345
+ * @param filePath Full path name of the standalone iModel file.
2346
+ * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel)
2347
+ * @see [[StandaloneDb.validateSchemas]]
2348
+ */
2349
+ static upgradeStandaloneSchemas(filePath) {
2350
+ let nativeDb = this.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.ReadWrite, { profile: core_common_1.ProfileOptions.Upgrade, schemaLockHeld: true });
2351
+ nativeDb.closeIModel();
2352
+ nativeDb = this.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.ReadWrite, { domain: core_common_1.DomainOptions.Upgrade, schemaLockHeld: true });
2353
+ nativeDb.closeIModel();
2354
+ }
2355
+ /** Open a standalone iModel file.
2356
+ * @param filePath The path of the standalone iModel file.
2357
+ * @param openMode Optional open mode for the standalone iModel. The default is read/write.
2358
+ * @throws [[IModelError]] if the file is not a standalone iModel.
2359
+ * @see [BriefcaseConnection.openStandalone]($frontend) to open a StandaloneDb from the frontend
2360
+ */
2361
+ static openFile(filePath, openMode = core_bentley_1.OpenMode.ReadWrite, options) {
2362
+ const file = { path: filePath, key: options?.key };
2363
+ const nativeDb = this.openDgnDb(file, openMode, undefined, options);
2364
+ try {
2365
+ const iTwinId = nativeDb.getITwinId();
2366
+ if (iTwinId !== core_bentley_1.Guid.empty) // a "standalone" iModel means it is not associated with an iTwin
2367
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.WrongIModel, `${filePath} is not a Standalone iModel. iTwinId=${iTwinId}`);
2368
+ (0, core_bentley_1.assert)(undefined !== file.key);
2369
+ return new StandaloneDb({ nativeDb, key: file.key, openMode, briefcaseId: core_common_1.BriefcaseIdValue.Unassigned });
2370
+ }
2371
+ catch (error) {
2372
+ nativeDb.closeIModel();
2373
+ throw error;
2374
+ }
2375
+ }
2376
+ }
2377
+ exports.StandaloneDb = StandaloneDb;
2378
2378
  //# sourceMappingURL=IModelDb.js.map