@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,581 +1,581 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.LocalHub = void 0;
8
- const path_1 = require("path");
9
- const core_bentley_1 = require("@itwin/core-bentley");
10
- const core_common_1 = require("@itwin/core-common");
11
- const BackendHubAccess_1 = require("./BackendHubAccess");
12
- const BriefcaseManager_1 = require("./BriefcaseManager");
13
- const IModelDb_1 = require("./IModelDb");
14
- const IModelJsFs_1 = require("./IModelJsFs");
15
- const SQLiteDb_1 = require("./SQLiteDb");
16
- /**
17
- * A "local" mock for IModelHub to provide access to a single iModel. Used by HubMock.
18
- * @internal
19
- */
20
- class LocalHub {
21
- constructor(rootDir, arg) {
22
- this.rootDir = rootDir;
23
- this._nextBriefcaseId = core_common_1.BriefcaseIdValue.FirstValid;
24
- this._latestChangesetIndex = 0;
25
- this.iTwinId = arg.iTwinId;
26
- this.iModelId = arg.iModelId;
27
- this.iModelName = arg.iModelName;
28
- this.description = arg.description;
29
- this.cleanup();
30
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(this.rootDir);
31
- IModelJsFs_1.IModelJsFs.mkdirSync(this.changesetDir);
32
- IModelJsFs_1.IModelJsFs.mkdirSync(this.checkpointDir);
33
- const db = this._hubDb = new SQLiteDb_1.SQLiteDb();
34
- db.createDb(this.mockDbName);
35
- db.executeSQL("CREATE TABLE briefcases(id INTEGER PRIMARY KEY NOT NULL,user TEXT NOT NULL,alias TEXT NOT NULL,assigned INTEGER DEFAULT 1)");
36
- db.executeSQL("CREATE TABLE timeline(csIndex INTEGER PRIMARY KEY NOT NULL,csId TEXT NOT NULL UNIQUE,description TEXT,user TEXT,size BIGINT,type INTEGER,pushDate TEXT,briefcaseId INTEGER,\
37
- FOREIGN KEY(briefcaseId) REFERENCES briefcases(id))");
38
- db.executeSQL("CREATE TABLE checkpoints(csIndex INTEGER PRIMARY KEY NOT NULL)");
39
- db.executeSQL("CREATE TABLE versions(name TEXT PRIMARY KEY NOT NULL,csIndex TEXT,FOREIGN KEY(csIndex) REFERENCES timeline(csIndex))");
40
- db.executeSQL("CREATE TABLE locks(id INTEGER PRIMARY KEY NOT NULL,level INTEGER NOT NULL,lastCSetIndex INTEGER,briefcaseId INTEGER)");
41
- db.executeSQL("CREATE TABLE sharedLocks(lockId INTEGER NOT NULL,briefcaseId INTEGER NOT NULL,PRIMARY KEY(lockId,briefcaseId))");
42
- db.executeSQL("CREATE INDEX LockIdx ON locks(briefcaseId)");
43
- db.executeSQL("CREATE INDEX SharedLockIdx ON sharedLocks(briefcaseId)");
44
- db.saveChanges();
45
- const version0Root = `${rootDir}_version0`;
46
- const version0 = arg.version0 ?? (0, path_1.join)(version0Root, "version0.bim");
47
- if (!arg.version0) { // if they didn't supply a version0 file, create a blank one.
48
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(version0Root);
49
- IModelJsFs_1.IModelJsFs.removeSync(version0);
50
- IModelDb_1.SnapshotDb.createEmpty(version0, { rootSubject: { name: arg.description ?? arg.iModelName } }).close();
51
- }
52
- const path = this.uploadCheckpoint({ changesetIndex: 0, localFile: version0 });
53
- if (!arg.version0)
54
- IModelJsFs_1.IModelJsFs.removeSync(version0);
55
- const nativeDb = IModelDb_1.IModelDb.openDgnDb({ path }, core_bentley_1.OpenMode.ReadWrite);
56
- try {
57
- nativeDb.setITwinId(this.iTwinId);
58
- nativeDb.setIModelId(this.iModelId);
59
- nativeDb.saveChanges();
60
- nativeDb.deleteAllTxns(); // necessary before resetting briefcaseId
61
- nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
62
- nativeDb.saveLocalValue(IModelDb_1.BriefcaseLocalValue.NoLocking, arg.noLocks ? "true" : undefined);
63
- nativeDb.saveChanges();
64
- }
65
- finally {
66
- nativeDb.closeIModel();
67
- }
68
- }
69
- get latestChangesetIndex() { return this._latestChangesetIndex; }
70
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
71
- get db() { return this._hubDb; } // eslint-disable-line @typescript-eslint/naming-convention
72
- get changesetDir() { return (0, path_1.join)(this.rootDir, "changesets"); }
73
- get checkpointDir() { return (0, path_1.join)(this.rootDir, "checkpoints"); }
74
- get mockDbName() { return (0, path_1.join)(this.rootDir, "localHub.db"); }
75
- /** Acquire the next available briefcaseId and assign it to the supplied user */
76
- acquireNewBriefcaseId(user, alias) {
77
- const db = this.db;
78
- const newId = this._nextBriefcaseId++;
79
- db.withSqliteStatement("INSERT INTO briefcases(id,user,alias) VALUES (?,?,?)", (stmt) => {
80
- stmt.bindInteger(1, newId);
81
- stmt.bindString(2, user);
82
- stmt.bindString(3, alias ?? `${user} (${newId})`);
83
- const rc = stmt.step();
84
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
85
- throw new core_common_1.IModelError(rc, "can't insert briefcaseId in mock database");
86
- });
87
- db.saveChanges();
88
- return newId;
89
- }
90
- /** Release a briefcaseId */
91
- releaseBriefcaseId(id) {
92
- const db = this.db;
93
- this.releaseAllLocks({ briefcaseId: id, changesetIndex: 0 });
94
- db.withSqliteStatement("UPDATE briefcases SET assigned=0 WHERE id=?", (stmt) => {
95
- stmt.bindInteger(1, id);
96
- const rc = stmt.step();
97
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
98
- throw new core_common_1.IModelError(rc, `briefcaseId ${id} was not reserved`);
99
- });
100
- db.saveChanges();
101
- }
102
- /** Get an array of all of the currently assigned Briefcases */
103
- getBriefcases(onlyAssigned = true) {
104
- const briefcases = [];
105
- let sql = "SELECT id,user,alias,assigned FROM briefcases";
106
- if (onlyAssigned)
107
- sql += " WHERE assigned=1";
108
- this.db.withSqliteStatement(sql, (stmt) => {
109
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
110
- briefcases.push({
111
- id: stmt.getValueInteger(0),
112
- user: stmt.getValueString(1),
113
- alias: stmt.getValueString(2),
114
- assigned: stmt.getValueInteger(3) !== 0,
115
- });
116
- }
117
- });
118
- return briefcases;
119
- }
120
- /** Get an array of all of the currently assigned BriefcaseIds for a user */
121
- getBriefcaseIds(user) {
122
- const briefcases = [];
123
- this.db.withSqliteStatement("SELECT id FROM briefcases WHERE user=? AND assigned=1", (stmt) => {
124
- stmt.bindString(1, user);
125
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
126
- briefcases.push(stmt.getValueInteger(0));
127
- });
128
- return briefcases;
129
- }
130
- getBriefcase(id) {
131
- return this.db.withSqliteStatement("SELECT user,alias,assigned FROM briefcases WHERE id=?", (stmt) => {
132
- stmt.bindInteger(1, id);
133
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== stmt.step())
134
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "no briefcase with that id");
135
- return { id, user: stmt.getValueString(0), alias: stmt.getValueString(1), assigned: stmt.getValueInteger(2) !== 0 };
136
- });
137
- }
138
- getChangesetFileName(index) {
139
- return (0, path_1.join)(this.changesetDir, `changeset-${index}`);
140
- }
141
- /** Add a changeset to the timeline
142
- * @return the changesetIndex of the added changeset
143
- */
144
- addChangeset(changeset) {
145
- const stats = IModelJsFs_1.IModelJsFs.lstatSync(changeset.pathname);
146
- if (!stats)
147
- throw new Error(`cannot read changeset file ${changeset.pathname}`);
148
- const parentIndex = this.getChangesetById(changeset.parentId).index;
149
- if (parentIndex !== this.latestChangesetIndex)
150
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidParent, "changeset parent is not latest changeset");
151
- this.getBriefcase(changeset.briefcaseId); // throws if invalid id
152
- const db = this.db;
153
- changeset.index = this._latestChangesetIndex + 1;
154
- db.withSqliteStatement("INSERT INTO timeline(csIndex,csId,description,size,type,pushDate,user,briefcaseId) VALUES (?,?,?,?,?,?,?,?)", (stmt) => {
155
- stmt.bindInteger(1, changeset.index);
156
- stmt.bindString(2, changeset.id);
157
- stmt.bindString(3, changeset.description);
158
- stmt.bindInteger(4, stats.size);
159
- stmt.bindInteger(5, changeset.changesType ?? 0);
160
- stmt.bindString(6, changeset.pushDate ?? new Date().toISOString());
161
- stmt.bindString(7, changeset.userCreated ?? "");
162
- stmt.bindInteger(8, changeset.briefcaseId);
163
- const rc = stmt.step();
164
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
165
- throw new core_common_1.IModelError(rc, "can't insert changeset into mock db");
166
- });
167
- this._latestChangesetIndex = changeset.index; // only change this after insert succeeds
168
- db.saveChanges();
169
- IModelJsFs_1.IModelJsFs.copySync(changeset.pathname, this.getChangesetFileName(changeset.index));
170
- return changeset.index;
171
- }
172
- getIndexFromChangeset(changeset) {
173
- return changeset.index ?? this.getChangesetIndex(changeset.id);
174
- }
175
- /** Get the index of a changeset by its Id */
176
- getChangesetIndex(id) {
177
- if (id === "")
178
- return 0;
179
- return this.db.withPreparedSqliteStatement("SELECT csIndex FROM timeline WHERE csId=?", (stmt) => {
180
- stmt.bindString(1, id);
181
- const rc = stmt.step();
182
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
183
- throw new core_common_1.IModelError(rc, `changeset ${id} not found`);
184
- return stmt.getValueInteger(0);
185
- });
186
- }
187
- /** Get the properties of a changeset by its Id */
188
- getChangesetById(id) {
189
- return this.getChangesetByIndex(this.getChangesetIndex(id));
190
- }
191
- getPreviousIndex(index) {
192
- return this.db.withPreparedSqliteStatement("SELECT max(csIndex) FROM timeline WHERE csIndex<?", (stmt) => {
193
- stmt.bindInteger(1, index);
194
- const rc = stmt.step();
195
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
196
- throw new core_common_1.IModelError(rc, `cannot get previous index`);
197
- return stmt.getValueInteger(0);
198
- });
199
- }
200
- getParentId(index) {
201
- if (index === 0)
202
- return "";
203
- return this.db.withPreparedSqliteStatement("SELECT csId FROM timeline WHERE csIndex=?", (stmt) => {
204
- stmt.bindInteger(1, this.getPreviousIndex(index));
205
- stmt.step();
206
- return stmt.getValueString(0);
207
- });
208
- }
209
- /** Get the properties of a changeset by its index */
210
- getChangesetByIndex(index) {
211
- if (index <= 0)
212
- return { id: "", changesType: 0, description: "version0", parentId: "", briefcaseId: 0, pushDate: "", userCreated: "", index: 0 };
213
- return this.db.withPreparedSqliteStatement("SELECT description,size,type,pushDate,user,csId,briefcaseId FROM timeline WHERE csIndex=?", (stmt) => {
214
- stmt.bindInteger(1, index);
215
- const rc = stmt.step();
216
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
217
- throw new core_common_1.IModelError(rc, `changeset at index ${index} not found`);
218
- return {
219
- description: stmt.getValueString(0),
220
- size: stmt.getValueDouble(1),
221
- changesType: stmt.getValueInteger(2),
222
- pushDate: stmt.getValueString(3),
223
- userCreated: stmt.getValueString(4),
224
- id: stmt.getValueString(5),
225
- briefcaseId: stmt.getValueInteger(6),
226
- index,
227
- parentId: this.getParentId(index),
228
- };
229
- });
230
- }
231
- getLatestChangeset() {
232
- return this.getChangesetByIndex(this.latestChangesetIndex);
233
- }
234
- getChangesetId(index) {
235
- return this.getChangesetByIndex(index).id;
236
- }
237
- /** Get an array of changesets starting with first to last, by index */
238
- queryChangesets(range) {
239
- const changesets = [];
240
- const first = range?.first ?? 0;
241
- const last = range?.end ?? this.latestChangesetIndex;
242
- this.db.withPreparedSqliteStatement("SELECT csIndex FROM timeline WHERE csIndex>=? AND csIndex<=? ORDER BY csIndex", (stmt) => {
243
- stmt.bindInteger(1, first);
244
- stmt.bindInteger(2, last);
245
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
246
- changesets.push(this.getChangesetByIndex(stmt.getValueInteger(0)));
247
- });
248
- return changesets;
249
- }
250
- /** Name a version */
251
- addNamedVersion(arg) {
252
- const db = this.db;
253
- db.withSqliteStatement("INSERT INTO versions(name,csIndex) VALUES (?,?)", (stmt) => {
254
- stmt.bindString(1, arg.versionName);
255
- stmt.bindInteger(2, arg.csIndex);
256
- const rc = stmt.step();
257
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
258
- throw new core_common_1.IModelError(rc, "can't insert named version");
259
- });
260
- db.saveChanges();
261
- }
262
- /** Delete a named version */
263
- deleteNamedVersion(versionName) {
264
- const db = this.db;
265
- db.withSqliteStatement("DELETE FROM versions WHERE name=?", (stmt) => {
266
- stmt.bindString(1, versionName);
267
- const rc = stmt.step();
268
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
269
- throw new core_common_1.IModelError(rc, "can't delete named version");
270
- });
271
- db.saveChanges();
272
- }
273
- /** find the changeset for a named version */
274
- findNamedVersion(versionName) {
275
- const index = this.db.withSqliteStatement("SELECT csIndex FROM versions WHERE name=?", (stmt) => {
276
- stmt.bindString(1, versionName);
277
- const rc = stmt.step();
278
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
279
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Named version ${versionName} not found`);
280
- return stmt.getValueInteger(0);
281
- });
282
- return this.getChangesetByIndex(index);
283
- }
284
- checkpointNameFromIndex(csIndex) {
285
- return `checkpoint-${csIndex}`;
286
- }
287
- /** "upload" a checkpoint */
288
- uploadCheckpoint(arg) {
289
- const db = this.db;
290
- db.withSqliteStatement("INSERT INTO checkpoints(csIndex) VALUES (?)", (stmt) => {
291
- stmt.bindInteger(1, arg.changesetIndex);
292
- const res = stmt.step();
293
- if (core_bentley_1.DbResult.BE_SQLITE_DONE !== res)
294
- throw new core_common_1.IModelError(res, "can't insert checkpoint into mock db");
295
- });
296
- db.saveChanges();
297
- const outName = (0, path_1.join)(this.checkpointDir, this.checkpointNameFromIndex(arg.changesetIndex));
298
- IModelJsFs_1.IModelJsFs.copySync(arg.localFile, outName);
299
- return outName;
300
- }
301
- /** Get an array of the indexes for a range of checkpoints */
302
- getCheckpoints(range) {
303
- const first = range?.first ?? 0;
304
- const last = range?.end ?? this.latestChangesetIndex;
305
- const checkpoints = [];
306
- this.db.withSqliteStatement("SELECT csIndex FROM checkpoints WHERE csIndex>=? AND csIndex<=? ORDER BY csIndex", (stmt) => {
307
- stmt.bindInteger(1, first);
308
- stmt.bindInteger(2, last);
309
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
310
- checkpoints.push(stmt.getValueInteger(0));
311
- });
312
- return checkpoints;
313
- }
314
- /** Find the checkpoint that is no newer than a changesetIndex */
315
- queryPreviousCheckpoint(changesetIndex) {
316
- if (changesetIndex <= 0)
317
- return 0;
318
- return this.db.withSqliteStatement("SELECT max(csIndex) FROM checkpoints WHERE csIndex <= ? ", (stmt) => {
319
- stmt.bindInteger(1, changesetIndex);
320
- const res = stmt.step();
321
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== res)
322
- throw new core_common_1.IModelError(res, "can't get previous checkpoint");
323
- return stmt.getValueInteger(0);
324
- });
325
- }
326
- /** "download" a checkpoint */
327
- downloadCheckpoint(arg) {
328
- const index = this.getIndexFromChangeset(arg.changeset);
329
- const prev = this.queryPreviousCheckpoint(index);
330
- IModelJsFs_1.IModelJsFs.copySync((0, path_1.join)(this.checkpointDir, this.checkpointNameFromIndex(prev)), arg.targetFile);
331
- const changeset = this.getChangesetByIndex(index);
332
- return { index, id: changeset.id };
333
- }
334
- copyChangeset(arg) {
335
- IModelJsFs_1.IModelJsFs.copySync(this.getChangesetFileName(arg.index), arg.pathname);
336
- return arg;
337
- }
338
- /** "download" a changeset */
339
- downloadChangeset(arg) {
340
- const cs = this.getChangesetByIndex(arg.index);
341
- const csProps = { ...cs, pathname: (0, path_1.join)(arg.targetDir, cs.id), index: arg.index };
342
- return this.copyChangeset(csProps);
343
- }
344
- /** "download" all the changesets in a given range */
345
- downloadChangesets(arg) {
346
- const cSets = this.queryChangesets(arg.range);
347
- for (const cs of cSets) {
348
- cs.pathname = (0, path_1.join)(arg.targetDir, cs.id);
349
- this.copyChangeset(cs);
350
- }
351
- return cSets;
352
- }
353
- querySharedLockHolders(elementId) {
354
- return this.db.withPreparedSqliteStatement("SELECT briefcaseId FROM sharedLocks WHERE lockId=?", (stmt) => {
355
- stmt.bindId(1, elementId);
356
- const briefcases = new Set();
357
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
358
- briefcases.add(stmt.getValueInteger(0));
359
- return briefcases;
360
- });
361
- }
362
- queryAllLocks(briefcaseId) {
363
- this.getBriefcase(briefcaseId); // throws if briefcaseId invalid.
364
- const locks = [];
365
- this.db.withPreparedSqliteStatement("SELECT id FROM locks WHERE briefcaseId=?", (stmt) => {
366
- stmt.bindInteger(1, briefcaseId);
367
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
368
- locks.push({ id: stmt.getValueId(0), state: BackendHubAccess_1.LockState.Exclusive });
369
- });
370
- this.db.withPreparedSqliteStatement("SELECT lockId FROM sharedLocks WHERE briefcaseId=?", (stmt) => {
371
- stmt.bindInteger(1, briefcaseId);
372
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
373
- locks.push({ id: stmt.getValueId(0), state: BackendHubAccess_1.LockState.Shared });
374
- });
375
- return locks;
376
- }
377
- queryLockStatus(elementId) {
378
- return this.db.withPreparedSqliteStatement("SELECT lastCSetIndex,level,briefcaseId FROM locks WHERE id=?", (stmt) => {
379
- stmt.bindId(1, elementId);
380
- const rc = stmt.step();
381
- if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
382
- return { state: BackendHubAccess_1.LockState.None };
383
- const lastCsVal = stmt.getValue(0);
384
- const lock = {
385
- lastCsIndex: lastCsVal.isNull ? undefined : lastCsVal.getInteger(),
386
- state: stmt.getValueInteger(1),
387
- };
388
- switch (lock.state) {
389
- case BackendHubAccess_1.LockState.None:
390
- return lock;
391
- case BackendHubAccess_1.LockState.Exclusive:
392
- return { ...lock, briefcaseId: stmt.getValueInteger(2) };
393
- case BackendHubAccess_1.LockState.Shared:
394
- return { ...lock, sharedBy: this.querySharedLockHolders(elementId) };
395
- default:
396
- throw new Error("illegal lock state");
397
- }
398
- });
399
- }
400
- reserveLock(currStatus, props, briefcase) {
401
- if (props.state === BackendHubAccess_1.LockState.Exclusive && currStatus.lastCsIndex && (currStatus.lastCsIndex > this.getIndexFromChangeset(briefcase.changeset)))
402
- throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.PullIsRequired, "pull is required to obtain lock");
403
- const wantShared = props.state === BackendHubAccess_1.LockState.Shared;
404
- if (wantShared && (currStatus.state === BackendHubAccess_1.LockState.Exclusive))
405
- throw new Error("cannot acquire shared lock because an exclusive lock is already held");
406
- this.db.withPreparedSqliteStatement("INSERT INTO locks(id,level,briefcaseId) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET briefcaseId=excluded.briefcaseId,level=excluded.level", (stmt) => {
407
- stmt.bindId(1, props.id);
408
- stmt.bindInteger(2, props.state);
409
- stmt.bindValue(3, wantShared ? undefined : briefcase.briefcaseId);
410
- const rc = stmt.step();
411
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
412
- throw new core_common_1.IModelError(rc, "cannot insert lock");
413
- });
414
- if (wantShared) {
415
- this.db.withPreparedSqliteStatement("INSERT INTO sharedLocks(lockId,briefcaseId) VALUES(?,?)", (stmt) => {
416
- stmt.bindId(1, props.id);
417
- stmt.bindInteger(2, briefcase.briefcaseId);
418
- const rc = stmt.step();
419
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
420
- throw new core_common_1.IModelError(rc, "cannot insert shared lock");
421
- });
422
- }
423
- }
424
- clearLock(id) {
425
- this.db.withPreparedSqliteStatement("UPDATE locks SET level=0,briefcaseId=NULL WHERE id=?", (stmt) => {
426
- stmt.bindId(1, id);
427
- const rc = stmt.step();
428
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
429
- throw new core_common_1.IModelError(rc, "can't release lock");
430
- });
431
- }
432
- updateLockChangeset(id, index) {
433
- if (index <= 0)
434
- return;
435
- this.db.withPreparedSqliteStatement("UPDATE locks SET lastCSetIndex=? WHERE id=?", (stmt) => {
436
- stmt.bindInteger(1, index);
437
- stmt.bindId(2, id);
438
- const rc = stmt.step();
439
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
440
- throw new core_common_1.IModelError(rc, "can't update lock changeSetId");
441
- });
442
- }
443
- requestLock(props, briefcase) {
444
- if (props.state === BackendHubAccess_1.LockState.None)
445
- throw new Error("cannot request lock for LockState.None");
446
- this.getBriefcase(briefcase.briefcaseId); // throws if briefcaseId invalid.
447
- const lockStatus = this.queryLockStatus(props.id);
448
- switch (lockStatus.state) {
449
- case BackendHubAccess_1.LockState.None:
450
- return this.reserveLock(lockStatus, props, briefcase);
451
- case BackendHubAccess_1.LockState.Shared:
452
- if (props.state === BackendHubAccess_1.LockState.Shared) {
453
- if (!lockStatus.sharedBy.has(briefcase.briefcaseId))
454
- this.reserveLock(lockStatus, props, briefcase);
455
- }
456
- else {
457
- // if requester is the only one holding a shared lock, "upgrade" the lock from shared to exclusive
458
- if (lockStatus.sharedBy.size > 1 || !lockStatus.sharedBy.has(briefcase.briefcaseId)) {
459
- const id = lockStatus.sharedBy.values().next().value;
460
- throw new BackendHubAccess_1.LockConflict(id, this.getBriefcase(id).alias, "shared lock is held");
461
- }
462
- this.removeSharedLock(props.id, briefcase.briefcaseId);
463
- this.reserveLock(this.queryLockStatus(props.id), props, briefcase);
464
- }
465
- return;
466
- case BackendHubAccess_1.LockState.Exclusive:
467
- if (lockStatus.briefcaseId !== briefcase.briefcaseId)
468
- throw new BackendHubAccess_1.LockConflict(lockStatus.briefcaseId, this.getBriefcase(lockStatus.briefcaseId).alias, "exclusive lock is already held");
469
- }
470
- }
471
- removeSharedLock(lockId, briefcaseId) {
472
- this.db.withPreparedSqliteStatement("DELETE FROM sharedLocks WHERE lockId=? AND briefcaseId=?", (stmt) => {
473
- stmt.bindId(1, lockId);
474
- stmt.bindInteger(2, briefcaseId);
475
- const rc = stmt.step();
476
- if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
477
- throw new core_common_1.IModelError(rc, "can't remove shared lock");
478
- });
479
- }
480
- releaseLock(props, arg) {
481
- const lockId = props.id;
482
- const lockStatus = this.queryLockStatus(lockId);
483
- switch (lockStatus.state) {
484
- case BackendHubAccess_1.LockState.None:
485
- throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockDoesNotExist, "lock not held");
486
- case BackendHubAccess_1.LockState.Exclusive:
487
- if (lockStatus.briefcaseId !== arg.briefcaseId)
488
- throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockOwnedByAnotherBriefcase, "lock not held by this briefcase");
489
- this.updateLockChangeset(lockId, arg.changesetIndex);
490
- this.clearLock(lockId);
491
- break;
492
- case BackendHubAccess_1.LockState.Shared:
493
- if (!lockStatus.sharedBy.has(arg.briefcaseId))
494
- throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockDoesNotExist, "shared lock not held by this briefcase");
495
- this.removeSharedLock(lockId, arg.briefcaseId);
496
- if (lockStatus.sharedBy.size === 1)
497
- this.clearLock(lockId);
498
- }
499
- }
500
- /** Acquire a set of locks. If any lock cannot be acquired, no locks are acquired */
501
- acquireLocks(locks, briefcase) {
502
- try {
503
- for (const lock of locks)
504
- this.requestLock({ id: lock[0], state: lock[1] }, briefcase);
505
- this.db.saveChanges(); // only after all locks have been acquired
506
- }
507
- catch (err) {
508
- this.db.abandonChanges(); // abandon all locks that may have been acquired
509
- throw err;
510
- }
511
- }
512
- acquireLock(props, briefcase) {
513
- const locks = new Map();
514
- locks.set(props.id, props.state);
515
- this.acquireLocks(locks, briefcase);
516
- }
517
- releaseLocks(locks, arg) {
518
- for (const props of locks)
519
- this.releaseLock(props, arg);
520
- this.db.saveChanges();
521
- }
522
- releaseAllLocks(arg) {
523
- const locks = this.queryAllLocks(arg.briefcaseId);
524
- this.releaseLocks(locks, arg);
525
- }
526
- countTable(tableName) {
527
- return this.db.withSqliteStatement(`SELECT count(*) from ${tableName}`, (stmt) => {
528
- stmt.step();
529
- return stmt.getValueInteger(0);
530
- });
531
- }
532
- // for debugging
533
- countSharedLocks() { return this.countTable("sharedLocks"); }
534
- // for debugging
535
- countLocks() { return this.countTable("locks"); }
536
- // for debugging
537
- queryAllSharedLocks() {
538
- const locks = [];
539
- this.db.withPreparedSqliteStatement("SELECT lockId,briefcaseId FROM sharedLocks", (stmt) => {
540
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
541
- locks.push({ id: stmt.getValueId(0), briefcaseId: stmt.getValueInteger(1) });
542
- });
543
- return locks;
544
- }
545
- // for debugging
546
- queryLocks() {
547
- const locks = [];
548
- this.db.withPreparedSqliteStatement("SELECT id,level,lastCSetIndex,briefcaseId FROM locks", (stmt) => {
549
- while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
550
- locks.push({
551
- id: stmt.getValueId(0),
552
- level: stmt.getValueInteger(1),
553
- lastCsIndex: stmt.getValue(2).isNull ? undefined : stmt.getValueInteger(2),
554
- briefcaseId: stmt.getValue(3).isNull ? undefined : stmt.getValueInteger(3),
555
- });
556
- });
557
- return locks;
558
- }
559
- removeDir(dirName) {
560
- if (IModelJsFs_1.IModelJsFs.existsSync(dirName)) {
561
- IModelJsFs_1.IModelJsFs.purgeDirSync(dirName);
562
- IModelJsFs_1.IModelJsFs.rmdirSync(dirName);
563
- }
564
- }
565
- cleanup() {
566
- if (this._hubDb) {
567
- this._hubDb.closeDb();
568
- this._hubDb = undefined;
569
- }
570
- try {
571
- this.removeDir(BriefcaseManager_1.BriefcaseManager.getIModelPath(this.iModelId));
572
- this.removeDir(this.rootDir);
573
- }
574
- catch (err) {
575
- // eslint-disable-next-line no-console
576
- console.log(`ERROR: test left an iModel open for [${this.iModelName}]. LocalMock cannot clean up - make sure you call imodel.close() in your test`);
577
- }
578
- }
579
- }
580
- exports.LocalHub = LocalHub;
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
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.LocalHub = void 0;
8
+ const path_1 = require("path");
9
+ const core_bentley_1 = require("@itwin/core-bentley");
10
+ const core_common_1 = require("@itwin/core-common");
11
+ const BackendHubAccess_1 = require("./BackendHubAccess");
12
+ const BriefcaseManager_1 = require("./BriefcaseManager");
13
+ const IModelDb_1 = require("./IModelDb");
14
+ const IModelJsFs_1 = require("./IModelJsFs");
15
+ const SQLiteDb_1 = require("./SQLiteDb");
16
+ /**
17
+ * A "local" mock for IModelHub to provide access to a single iModel. Used by HubMock.
18
+ * @internal
19
+ */
20
+ class LocalHub {
21
+ constructor(rootDir, arg) {
22
+ this.rootDir = rootDir;
23
+ this._nextBriefcaseId = core_common_1.BriefcaseIdValue.FirstValid;
24
+ this._latestChangesetIndex = 0;
25
+ this.iTwinId = arg.iTwinId;
26
+ this.iModelId = arg.iModelId;
27
+ this.iModelName = arg.iModelName;
28
+ this.description = arg.description;
29
+ this.cleanup();
30
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(this.rootDir);
31
+ IModelJsFs_1.IModelJsFs.mkdirSync(this.changesetDir);
32
+ IModelJsFs_1.IModelJsFs.mkdirSync(this.checkpointDir);
33
+ const db = this._hubDb = new SQLiteDb_1.SQLiteDb();
34
+ db.createDb(this.mockDbName);
35
+ db.executeSQL("CREATE TABLE briefcases(id INTEGER PRIMARY KEY NOT NULL,user TEXT NOT NULL,alias TEXT NOT NULL,assigned INTEGER DEFAULT 1)");
36
+ db.executeSQL("CREATE TABLE timeline(csIndex INTEGER PRIMARY KEY NOT NULL,csId TEXT NOT NULL UNIQUE,description TEXT,user TEXT,size BIGINT,type INTEGER,pushDate TEXT,briefcaseId INTEGER,\
37
+ FOREIGN KEY(briefcaseId) REFERENCES briefcases(id))");
38
+ db.executeSQL("CREATE TABLE checkpoints(csIndex INTEGER PRIMARY KEY NOT NULL)");
39
+ db.executeSQL("CREATE TABLE versions(name TEXT PRIMARY KEY NOT NULL,csIndex TEXT,FOREIGN KEY(csIndex) REFERENCES timeline(csIndex))");
40
+ db.executeSQL("CREATE TABLE locks(id INTEGER PRIMARY KEY NOT NULL,level INTEGER NOT NULL,lastCSetIndex INTEGER,briefcaseId INTEGER)");
41
+ db.executeSQL("CREATE TABLE sharedLocks(lockId INTEGER NOT NULL,briefcaseId INTEGER NOT NULL,PRIMARY KEY(lockId,briefcaseId))");
42
+ db.executeSQL("CREATE INDEX LockIdx ON locks(briefcaseId)");
43
+ db.executeSQL("CREATE INDEX SharedLockIdx ON sharedLocks(briefcaseId)");
44
+ db.saveChanges();
45
+ const version0Root = `${rootDir}_version0`;
46
+ const version0 = arg.version0 ?? (0, path_1.join)(version0Root, "version0.bim");
47
+ if (!arg.version0) { // if they didn't supply a version0 file, create a blank one.
48
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(version0Root);
49
+ IModelJsFs_1.IModelJsFs.removeSync(version0);
50
+ IModelDb_1.SnapshotDb.createEmpty(version0, { rootSubject: { name: arg.description ?? arg.iModelName } }).close();
51
+ }
52
+ const path = this.uploadCheckpoint({ changesetIndex: 0, localFile: version0 });
53
+ if (!arg.version0)
54
+ IModelJsFs_1.IModelJsFs.removeSync(version0);
55
+ const nativeDb = IModelDb_1.IModelDb.openDgnDb({ path }, core_bentley_1.OpenMode.ReadWrite);
56
+ try {
57
+ nativeDb.setITwinId(this.iTwinId);
58
+ nativeDb.setIModelId(this.iModelId);
59
+ nativeDb.saveChanges();
60
+ nativeDb.deleteAllTxns(); // necessary before resetting briefcaseId
61
+ nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
62
+ nativeDb.saveLocalValue(IModelDb_1.BriefcaseLocalValue.NoLocking, arg.noLocks ? "true" : undefined);
63
+ nativeDb.saveChanges();
64
+ }
65
+ finally {
66
+ nativeDb.closeIModel();
67
+ }
68
+ }
69
+ get latestChangesetIndex() { return this._latestChangesetIndex; }
70
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
71
+ get db() { return this._hubDb; } // eslint-disable-line @typescript-eslint/naming-convention
72
+ get changesetDir() { return (0, path_1.join)(this.rootDir, "changesets"); }
73
+ get checkpointDir() { return (0, path_1.join)(this.rootDir, "checkpoints"); }
74
+ get mockDbName() { return (0, path_1.join)(this.rootDir, "localHub.db"); }
75
+ /** Acquire the next available briefcaseId and assign it to the supplied user */
76
+ acquireNewBriefcaseId(user, alias) {
77
+ const db = this.db;
78
+ const newId = this._nextBriefcaseId++;
79
+ db.withSqliteStatement("INSERT INTO briefcases(id,user,alias) VALUES (?,?,?)", (stmt) => {
80
+ stmt.bindInteger(1, newId);
81
+ stmt.bindString(2, user);
82
+ stmt.bindString(3, alias ?? `${user} (${newId})`);
83
+ const rc = stmt.step();
84
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
85
+ throw new core_common_1.IModelError(rc, "can't insert briefcaseId in mock database");
86
+ });
87
+ db.saveChanges();
88
+ return newId;
89
+ }
90
+ /** Release a briefcaseId */
91
+ releaseBriefcaseId(id) {
92
+ const db = this.db;
93
+ this.releaseAllLocks({ briefcaseId: id, changesetIndex: 0 });
94
+ db.withSqliteStatement("UPDATE briefcases SET assigned=0 WHERE id=?", (stmt) => {
95
+ stmt.bindInteger(1, id);
96
+ const rc = stmt.step();
97
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
98
+ throw new core_common_1.IModelError(rc, `briefcaseId ${id} was not reserved`);
99
+ });
100
+ db.saveChanges();
101
+ }
102
+ /** Get an array of all of the currently assigned Briefcases */
103
+ getBriefcases(onlyAssigned = true) {
104
+ const briefcases = [];
105
+ let sql = "SELECT id,user,alias,assigned FROM briefcases";
106
+ if (onlyAssigned)
107
+ sql += " WHERE assigned=1";
108
+ this.db.withSqliteStatement(sql, (stmt) => {
109
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step()) {
110
+ briefcases.push({
111
+ id: stmt.getValueInteger(0),
112
+ user: stmt.getValueString(1),
113
+ alias: stmt.getValueString(2),
114
+ assigned: stmt.getValueInteger(3) !== 0,
115
+ });
116
+ }
117
+ });
118
+ return briefcases;
119
+ }
120
+ /** Get an array of all of the currently assigned BriefcaseIds for a user */
121
+ getBriefcaseIds(user) {
122
+ const briefcases = [];
123
+ this.db.withSqliteStatement("SELECT id FROM briefcases WHERE user=? AND assigned=1", (stmt) => {
124
+ stmt.bindString(1, user);
125
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
126
+ briefcases.push(stmt.getValueInteger(0));
127
+ });
128
+ return briefcases;
129
+ }
130
+ getBriefcase(id) {
131
+ return this.db.withSqliteStatement("SELECT user,alias,assigned FROM briefcases WHERE id=?", (stmt) => {
132
+ stmt.bindInteger(1, id);
133
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== stmt.step())
134
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "no briefcase with that id");
135
+ return { id, user: stmt.getValueString(0), alias: stmt.getValueString(1), assigned: stmt.getValueInteger(2) !== 0 };
136
+ });
137
+ }
138
+ getChangesetFileName(index) {
139
+ return (0, path_1.join)(this.changesetDir, `changeset-${index}`);
140
+ }
141
+ /** Add a changeset to the timeline
142
+ * @return the changesetIndex of the added changeset
143
+ */
144
+ addChangeset(changeset) {
145
+ const stats = IModelJsFs_1.IModelJsFs.lstatSync(changeset.pathname);
146
+ if (!stats)
147
+ throw new Error(`cannot read changeset file ${changeset.pathname}`);
148
+ const parentIndex = this.getChangesetById(changeset.parentId).index;
149
+ if (parentIndex !== this.latestChangesetIndex)
150
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidParent, "changeset parent is not latest changeset");
151
+ this.getBriefcase(changeset.briefcaseId); // throws if invalid id
152
+ const db = this.db;
153
+ changeset.index = this._latestChangesetIndex + 1;
154
+ db.withSqliteStatement("INSERT INTO timeline(csIndex,csId,description,size,type,pushDate,user,briefcaseId) VALUES (?,?,?,?,?,?,?,?)", (stmt) => {
155
+ stmt.bindInteger(1, changeset.index);
156
+ stmt.bindString(2, changeset.id);
157
+ stmt.bindString(3, changeset.description);
158
+ stmt.bindInteger(4, stats.size);
159
+ stmt.bindInteger(5, changeset.changesType ?? 0);
160
+ stmt.bindString(6, changeset.pushDate ?? new Date().toISOString());
161
+ stmt.bindString(7, changeset.userCreated ?? "");
162
+ stmt.bindInteger(8, changeset.briefcaseId);
163
+ const rc = stmt.step();
164
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
165
+ throw new core_common_1.IModelError(rc, "can't insert changeset into mock db");
166
+ });
167
+ this._latestChangesetIndex = changeset.index; // only change this after insert succeeds
168
+ db.saveChanges();
169
+ IModelJsFs_1.IModelJsFs.copySync(changeset.pathname, this.getChangesetFileName(changeset.index));
170
+ return changeset.index;
171
+ }
172
+ getIndexFromChangeset(changeset) {
173
+ return changeset.index ?? this.getChangesetIndex(changeset.id);
174
+ }
175
+ /** Get the index of a changeset by its Id */
176
+ getChangesetIndex(id) {
177
+ if (id === "")
178
+ return 0;
179
+ return this.db.withPreparedSqliteStatement("SELECT csIndex FROM timeline WHERE csId=?", (stmt) => {
180
+ stmt.bindString(1, id);
181
+ const rc = stmt.step();
182
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
183
+ throw new core_common_1.IModelError(rc, `changeset ${id} not found`);
184
+ return stmt.getValueInteger(0);
185
+ });
186
+ }
187
+ /** Get the properties of a changeset by its Id */
188
+ getChangesetById(id) {
189
+ return this.getChangesetByIndex(this.getChangesetIndex(id));
190
+ }
191
+ getPreviousIndex(index) {
192
+ return this.db.withPreparedSqliteStatement("SELECT max(csIndex) FROM timeline WHERE csIndex<?", (stmt) => {
193
+ stmt.bindInteger(1, index);
194
+ const rc = stmt.step();
195
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
196
+ throw new core_common_1.IModelError(rc, `cannot get previous index`);
197
+ return stmt.getValueInteger(0);
198
+ });
199
+ }
200
+ getParentId(index) {
201
+ if (index === 0)
202
+ return "";
203
+ return this.db.withPreparedSqliteStatement("SELECT csId FROM timeline WHERE csIndex=?", (stmt) => {
204
+ stmt.bindInteger(1, this.getPreviousIndex(index));
205
+ stmt.step();
206
+ return stmt.getValueString(0);
207
+ });
208
+ }
209
+ /** Get the properties of a changeset by its index */
210
+ getChangesetByIndex(index) {
211
+ if (index <= 0)
212
+ return { id: "", changesType: 0, description: "version0", parentId: "", briefcaseId: 0, pushDate: "", userCreated: "", index: 0 };
213
+ return this.db.withPreparedSqliteStatement("SELECT description,size,type,pushDate,user,csId,briefcaseId FROM timeline WHERE csIndex=?", (stmt) => {
214
+ stmt.bindInteger(1, index);
215
+ const rc = stmt.step();
216
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
217
+ throw new core_common_1.IModelError(rc, `changeset at index ${index} not found`);
218
+ return {
219
+ description: stmt.getValueString(0),
220
+ size: stmt.getValueDouble(1),
221
+ changesType: stmt.getValueInteger(2),
222
+ pushDate: stmt.getValueString(3),
223
+ userCreated: stmt.getValueString(4),
224
+ id: stmt.getValueString(5),
225
+ briefcaseId: stmt.getValueInteger(6),
226
+ index,
227
+ parentId: this.getParentId(index),
228
+ };
229
+ });
230
+ }
231
+ getLatestChangeset() {
232
+ return this.getChangesetByIndex(this.latestChangesetIndex);
233
+ }
234
+ getChangesetId(index) {
235
+ return this.getChangesetByIndex(index).id;
236
+ }
237
+ /** Get an array of changesets starting with first to last, by index */
238
+ queryChangesets(range) {
239
+ const changesets = [];
240
+ const first = range?.first ?? 0;
241
+ const last = range?.end ?? this.latestChangesetIndex;
242
+ this.db.withPreparedSqliteStatement("SELECT csIndex FROM timeline WHERE csIndex>=? AND csIndex<=? ORDER BY csIndex", (stmt) => {
243
+ stmt.bindInteger(1, first);
244
+ stmt.bindInteger(2, last);
245
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
246
+ changesets.push(this.getChangesetByIndex(stmt.getValueInteger(0)));
247
+ });
248
+ return changesets;
249
+ }
250
+ /** Name a version */
251
+ addNamedVersion(arg) {
252
+ const db = this.db;
253
+ db.withSqliteStatement("INSERT INTO versions(name,csIndex) VALUES (?,?)", (stmt) => {
254
+ stmt.bindString(1, arg.versionName);
255
+ stmt.bindInteger(2, arg.csIndex);
256
+ const rc = stmt.step();
257
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
258
+ throw new core_common_1.IModelError(rc, "can't insert named version");
259
+ });
260
+ db.saveChanges();
261
+ }
262
+ /** Delete a named version */
263
+ deleteNamedVersion(versionName) {
264
+ const db = this.db;
265
+ db.withSqliteStatement("DELETE FROM versions WHERE name=?", (stmt) => {
266
+ stmt.bindString(1, versionName);
267
+ const rc = stmt.step();
268
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== rc)
269
+ throw new core_common_1.IModelError(rc, "can't delete named version");
270
+ });
271
+ db.saveChanges();
272
+ }
273
+ /** find the changeset for a named version */
274
+ findNamedVersion(versionName) {
275
+ const index = this.db.withSqliteStatement("SELECT csIndex FROM versions WHERE name=?", (stmt) => {
276
+ stmt.bindString(1, versionName);
277
+ const rc = stmt.step();
278
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
279
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `Named version ${versionName} not found`);
280
+ return stmt.getValueInteger(0);
281
+ });
282
+ return this.getChangesetByIndex(index);
283
+ }
284
+ checkpointNameFromIndex(csIndex) {
285
+ return `checkpoint-${csIndex}`;
286
+ }
287
+ /** "upload" a checkpoint */
288
+ uploadCheckpoint(arg) {
289
+ const db = this.db;
290
+ db.withSqliteStatement("INSERT INTO checkpoints(csIndex) VALUES (?)", (stmt) => {
291
+ stmt.bindInteger(1, arg.changesetIndex);
292
+ const res = stmt.step();
293
+ if (core_bentley_1.DbResult.BE_SQLITE_DONE !== res)
294
+ throw new core_common_1.IModelError(res, "can't insert checkpoint into mock db");
295
+ });
296
+ db.saveChanges();
297
+ const outName = (0, path_1.join)(this.checkpointDir, this.checkpointNameFromIndex(arg.changesetIndex));
298
+ IModelJsFs_1.IModelJsFs.copySync(arg.localFile, outName);
299
+ return outName;
300
+ }
301
+ /** Get an array of the indexes for a range of checkpoints */
302
+ getCheckpoints(range) {
303
+ const first = range?.first ?? 0;
304
+ const last = range?.end ?? this.latestChangesetIndex;
305
+ const checkpoints = [];
306
+ this.db.withSqliteStatement("SELECT csIndex FROM checkpoints WHERE csIndex>=? AND csIndex<=? ORDER BY csIndex", (stmt) => {
307
+ stmt.bindInteger(1, first);
308
+ stmt.bindInteger(2, last);
309
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
310
+ checkpoints.push(stmt.getValueInteger(0));
311
+ });
312
+ return checkpoints;
313
+ }
314
+ /** Find the checkpoint that is no newer than a changesetIndex */
315
+ queryPreviousCheckpoint(changesetIndex) {
316
+ if (changesetIndex <= 0)
317
+ return 0;
318
+ return this.db.withSqliteStatement("SELECT max(csIndex) FROM checkpoints WHERE csIndex <= ? ", (stmt) => {
319
+ stmt.bindInteger(1, changesetIndex);
320
+ const res = stmt.step();
321
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== res)
322
+ throw new core_common_1.IModelError(res, "can't get previous checkpoint");
323
+ return stmt.getValueInteger(0);
324
+ });
325
+ }
326
+ /** "download" a checkpoint */
327
+ downloadCheckpoint(arg) {
328
+ const index = this.getIndexFromChangeset(arg.changeset);
329
+ const prev = this.queryPreviousCheckpoint(index);
330
+ IModelJsFs_1.IModelJsFs.copySync((0, path_1.join)(this.checkpointDir, this.checkpointNameFromIndex(prev)), arg.targetFile);
331
+ const changeset = this.getChangesetByIndex(index);
332
+ return { index, id: changeset.id };
333
+ }
334
+ copyChangeset(arg) {
335
+ IModelJsFs_1.IModelJsFs.copySync(this.getChangesetFileName(arg.index), arg.pathname);
336
+ return arg;
337
+ }
338
+ /** "download" a changeset */
339
+ downloadChangeset(arg) {
340
+ const cs = this.getChangesetByIndex(arg.index);
341
+ const csProps = { ...cs, pathname: (0, path_1.join)(arg.targetDir, cs.id), index: arg.index };
342
+ return this.copyChangeset(csProps);
343
+ }
344
+ /** "download" all the changesets in a given range */
345
+ downloadChangesets(arg) {
346
+ const cSets = this.queryChangesets(arg.range);
347
+ for (const cs of cSets) {
348
+ cs.pathname = (0, path_1.join)(arg.targetDir, cs.id);
349
+ this.copyChangeset(cs);
350
+ }
351
+ return cSets;
352
+ }
353
+ querySharedLockHolders(elementId) {
354
+ return this.db.withPreparedSqliteStatement("SELECT briefcaseId FROM sharedLocks WHERE lockId=?", (stmt) => {
355
+ stmt.bindId(1, elementId);
356
+ const briefcases = new Set();
357
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
358
+ briefcases.add(stmt.getValueInteger(0));
359
+ return briefcases;
360
+ });
361
+ }
362
+ queryAllLocks(briefcaseId) {
363
+ this.getBriefcase(briefcaseId); // throws if briefcaseId invalid.
364
+ const locks = [];
365
+ this.db.withPreparedSqliteStatement("SELECT id FROM locks WHERE briefcaseId=?", (stmt) => {
366
+ stmt.bindInteger(1, briefcaseId);
367
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
368
+ locks.push({ id: stmt.getValueId(0), state: BackendHubAccess_1.LockState.Exclusive });
369
+ });
370
+ this.db.withPreparedSqliteStatement("SELECT lockId FROM sharedLocks WHERE briefcaseId=?", (stmt) => {
371
+ stmt.bindInteger(1, briefcaseId);
372
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
373
+ locks.push({ id: stmt.getValueId(0), state: BackendHubAccess_1.LockState.Shared });
374
+ });
375
+ return locks;
376
+ }
377
+ queryLockStatus(elementId) {
378
+ return this.db.withPreparedSqliteStatement("SELECT lastCSetIndex,level,briefcaseId FROM locks WHERE id=?", (stmt) => {
379
+ stmt.bindId(1, elementId);
380
+ const rc = stmt.step();
381
+ if (core_bentley_1.DbResult.BE_SQLITE_ROW !== rc)
382
+ return { state: BackendHubAccess_1.LockState.None };
383
+ const lastCsVal = stmt.getValue(0);
384
+ const lock = {
385
+ lastCsIndex: lastCsVal.isNull ? undefined : lastCsVal.getInteger(),
386
+ state: stmt.getValueInteger(1),
387
+ };
388
+ switch (lock.state) {
389
+ case BackendHubAccess_1.LockState.None:
390
+ return lock;
391
+ case BackendHubAccess_1.LockState.Exclusive:
392
+ return { ...lock, briefcaseId: stmt.getValueInteger(2) };
393
+ case BackendHubAccess_1.LockState.Shared:
394
+ return { ...lock, sharedBy: this.querySharedLockHolders(elementId) };
395
+ default:
396
+ throw new Error("illegal lock state");
397
+ }
398
+ });
399
+ }
400
+ reserveLock(currStatus, props, briefcase) {
401
+ if (props.state === BackendHubAccess_1.LockState.Exclusive && currStatus.lastCsIndex && (currStatus.lastCsIndex > this.getIndexFromChangeset(briefcase.changeset)))
402
+ throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.PullIsRequired, "pull is required to obtain lock");
403
+ const wantShared = props.state === BackendHubAccess_1.LockState.Shared;
404
+ if (wantShared && (currStatus.state === BackendHubAccess_1.LockState.Exclusive))
405
+ throw new Error("cannot acquire shared lock because an exclusive lock is already held");
406
+ this.db.withPreparedSqliteStatement("INSERT INTO locks(id,level,briefcaseId) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET briefcaseId=excluded.briefcaseId,level=excluded.level", (stmt) => {
407
+ stmt.bindId(1, props.id);
408
+ stmt.bindInteger(2, props.state);
409
+ stmt.bindValue(3, wantShared ? undefined : briefcase.briefcaseId);
410
+ const rc = stmt.step();
411
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
412
+ throw new core_common_1.IModelError(rc, "cannot insert lock");
413
+ });
414
+ if (wantShared) {
415
+ this.db.withPreparedSqliteStatement("INSERT INTO sharedLocks(lockId,briefcaseId) VALUES(?,?)", (stmt) => {
416
+ stmt.bindId(1, props.id);
417
+ stmt.bindInteger(2, briefcase.briefcaseId);
418
+ const rc = stmt.step();
419
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
420
+ throw new core_common_1.IModelError(rc, "cannot insert shared lock");
421
+ });
422
+ }
423
+ }
424
+ clearLock(id) {
425
+ this.db.withPreparedSqliteStatement("UPDATE locks SET level=0,briefcaseId=NULL WHERE id=?", (stmt) => {
426
+ stmt.bindId(1, id);
427
+ const rc = stmt.step();
428
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
429
+ throw new core_common_1.IModelError(rc, "can't release lock");
430
+ });
431
+ }
432
+ updateLockChangeset(id, index) {
433
+ if (index <= 0)
434
+ return;
435
+ this.db.withPreparedSqliteStatement("UPDATE locks SET lastCSetIndex=? WHERE id=?", (stmt) => {
436
+ stmt.bindInteger(1, index);
437
+ stmt.bindId(2, id);
438
+ const rc = stmt.step();
439
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
440
+ throw new core_common_1.IModelError(rc, "can't update lock changeSetId");
441
+ });
442
+ }
443
+ requestLock(props, briefcase) {
444
+ if (props.state === BackendHubAccess_1.LockState.None)
445
+ throw new Error("cannot request lock for LockState.None");
446
+ this.getBriefcase(briefcase.briefcaseId); // throws if briefcaseId invalid.
447
+ const lockStatus = this.queryLockStatus(props.id);
448
+ switch (lockStatus.state) {
449
+ case BackendHubAccess_1.LockState.None:
450
+ return this.reserveLock(lockStatus, props, briefcase);
451
+ case BackendHubAccess_1.LockState.Shared:
452
+ if (props.state === BackendHubAccess_1.LockState.Shared) {
453
+ if (!lockStatus.sharedBy.has(briefcase.briefcaseId))
454
+ this.reserveLock(lockStatus, props, briefcase);
455
+ }
456
+ else {
457
+ // if requester is the only one holding a shared lock, "upgrade" the lock from shared to exclusive
458
+ if (lockStatus.sharedBy.size > 1 || !lockStatus.sharedBy.has(briefcase.briefcaseId)) {
459
+ const id = lockStatus.sharedBy.values().next().value;
460
+ throw new BackendHubAccess_1.LockConflict(id, this.getBriefcase(id).alias, "shared lock is held");
461
+ }
462
+ this.removeSharedLock(props.id, briefcase.briefcaseId);
463
+ this.reserveLock(this.queryLockStatus(props.id), props, briefcase);
464
+ }
465
+ return;
466
+ case BackendHubAccess_1.LockState.Exclusive:
467
+ if (lockStatus.briefcaseId !== briefcase.briefcaseId)
468
+ throw new BackendHubAccess_1.LockConflict(lockStatus.briefcaseId, this.getBriefcase(lockStatus.briefcaseId).alias, "exclusive lock is already held");
469
+ }
470
+ }
471
+ removeSharedLock(lockId, briefcaseId) {
472
+ this.db.withPreparedSqliteStatement("DELETE FROM sharedLocks WHERE lockId=? AND briefcaseId=?", (stmt) => {
473
+ stmt.bindId(1, lockId);
474
+ stmt.bindInteger(2, briefcaseId);
475
+ const rc = stmt.step();
476
+ if (rc !== core_bentley_1.DbResult.BE_SQLITE_DONE)
477
+ throw new core_common_1.IModelError(rc, "can't remove shared lock");
478
+ });
479
+ }
480
+ releaseLock(props, arg) {
481
+ const lockId = props.id;
482
+ const lockStatus = this.queryLockStatus(lockId);
483
+ switch (lockStatus.state) {
484
+ case BackendHubAccess_1.LockState.None:
485
+ throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockDoesNotExist, "lock not held");
486
+ case BackendHubAccess_1.LockState.Exclusive:
487
+ if (lockStatus.briefcaseId !== arg.briefcaseId)
488
+ throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockOwnedByAnotherBriefcase, "lock not held by this briefcase");
489
+ this.updateLockChangeset(lockId, arg.changesetIndex);
490
+ this.clearLock(lockId);
491
+ break;
492
+ case BackendHubAccess_1.LockState.Shared:
493
+ if (!lockStatus.sharedBy.has(arg.briefcaseId))
494
+ throw new core_common_1.IModelError(core_bentley_1.IModelHubStatus.LockDoesNotExist, "shared lock not held by this briefcase");
495
+ this.removeSharedLock(lockId, arg.briefcaseId);
496
+ if (lockStatus.sharedBy.size === 1)
497
+ this.clearLock(lockId);
498
+ }
499
+ }
500
+ /** Acquire a set of locks. If any lock cannot be acquired, no locks are acquired */
501
+ acquireLocks(locks, briefcase) {
502
+ try {
503
+ for (const lock of locks)
504
+ this.requestLock({ id: lock[0], state: lock[1] }, briefcase);
505
+ this.db.saveChanges(); // only after all locks have been acquired
506
+ }
507
+ catch (err) {
508
+ this.db.abandonChanges(); // abandon all locks that may have been acquired
509
+ throw err;
510
+ }
511
+ }
512
+ acquireLock(props, briefcase) {
513
+ const locks = new Map();
514
+ locks.set(props.id, props.state);
515
+ this.acquireLocks(locks, briefcase);
516
+ }
517
+ releaseLocks(locks, arg) {
518
+ for (const props of locks)
519
+ this.releaseLock(props, arg);
520
+ this.db.saveChanges();
521
+ }
522
+ releaseAllLocks(arg) {
523
+ const locks = this.queryAllLocks(arg.briefcaseId);
524
+ this.releaseLocks(locks, arg);
525
+ }
526
+ countTable(tableName) {
527
+ return this.db.withSqliteStatement(`SELECT count(*) from ${tableName}`, (stmt) => {
528
+ stmt.step();
529
+ return stmt.getValueInteger(0);
530
+ });
531
+ }
532
+ // for debugging
533
+ countSharedLocks() { return this.countTable("sharedLocks"); }
534
+ // for debugging
535
+ countLocks() { return this.countTable("locks"); }
536
+ // for debugging
537
+ queryAllSharedLocks() {
538
+ const locks = [];
539
+ this.db.withPreparedSqliteStatement("SELECT lockId,briefcaseId FROM sharedLocks", (stmt) => {
540
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
541
+ locks.push({ id: stmt.getValueId(0), briefcaseId: stmt.getValueInteger(1) });
542
+ });
543
+ return locks;
544
+ }
545
+ // for debugging
546
+ queryLocks() {
547
+ const locks = [];
548
+ this.db.withPreparedSqliteStatement("SELECT id,level,lastCSetIndex,briefcaseId FROM locks", (stmt) => {
549
+ while (core_bentley_1.DbResult.BE_SQLITE_ROW === stmt.step())
550
+ locks.push({
551
+ id: stmt.getValueId(0),
552
+ level: stmt.getValueInteger(1),
553
+ lastCsIndex: stmt.getValue(2).isNull ? undefined : stmt.getValueInteger(2),
554
+ briefcaseId: stmt.getValue(3).isNull ? undefined : stmt.getValueInteger(3),
555
+ });
556
+ });
557
+ return locks;
558
+ }
559
+ removeDir(dirName) {
560
+ if (IModelJsFs_1.IModelJsFs.existsSync(dirName)) {
561
+ IModelJsFs_1.IModelJsFs.purgeDirSync(dirName);
562
+ IModelJsFs_1.IModelJsFs.rmdirSync(dirName);
563
+ }
564
+ }
565
+ cleanup() {
566
+ if (this._hubDb) {
567
+ this._hubDb.closeDb();
568
+ this._hubDb = undefined;
569
+ }
570
+ try {
571
+ this.removeDir(BriefcaseManager_1.BriefcaseManager.getIModelPath(this.iModelId));
572
+ this.removeDir(this.rootDir);
573
+ }
574
+ catch (err) {
575
+ // eslint-disable-next-line no-console
576
+ console.log(`ERROR: test left an iModel open for [${this.iModelName}]. LocalMock cannot clean up - make sure you call imodel.close() in your test`);
577
+ }
578
+ }
579
+ }
580
+ exports.LocalHub = LocalHub;
581
581
  //# sourceMappingURL=LocalHub.js.map