@itwin/core-backend 3.4.0-dev.56 → 3.4.0-dev.58

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