/
IModelDb.ts
1899 lines (1672 loc) · 89.9 KB
/
IModelDb.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------------------------------------------*/
/** @module iModels */
import {
ClientRequestContext, BeEvent, BentleyStatus, DbResult, AuthStatus, Guid, GuidString, Id64, Id64Arg, Id64Set,
Id64String, JsonUtils, Logger, OpenMode, PerfLogger, BeDuration,
} from "@bentley/bentleyjs-core";
import { AuthorizedClientRequestContext, UlasClient, UsageLogEntry, UsageType } from "@bentley/imodeljs-clients";
import {
AxisAlignedBox3d, CategorySelectorProps, Code, CodeSpec, CreateIModelProps, DisplayStyleProps, EcefLocation, ElementAspectProps,
ElementLoadProps, ElementProps, EntityMetaData, EntityProps, EntityQueryParams, FilePropertyProps, FontMap, FontMapProps, FontProps,
IModel, IModelError, IModelNotFoundResponse, IModelProps, IModelStatus, IModelToken, IModelVersion, ModelProps, ModelSelectorProps,
PropertyCallback, SheetProps, SnapRequestProps, SnapResponseProps, ThumbnailProps, TileTreeProps, ViewDefinitionProps, ViewQueryParams,
ViewStateProps, IModelCoordinatesResponseProps, GeoCoordinatesResponseProps, QueryResponseStatus, QueryResponse, QueryPriority, QueryLimit, QueryQuota, RpcPendingResponse,
} from "@bentley/imodeljs-common";
import * as path from "path";
import * as os from "os";
import { BriefcaseEntry, BriefcaseId, BriefcaseManager, KeepBriefcase } from "./BriefcaseManager";
import { ClassRegistry, MetaDataRegistry } from "./ClassRegistry";
import { CodeSpecs } from "./CodeSpecs";
import { ConcurrencyControl } from "./ConcurrencyControl";
import { ECSqlStatement, ECSqlStatementCache } from "./ECSqlStatement";
import { Element, Subject } from "./Element";
import { ElementAspect } from "./ElementAspect";
import { Entity } from "./Entity";
import { ExportGraphicsProps } from "./ExportGraphics";
import { IModelJsFs } from "./IModelJsFs";
import { IModelJsNative } from "./IModelJsNative";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { Model } from "./Model";
import { Relationship, RelationshipProps, Relationships } from "./Relationship";
import { CachedSqliteStatement, SqliteStatement, SqliteStatementCache } from "./SqliteStatement";
import { SheetViewDefinition, ViewDefinition } from "./ViewDefinition";
import { IModelHost } from "./IModelHost";
import { PollStatus, PostStatus } from "./ConcurrentQuery";
const loggerCategory: string = BackendLoggerCategory.IModelDb;
/** A string that identifies a Txn.
* @public
*/
export type TxnIdString = string;
/** The signature of a function that can supply a description of local Txns in the specified briefcase up to and including the specified endTxnId.
* @public
*/
export type ChangeSetDescriber = (endTxnId: TxnIdString) => string;
/** Operations allowed when synchronizing changes between the IModelDb and the iModel Hub
* @public
*/
export enum SyncMode { FixedVersion = 1, PullAndPush = 2 }
/** Parameters to open an IModelDb
* @public
*/
export class OpenParams {
// Constructor
public constructor(
/** Mode to Open the IModelDb */
public readonly openMode: OpenMode,
/** Operations allowed when synchronizing changes between the IModelDb and IModelHub */
public readonly syncMode?: SyncMode,
/** Timeout (in milliseconds) before the open operations throws a RpcPendingResponse exception
* after queuing up the open. If undefined, waits for the open to complete.
*/
public timeout?: number,
) {
this.validate();
}
/** Returns true if the open params open a snapshot Db */
public get isStandalone(): boolean { return this.syncMode === undefined; }
private validate() {
if (this.isStandalone && this.syncMode !== undefined)
throw new IModelError(BentleyStatus.ERROR, "Invalid parameters - only openMode can be defined if opening a standalone Db");
if (this.openMode === OpenMode.Readonly && this.syncMode === SyncMode.PullAndPush) {
throw new IModelError(BentleyStatus.ERROR, "Cannot pull or push changes into/from a ReadOnly IModel");
}
}
/** Create parameters to open the Db as of a fixed version in a readonly mode */
public static fixedVersion(): OpenParams { return new OpenParams(OpenMode.Readonly, SyncMode.FixedVersion); }
/** Create parameters to open the Db to make edits and push changes to the Hub */
public static pullAndPush(): OpenParams { return new OpenParams(OpenMode.ReadWrite, SyncMode.PullAndPush); }
/** Create parameters to open a standalone Db
* @deprecated The confusing concept of *standalone* is being replaced by the more strict concept of a read-only iModel *snapshot*.
*/
public static standalone(openMode: OpenMode) { return new OpenParams(openMode); }
/** Returns true if equal and false otherwise */
public equals(other: OpenParams) {
return other.openMode === this.openMode && other.syncMode === this.syncMode;
}
}
/** An iModel database file. The database file is either a local copy (briefcase) of an iModel managed by iModelHub or a read-only *snapshot* used for archival and data transfer purposes.
*
* IModelDb raises a set of events to allow apps and subsystems to track IModelDb object life cycle, including [[onOpen]] and [[onOpened]].
* @see [learning about IModelDb]($docs/learning/backend/IModelDb.md)
* @public
*/
export class IModelDb extends IModel {
public static readonly defaultLimit = 1000; // default limit for batching queries
public static readonly maxLimit = 10000; // maximum limit for batching queries
/** Event called after a changeset is applied to this IModelDb. */
public readonly onChangesetApplied = new BeEvent<() => void>();
public readonly models = new IModelDb.Models(this);
public readonly elements = new IModelDb.Elements(this);
public readonly views = new IModelDb.Views(this);
public readonly tiles = new IModelDb.Tiles(this);
/** @beta */
public readonly txns = new TxnManager(this);
private _relationships?: Relationships;
private _concurrentQueryInitialized: boolean = false;
private readonly _statementCache = new ECSqlStatementCache();
private readonly _sqliteStatementCache = new SqliteStatementCache();
private _codeSpecs?: CodeSpecs;
private _classMetaDataRegistry?: MetaDataRegistry;
private _concurrency?: ConcurrencyControl;
protected _fontMap?: FontMap;
private readonly _snaps = new Map<string, IModelJsNative.SnapRequest>();
public readFontJson(): string { return this.nativeDb.readFontMap(); }
public get fontMap(): FontMap { return this._fontMap || (this._fontMap = new FontMap(JSON.parse(this.readFontJson()) as FontMapProps)); }
public embedFont(prop: FontProps): FontProps { this._fontMap = undefined; return JSON.parse(this.nativeDb.embedFont(JSON.stringify(prop))) as FontProps; }
/** Get the parameters used to open this iModel */
public readonly openParams: OpenParams;
/** Event raised just before an IModelDb is opened.
*
* **Example:**
* ``` ts
* [[include:IModelDb.onOpen]]
* ```
*/
public static readonly onOpen = new BeEvent<(_requestContext: AuthorizedClientRequestContext, _contextId: string, _iModelId: string, _openParams: OpenParams, _version: IModelVersion) => void>();
/** Event raised just after an IModelDb is opened.
* @note This event is *not* raised for snapshot IModelDbs.
*
* **Example:**
* ``` ts
* [[include:IModelDb.onOpened]]
* ```
*/
public static readonly onOpened = new BeEvent<(_requestContext: AuthorizedClientRequestContext, _imodelDb: IModelDb) => void>();
/** Event raised just before an IModelDb is created in iModelHub. This event is raised only for iModel access initiated by this app only. This event is not raised for snapshot IModelDbs. */
public static readonly onCreate = new BeEvent<(_requestContext: AuthorizedClientRequestContext, _contextId: string, _args: CreateIModelProps) => void>();
/** Event raised just after an IModelDb is created in iModelHub. This event is raised only for iModel access initiated by this app only. This event is not raised for snapshot IModelDbs. */
public static readonly onCreated = new BeEvent<(_imodelDb: IModelDb) => void>();
private _briefcase?: BriefcaseEntry;
/** @internal */
public get briefcase(): BriefcaseEntry { return this._briefcase!; }
/** Check if this iModel has been opened read-only or not. */
public get isReadonly(): boolean { return this.openParams.openMode === OpenMode.Readonly; }
private constructor(briefcaseEntry: BriefcaseEntry, iModelToken: IModelToken, openParams: OpenParams) {
super(iModelToken);
this.openParams = openParams;
this.setupBriefcaseEntry(briefcaseEntry);
this.initializeIModelDb();
}
private initializeIModelDb() {
const props = JSON.parse(this.nativeDb.getIModelProps()) as IModelProps;
const name = props.rootSubject ? props.rootSubject.name : path.basename(this.briefcase.pathname);
super.initialize(name, props);
}
private static constructIModelDb(briefcaseEntry: BriefcaseEntry, openParams: OpenParams, contextId?: string): IModelDb {
if (briefcaseEntry.iModelDb)
return briefcaseEntry.iModelDb; // If there's an IModelDb already associated with the briefcase, that should be reused.
const iModelToken = new IModelToken(briefcaseEntry.getKey(), contextId, briefcaseEntry.iModelId, briefcaseEntry.currentChangeSetId, openParams.openMode);
return new IModelDb(briefcaseEntry, iModelToken, openParams);
}
/** Create an *empty* local iModel *snapshot* file. Snapshots are disconnected from iModelHub so do not have a change timeline. Snapshots are typically used for archival or data transfer purposes.
* > Note: A *snapshot* cannot be modified after [[closeSnapshot]] is called.
* @param snapshotFile The file that will contain the new iModel *snapshot*
* @param args The parameters that define the new iModel *snapshot*
* @beta
*/
public static createSnapshot(snapshotFile: string, args: CreateIModelProps): IModelDb {
const briefcaseEntry: BriefcaseEntry = BriefcaseManager.createStandalone(snapshotFile, args);
return IModelDb.constructIModelDb(briefcaseEntry, OpenParams.standalone(briefcaseEntry.openParams.openMode));
}
/** Create a local iModel *snapshot* file using this iModel as a *seed* or starting point.
* Snapshots are disconnected from iModelHub so do not have a change timeline. Snapshots are typically used for archival or data transfer purposes.
* > Note: A *snapshot* cannot be modified after [[closeSnapshot]] is called.
* @param snapshotFile The file that will contain the new iModel *snapshot*
* @returns A writeable IModelDb
* @beta
*/
public createSnapshot(snapshotFile: string): IModelDb {
IModelJsFs.copySync(this.briefcase.pathname, snapshotFile);
const briefcaseEntry: BriefcaseEntry = BriefcaseManager.openStandalone(snapshotFile, OpenMode.ReadWrite, false);
const isSeedFileMaster: boolean = BriefcaseId.Master === briefcaseEntry.briefcaseId;
const isSeedFileSnapshot: boolean = BriefcaseId.Snapshot === briefcaseEntry.briefcaseId;
// Replace iModelId if seedFile is a master or snapshot, preserve iModelId if seedFile is an iModelHub-managed briefcase
if ((isSeedFileMaster) || (isSeedFileSnapshot)) {
briefcaseEntry.iModelId = Guid.createValue();
}
briefcaseEntry.briefcaseId = BriefcaseId.Snapshot;
const snapshotDb: IModelDb = IModelDb.constructIModelDb(briefcaseEntry, OpenParams.standalone(OpenMode.ReadWrite)); // WIP: clean up copied file on error?
if (isSeedFileMaster) {
snapshotDb.setGuid(briefcaseEntry.iModelId);
} else {
snapshotDb.setAsMaster(briefcaseEntry.iModelId);
}
snapshotDb.nativeDb.setBriefcaseId(briefcaseEntry.briefcaseId);
return snapshotDb;
}
/** Create an iModel on iModelHub */
public static async create(requestContext: AuthorizedClientRequestContext, contextId: string, iModelName: string, args: CreateIModelProps): Promise<IModelDb> {
requestContext.enter();
IModelDb.onCreate.raiseEvent(requestContext, contextId, args);
const iModelId: string = await BriefcaseManager.create(requestContext, contextId, iModelName, args);
requestContext.enter();
return IModelDb.open(requestContext, contextId, iModelId);
}
/** Open an iModel from a local file.
* @param pathname The pathname of the iModel
* @param openMode Open mode for database
* @param enableTransactions Enable tracking of transactions in this standalone iModel
* @throws [[IModelError]]
* @see [[open]], [[openSnapshot]]
* @deprecated iModelHub manages the change history of an iModel, so writing changes to a local/unmanaged file doesn't make sense. Callers should migrate to [[openSnapshot]] or [[open]] instead.
* @internal
*/
public static openStandalone(pathname: string, openMode: OpenMode = OpenMode.ReadWrite, enableTransactions: boolean = false): IModelDb {
const briefcaseEntry: BriefcaseEntry = BriefcaseManager.openStandalone(pathname, openMode, enableTransactions);
return IModelDb.constructIModelDb(briefcaseEntry, OpenParams.standalone(openMode));
}
/** Open a local iModel *snapshot*. Once created, *snapshots* are read-only and are typically used for archival or data transfer purposes.
* @see [[open]]
* @throws [IModelError]($common) If the file is not found or is not a valid *snapshot*.
* @beta
*/
public static openSnapshot(filePath: string): IModelDb {
const iModelDb: IModelDb = this.openStandalone(filePath, OpenMode.Readonly, false);
const briefcaseId: number = iModelDb.getBriefcaseId().value;
if ((BriefcaseId.Snapshot === briefcaseId) || (BriefcaseId.Master === briefcaseId)) {
return iModelDb;
}
throw new IModelError(IModelStatus.BadRequest, "IModelDb.openSnapshot cannot be used to open a briefcase", Logger.logError, loggerCategory);
}
/** Open an iModel from iModelHub. IModelDb files are cached locally. The requested version may be downloaded from iModelHub to the
* cache, or a previously downloaded version re-used from the cache - this behavior can optionally be configured through OpenParams.
* Every open call must be matched with a call to close the IModelDb.
* @param requestContext The client request context.
* @param contextId Id of the Connect Project or Asset containing the iModel
* @param iModelId Id of the iModel
* @param version Version of the iModel to open
* @param openParams Parameters to open the iModel
*/
public static async open(requestContext: AuthorizedClientRequestContext, contextId: string, iModelId: string, openParams: OpenParams = OpenParams.pullAndPush(), version: IModelVersion = IModelVersion.latest()): Promise<IModelDb> {
requestContext.enter();
const perfLogger = new PerfLogger("Opening iModel", () => ({ contextId, iModelId, ...openParams }));
IModelDb.onOpen.raiseEvent(requestContext, contextId, iModelId, openParams, version);
let briefcaseEntry: BriefcaseEntry;
let timedOut = false;
try {
briefcaseEntry = await BriefcaseManager.open(requestContext, contextId, iModelId, openParams, version);
requestContext.enter();
if (briefcaseEntry.isPending) {
if (typeof openParams.timeout === "undefined")
await briefcaseEntry.isPending;
else {
const waitPromise = BeDuration.wait(openParams.timeout).then(() => {
timedOut = true;
});
await Promise.race([briefcaseEntry.isPending, waitPromise]);
}
}
} catch (error) {
requestContext.enter();
Logger.logError(loggerCategory, "Failed IModelDb.open", () => ({ token: requestContext.accessToken.toTokenString(), contextId, iModelId, ...openParams }));
throw error;
}
if (timedOut) {
Logger.logTrace(loggerCategory, "Issuing pending status in IModelDb.open", () => ({ contextId, iModelId, ...openParams }));
throw new RpcPendingResponse();
}
const imodelDb = IModelDb.constructIModelDb(briefcaseEntry, openParams, contextId);
try {
const client = new UlasClient();
const ulasEntry = new UsageLogEntry(os.hostname(), UsageType.Trial, contextId);
await client.logUsage(requestContext, ulasEntry);
requestContext.enter();
} catch (error) {
requestContext.enter();
Logger.logError(loggerCategory, "Could not log usage information", () => ({ errorStatus: error.status, errorMessage: error.Message, iModelToken: imodelDb.iModelToken }));
}
IModelDb.onOpened.raiseEvent(requestContext, imodelDb);
perfLogger.dispose();
return imodelDb;
}
/**
* Returns true if this is a standalone iModel
* @deprecated The confusing concept of *standalone* is being replaced by the more strict concept of a read-only iModel *snapshot*.
*/
public get isStandalone(): boolean {
return this.briefcase.openParams.isStandalone;
}
/** Close this standalone iModel, if it is currently open
* @throws IModelError if the iModel is not open, or is not standalone
* @see [[closeSnapshot]]
* @deprecated The confusing concept of *standalone* is being replaced by the more strict concept of a read-only iModel *snapshot*. Callers should migrate to [[closeSnapshot]].
* @internal
*/
public closeStandalone(): void {
if (!this.briefcase)
throw this.newNotOpenError();
if (!this.isStandalone)
throw new IModelError(BentleyStatus.ERROR, "Cannot use to close a managed iModel. Use IModelDb.close() instead");
BriefcaseManager.closeStandalone(this.briefcase);
this.clearBriefcaseEntry();
}
/** Close this local read-only iModel *snapshot*, if it is currently open.
* > Note: A *snapshot* cannot be modified after this function is called.
* @throws IModelError if the iModel is not open, or is not a *snapshot*.
* @beta
*/
public closeSnapshot(): void {
this.closeStandalone();
}
/** Close this iModel, if it is currently open.
* @param requestContext The client request context.
* @param keepBriefcase Hint to discard or keep the briefcase for potential future use.
* @throws IModelError if the iModel is not open, or is really a snapshot iModel
*/
public async close(requestContext: AuthorizedClientRequestContext, keepBriefcase: KeepBriefcase = KeepBriefcase.Yes): Promise<void> {
requestContext.enter();
if (!this.briefcase)
throw this.newNotOpenError();
if (this.isStandalone)
throw new IModelError(BentleyStatus.ERROR, "Cannot use IModelDb.close() to close a snapshot iModel. Use IModelDb.closeSnapshot() instead");
try {
await BriefcaseManager.close(requestContext, this.briefcase, keepBriefcase);
} catch (error) {
throw error;
} finally {
requestContext.enter();
this.clearBriefcaseEntry();
}
}
private forwardChangesetApplied() { this.onChangesetApplied.raiseEvent(); }
private setupBriefcaseEntry(briefcaseEntry: BriefcaseEntry) {
briefcaseEntry.iModelDb = this;
briefcaseEntry.onBeforeClose.addListener(this.onBriefcaseCloseHandler, this);
briefcaseEntry.onBeforeVersionUpdate.addListener(this.onBriefcaseVersionUpdatedHandler, this);
briefcaseEntry.onChangesetApplied.addListener(this.forwardChangesetApplied, this);
this._briefcase = briefcaseEntry;
}
private clearBriefcaseEntry(): void {
const briefcaseEntry = this.briefcase;
briefcaseEntry.onBeforeClose.removeListener(this.onBriefcaseCloseHandler, this);
briefcaseEntry.onBeforeVersionUpdate.removeListener(this.onBriefcaseVersionUpdatedHandler, this);
briefcaseEntry.onChangesetApplied.removeListener(this.forwardChangesetApplied, this);
briefcaseEntry.iModelDb = undefined;
this._briefcase = undefined;
}
private onBriefcaseCloseHandler() {
this.onBeforeClose.raiseEvent();
this.clearStatementCache();
this.clearSqliteStatementCache();
}
private onBriefcaseVersionUpdatedHandler() { this.iModelToken.changeSetId = this.briefcase.currentChangeSetId; }
/** Event called when the iModel is about to be closed */
public readonly onBeforeClose = new BeEvent<() => void>();
/** Get the in-memory handle of the native Db
* @internal
*/
public get nativeDb(): IModelJsNative.DgnDb { return this.briefcase.nativeDb; }
/** Get the briefcase Id of this iModel */
public getBriefcaseId(): BriefcaseId { return new BriefcaseId(this.briefcase === undefined ? BriefcaseId.Illegal : this.briefcase.briefcaseId); }
/** Returns a new IModelError with errorNumber, message, and meta-data set properly for a *not open* error.
* @internal
*/
public newNotOpenError() {
return new IModelError(IModelStatus.NotOpen, "IModelDb not open", Logger.logError, loggerCategory, () => ({ name: this.name, ...this.iModelToken }));
}
/** Get a prepared ECSQL statement - may require preparing the statement, if not found in the cache.
* @param ecsql The ECSQL statement to prepare
* @returns the prepared statement
* @throws IModelError if the statement cannot be prepared. Normally, prepare fails due to ECSQL syntax errors or references to tables or properties that do not exist. The error.message property will describe the property.
*/
private getPreparedStatement(ecsql: string): ECSqlStatement {
const cachedStatement = this._statementCache.find(ecsql);
if (cachedStatement !== undefined && cachedStatement.useCount === 0) { // we can only recycle a previously cached statement if nobody is currently using it.
cachedStatement.useCount++;
return cachedStatement.statement;
}
this._statementCache.removeUnusedStatementsIfNecessary();
const stmt = this.prepareStatement(ecsql);
if (cachedStatement)
this._statementCache.replace(ecsql, stmt);
else
this._statementCache.add(ecsql, stmt);
return stmt;
}
/** Use a prepared ECSQL statement. This function takes care of preparing the statement and then releasing it.
*
* As preparing statements can be costly, they get cached. When calling this method again with the same ECSQL,
* the already prepared statement from the cache will be reused.
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
*
* @param ecsql The ECSQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @returns the value returned by cb
*/
public withPreparedStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T): T {
const stmt = this.getPreparedStatement(ecsql);
const release = () => {
if (stmt.isShared)
this._statementCache.release(stmt);
else
stmt.dispose();
};
try {
const val: T = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err) {
release();
Logger.logError(loggerCategory, err.toString());
throw err;
}
}
/** Compute number of rows that would be returned by the ECSQL.
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
*
* @param ecsql The ECSQL statement to execute
* @param bindings The values to bind to the parameters (if the ECSQL has any).
* Pass an *array* of values if the parameters are *positional*.
* Pass an *object of the values keyed on the parameter name* for *named parameters*.
* The values in either the array or object must match the respective types of the parameters.
* See "[iModel.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
* @returns Return row count.
* @throws [IModelError]($common) If the statement is invalid
*/
public async queryRowCount(ecsql: string, bindings?: any[] | object): Promise<number> {
for await (const row of this.query(`select count(*) nRows from (${ecsql})`, bindings)) {
return row.nRows;
}
throw new IModelError(DbResult.BE_SQLITE_ERROR, "Failed to get row count");
}
/** Execute a query against this ECDb but restricted by quota and limit settings. This is intended to be used internally
* The result of the query is returned as an array of JavaScript objects where every array element represents an
* [ECSQL row]($docs/learning/ECSQLRowFormat).
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
*
* @param ecsql The ECSQL statement to execute
* @param bindings The values to bind to the parameters (if the ECSQL has any).
* Pass an *array* of values if the parameters are *positional*.
* Pass an *object of the values keyed on the parameter name* for *named parameters*.
* The values in either the array or object must match the respective types of the parameters.
* See "[iModel.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
* @param limitRows Specify upper limit for rows that can be returned by the query.
* @param quota Specify non binding quota. These values are constrained by global setting
* but never the less can be specified to narrow down the quota constraint for the query but staying under global settings.
* @param priority Specify non binding priority for the query. It can help user to adjust
* priority of query in queue so that small and quicker queries can be prioritized over others.
* @returns Returns structure containing rows and status.
* See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
* @internal
*/
public async queryRows(ecsql: string, bindings?: any[] | object, limit?: QueryLimit, quota?: QueryQuota, priority?: QueryPriority): Promise<QueryResponse> {
if (!this._concurrentQueryInitialized) {
this._concurrentQueryInitialized = this.nativeDb.concurrentQueryInit(IModelHost.configuration!.concurrentQuery);
}
if (!bindings) bindings = [];
if (!limit) limit = {};
if (!quota) quota = {};
if (!priority) priority = QueryPriority.Normal;
const base64Header = "encoding=base64;";
// handle binary type
const reviver = (_name: string, value: any) => {
if (typeof value === "string") {
if (value.length >= base64Header.length && value.startsWith(base64Header)) {
const out = value.substr(base64Header.length);
const buffer = Buffer.from(out, "base64");
return new Uint8Array(buffer);
}
}
return value;
};
// handle binary type
const replacer = (_name: string, value: any) => {
if (value && value.constructor === Uint8Array) {
const buffer = Buffer.from(value);
return base64Header + buffer.toString("base64");
}
return value;
};
return new Promise<QueryResponse>((resolve) => {
const postrc = this.nativeDb.postConcurrentQuery(ecsql, JSON.stringify(bindings, replacer), limit!, quota!, priority!);
if (postrc.status !== PostStatus.Done)
resolve({ status: QueryResponseStatus.PostError, rows: [] });
const poll = () => {
const pollrc = this.nativeDb.pollConcurrentQuery(postrc.taskId);
if (pollrc.status === PollStatus.Done)
resolve({ status: QueryResponseStatus.Done, rows: JSON.parse(pollrc.result, reviver) });
else if (pollrc.status === PollStatus.Partial)
resolve({ status: QueryResponseStatus.Partial, rows: JSON.parse(pollrc.result, reviver) });
else if (pollrc.status === PollStatus.Timeout)
resolve({ status: QueryResponseStatus.Timeout, rows: [] });
else if (pollrc.status === PollStatus.Pending)
setTimeout(() => { poll(); }, IModelHost.configuration!.concurrentQuery.pollInterval);
else
resolve({ status: QueryResponseStatus.Error, rows: [pollrc.result] });
};
setTimeout(() => { poll(); }, IModelHost.configuration!.concurrentQuery.pollInterval);
});
}
/** Execute a query and stream its results
* The result of the query is async iterator over the rows. The iterator will get next page automatically once rows in current page has been read.
* [ECSQL row]($docs/learning/ECSQLRowFormat).
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
*
* @param ecsql The ECSQL statement to execute
* @param bindings The values to bind to the parameters (if the ECSQL has any).
* Pass an *array* of values if the parameters are *positional*.
* Pass an *object of the values keyed on the parameter name* for *named parameters*.
* The values in either the array or object must match the respective types of the parameters.
* See "[iModel.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
* @param limitRows Specify upper limit for rows that can be returned by the query.
* @param quota Specify non binding quota. These values are constrained by global setting
* but never the less can be specified to narrow down the quota constraint for the query but staying under global settings.
* @param priority Specify non binding priority for the query. It can help user to adjust
* priority of query in queue so that small and quicker queries can be prioritized over others.
* @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed
* See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
* @throws [IModelError]($common) If there was any error while submitting, preparing or stepping into query
*/
public async * query(ecsql: string, bindings?: any[] | object, limitRows?: number, quota?: QueryQuota, priority?: QueryPriority): AsyncIterableIterator<any> {
let result: QueryResponse;
let offset: number = 0;
let rowsToGet = limitRows ? limitRows : -1;
do {
result = await this.queryRows(ecsql, bindings, { maxRowAllowed: rowsToGet, startRowOffset: offset }, quota, priority);
while (result.status === QueryResponseStatus.Timeout) {
result = await this.queryRows(ecsql, bindings, { maxRowAllowed: rowsToGet, startRowOffset: offset }, quota, priority);
}
if (result.status === QueryResponseStatus.Error)
throw new IModelError(DbResult.BE_SQLITE_ERROR, result.rows.length > 0 ? result.rows[0] : "Failed to execute ECSQL");
if (rowsToGet > 0) {
rowsToGet -= result.rows.length;
}
offset += result.rows.length;
for (const row of result.rows)
yield row;
} while (result.status !== QueryResponseStatus.Done);
}
/** Execute a query against this IModelDb.
* The result of the query is returned as an array of JavaScript objects where every array element represents an
* [ECSQL row]($docs/learning/ECSQLRowFormat).
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
*
* @param ecsql The ECSQL SELECT statement to execute
* @param bindings The values to bind to the parameters (if the ECSQL has any).
* Pass an *array* of values if the parameters are *positional*.
* Pass an *object of the values keyed on the parameter name* for *named parameters*.
* The values in either the array or object must match the respective types of the parameters.
* See "[iModel.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
* @returns Returns the query result as an array of the resulting rows or an empty array if the query has returned no rows.
* See [ECSQL row format]($docs/learning/ECSQLRowFormat) for details about the format of the returned rows.
* @throws [IModelError]($common) If the statement is invalid or [IModelDb.maxLimit]($backend) exceeded when collecting ids.
* @deprecated use withPreparedStatement or query or queryPage instead
*/
public executeQuery(ecsql: string, bindings?: any[] | object): any[] {
return this.withPreparedStatement(ecsql, (stmt: ECSqlStatement) => {
if (bindings)
stmt.bindValues(bindings);
const rows: any[] = [];
while (DbResult.BE_SQLITE_ROW === stmt.step()) {
rows.push(stmt.getRow());
if (rows.length > IModelDb.maxLimit) {
throw new IModelError(IModelStatus.BadRequest, "Max LIMIT exceeded in SELECT statement", Logger.logError, loggerCategory);
}
}
return rows;
});
}
/** Use a prepared SQLite SQL statement. This function takes care of preparing the statement and then releasing it.
* As preparing statements can be costly, they get cached. When calling this method again with the same ECSQL,
* the already prepared statement from the cache will be reused.
* @param sql The SQLite SQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @returns the value returned by cb
* @internal
*/
public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {
const stmt = this.getPreparedSqlStatement(sql);
const release = () => {
if (stmt.isShared)
this._sqliteStatementCache.release(stmt);
else
stmt.dispose();
};
try {
const val: T = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err) {
release();
Logger.logError(loggerCategory, err.toString());
throw err;
}
}
/** Prepare an SQLite SQL statement.
* @param sql The SQLite SQL statement to prepare
* @throws [[IModelError]] if there is a problem preparing the statement.
* @internal
*/
public prepareSqliteStatement(sql: string): SqliteStatement {
const stmt = new SqliteStatement();
stmt.prepare(this.briefcase.nativeDb, sql);
return stmt;
}
/** Get a prepared SQLite SQL statement - may require preparing the statement, if not found in the cache.
* @param sql The SQLite SQL statement to prepare
* @returns the prepared statement
* @throws IModelError if the statement cannot be prepared. Normally, prepare fails due to SQL syntax errors or references to tables or properties that do not exist. The error.message property will describe the property.
*/
private getPreparedSqlStatement(sql: string): SqliteStatement {
const cachedStatement: CachedSqliteStatement | undefined = this._sqliteStatementCache.find(sql);
if (cachedStatement !== undefined && cachedStatement.useCount === 0) { // we can only recycle a previously cached statement if nobody is currently using it.
cachedStatement.useCount++;
return cachedStatement.statement;
}
this._sqliteStatementCache.removeUnusedStatementsIfNecessary();
const stmt: SqliteStatement = this.prepareSqliteStatement(sql);
if (cachedStatement)
this._sqliteStatementCache.replace(sql, stmt);
else
this._sqliteStatementCache.add(sql, stmt);
return stmt;
}
/** Query for a set of entity ids, given an EntityQueryParams
* @param params The query parameters. The `limit` and `offset` members should be used to page results.
* @returns an Id64Set with results of query
* @throws [IModelError]($common) if the generated statement is invalid or [IModelDb.maxLimit]($backend) exceeded when collecting ids.
*
* *Example:*
* ``` ts
* [[include:ECSQL-backend-queries.select-element-by-code-value-using-queryEntityIds]]
* ```
*/
public queryEntityIds(params: EntityQueryParams): Id64Set {
let sql = "SELECT ECInstanceId FROM ";
if (params.only)
sql += "ONLY ";
sql += params.from;
if (params.where) sql += " WHERE " + params.where;
if (typeof params.limit === "number" && params.limit > 0) sql += " LIMIT " + params.limit;
if (typeof params.offset === "number" && params.offset > 0) sql += " OFFSET " + params.offset;
if (params.orderBy) sql += " ORDER BY " + params.orderBy;
const ids = new Set<string>();
this.withPreparedStatement(sql, (stmt) => {
for (const row of stmt) {
if (row.id !== undefined) {
ids.add(row.id);
if (ids.size > IModelDb.maxLimit) {
throw new IModelError(IModelStatus.BadRequest, "Max LIMIT exceeded in SELECT statement", Logger.logError, loggerCategory);
}
}
}
});
return ids;
}
/** Empty the [ECSqlStatementCache]($backend) for this iModel. */
public clearStatementCache(): void { this._statementCache.clear(); }
/** Empty the [SqliteStatementCache]($backend) for this iModel. */
public clearSqliteStatementCache(): void { this._sqliteStatementCache.clear(); }
/** Get the GUID of this iModel. */
public getGuid(): GuidString { return this.nativeDb.getDbGuid(); }
/** Set the GUID of this iModel. */
public setGuid(guid: GuidString): DbResult { return this.nativeDb.setDbGuid(guid); }
/** Update the project extents for this iModel.
* <p><em>Example:</em>
* ``` ts
* [[include:IModelDb.updateProjectExtents]]
* ```
*/
public updateProjectExtents(newExtents: AxisAlignedBox3d) {
this.projectExtents = newExtents;
this.updateIModelProps();
}
/** Update the [EcefLocation]($docs/learning/glossary#eceflocation) of this iModel. */
public updateEcefLocation(ecef: EcefLocation) {
this.setEcefLocation(ecef);
this.updateIModelProps();
}
/** Update the IModelProps of this iModel in the database. */
public updateIModelProps() { this.nativeDb.updateIModelProps(JSON.stringify(this.toJSON())); }
/**
* Commit pending changes to this iModel.
* @note If this IModelDb is connected to an iModel, then you must call [[ConcurrencyControl.request]] before attempting to save changes.
* @param _description Optional description of the changes
* @throws [[IModelError]] if there is a problem saving changes or if there are pending, un-processed lock or code requests.
*/
public saveChanges(description?: string) {
if (this.openParams.openMode === OpenMode.Readonly)
throw new IModelError(IModelStatus.ReadOnly, "IModelDb was opened read-only", Logger.logError, loggerCategory);
// TODO: this.Txns.onSaveChanges => validation, rules, indirect changes, etc.
this.concurrencyControl.onSaveChanges();
const stat = this.nativeDb.saveChanges(description);
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, "Problem saving changes", Logger.logError, loggerCategory);
this.concurrencyControl.onSavedChanges();
}
/** Abandon pending changes in this iModel */
public abandonChanges() {
this.concurrencyControl.abandonRequest();
this.nativeDb.abandonChanges();
}
/** Pull and Merge changes from iModelHub
* @param requestContext The client request context.
* @param version Version to pull and merge to.
* @throws [[IModelError]] If the pull and merge fails.
* @beta
*/
public async pullAndMergeChanges(requestContext: AuthorizedClientRequestContext, version: IModelVersion = IModelVersion.latest()): Promise<void> {
requestContext.enter();
this.concurrencyControl.onMergeChanges();
await BriefcaseManager.pullAndMergeChanges(requestContext, this.briefcase, version);
requestContext.enter();
this.concurrencyControl.onMergedChanges();
this._token.changeSetId = this.briefcase.currentChangeSetId;
this.initializeIModelDb();
}
/** Push changes to iModelHub
* @param requestContext The client request context.
* @param describer A function that returns a description of the changeset. Defaults to the combination of the descriptions of all local Txns.
* @throws [[IModelError]] If the pull and merge fails.
* @beta
*/
public async pushChanges(requestContext: AuthorizedClientRequestContext, describer?: ChangeSetDescriber): Promise<void> {
requestContext.enter();
const description = describer ? describer(this.txns.getCurrentTxnId()) : this.txns.describeChangeSet();
await BriefcaseManager.pushChanges(requestContext, this.briefcase, description);
requestContext.enter();
this._token.changeSetId = this.briefcase.currentChangeSetId;
this.initializeIModelDb();
}
/** Reverse a previously merged set of changes
* @param requestContext The client request context.
* @param version Version to reverse changes to.
* @throws [[IModelError]] If the reversal fails.
* @beta
*/
public async reverseChanges(requestContext: AuthorizedClientRequestContext, version: IModelVersion = IModelVersion.latest()): Promise<void> {
requestContext.enter();
await BriefcaseManager.reverseChanges(requestContext, this.briefcase, version);
requestContext.enter();
this.initializeIModelDb();
}
/** Reinstate a previously reversed set of changes
* @param requestContext The client request context.
* @param version Version to reinstate changes to.
* @throws [[IModelError]] If the reinstate fails.
* @beta
*/
public async reinstateChanges(requestContext: AuthorizedClientRequestContext, version: IModelVersion = IModelVersion.latest()): Promise<void> {
requestContext.enter();
await BriefcaseManager.reinstateChanges(requestContext, this.briefcase, version);
requestContext.enter();
this.initializeIModelDb();
}
/** Set iModel as Master copy.
* @param guid Optionally provide db guid. If its not provided the method would generate one.
*/
public setAsMaster(guid?: GuidString): void {
if (guid === undefined) {
if (DbResult.BE_SQLITE_OK !== this.nativeDb.setAsMaster())
throw new IModelError(IModelStatus.SQLiteError, "", Logger.logWarning, loggerCategory);
} else {
if (DbResult.BE_SQLITE_OK !== this.nativeDb.setAsMaster(guid!))
throw new IModelError(IModelStatus.SQLiteError, "", Logger.logWarning, loggerCategory);
}
}
/** Import an ECSchema. On success, the schema definition is stored in the iModel.
* This method is asynchronous (must be awaited) because, in the case where this IModelId is a briefcase,
* this method must first obtain the schema lock from the IModel server.
* You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
* @param requestContext The client request context
* @param schemaFileName Full path to an ECSchema.xml file that is to be imported.
* @throws IModelError if the schema lock cannot be obtained.
* @see containsClass
*/
public async importSchema(requestContext: ClientRequestContext | AuthorizedClientRequestContext, schemaFileName: string): Promise<void> {
requestContext.enter();
if (!this.briefcase)
throw this.newNotOpenError();
if (this.isStandalone) {
const status = this.briefcase.nativeDb.importSchema(schemaFileName);
if (DbResult.BE_SQLITE_OK !== status)
throw new IModelError(status, "Error importing schema", Logger.logError, loggerCategory, () => ({ schemaFileName }));
return;
}
if (!(requestContext instanceof AuthorizedClientRequestContext))
throw new IModelError(AuthStatus.Error, "Importing the schema requires an AuthorizedClientRequestContext");
await this.concurrencyControl.lockSchema(requestContext);
requestContext.enter();
const stat = this.briefcase.nativeDb.importSchema(schemaFileName);
if (DbResult.BE_SQLITE_OK !== stat) {
throw new IModelError(stat, "Error importing schema", Logger.logError, loggerCategory, () => ({ schemaFileName }));
}
try {
// The schema import logic and/or imported Domains may have created new elements and models.
// Make sure we have the supporting locks and codes.
if (!(requestContext instanceof AuthorizedClientRequestContext))
throw new IModelError(AuthStatus.Error, "Importing the schema requires an AuthorizedClientRequestContext");
await this.concurrencyControl.request(requestContext);
requestContext.enter();
} catch (err) {
requestContext.enter();
this.abandonChanges();
throw err;
}
}
/** Find an already open IModelDb. Used by the remoting logic.
* @throws [[IModelError]] if an open IModelDb matching the token is not found.
*/
public static find(iModelToken: IModelToken): IModelDb {
const briefcaseEntry = BriefcaseManager.findBriefcaseByToken(iModelToken);
if (!briefcaseEntry || !briefcaseEntry.iModelDb) {
Logger.logError(loggerCategory, "IModelDb not found in briefcase cache", () => iModelToken);
throw new IModelNotFoundResponse();
}
Logger.logTrace(loggerCategory, "IModelDb found in briefcase cache", () => iModelToken);
return briefcaseEntry.iModelDb;
}
/** Get the ClassMetaDataRegistry for this iModel.
* @internal
*/
public get classMetaDataRegistry(): MetaDataRegistry {
if (this._classMetaDataRegistry === undefined) this._classMetaDataRegistry = new MetaDataRegistry();
return this._classMetaDataRegistry;
}
/** Get the linkTableRelationships for this IModel */
public get relationships(): Relationships { return this._relationships || (this._relationships = new Relationships(this)); }
/** Get the ConcurrencyControl for this IModel.
* @beta
*/
public get concurrencyControl(): ConcurrencyControl { return (this._concurrency !== undefined) ? this._concurrency : (this._concurrency = new ConcurrencyControl(this)); }
/** Get the CodeSpecs in this IModel. */
public get codeSpecs(): CodeSpecs { return (this._codeSpecs !== undefined) ? this._codeSpecs : (this._codeSpecs = new CodeSpecs(this)); }
/** @internal */
public insertCodeSpec(codeSpec: CodeSpec): Id64String {
if (!this.briefcase) throw this.newNotOpenError();
const { error, result } = this.nativeDb.insertCodeSpec(codeSpec.name, codeSpec.specScopeType, codeSpec.scopeReq);
if (error) throw new IModelError(error.status, "inserting CodeSpec" + codeSpec, Logger.logWarning, loggerCategory);
return Id64.fromJSON(result);
}
/** Prepare an ECSQL statement.
* @param sql The ECSQL statement to prepare
* @throws [[IModelError]] if there is a problem preparing the statement.
*/
public prepareStatement(sql: string): ECSqlStatement {
if (!this.briefcase)
throw this.newNotOpenError();
const stmt = new ECSqlStatement();
stmt.prepare(this.nativeDb, sql);
return stmt;
}
/** Construct an entity (Element or Model) from an iModel.
* @throws [[IModelError]] if the entity cannot be constructed.
*/
public constructEntity<T extends Entity>(props: EntityProps): T {
const jsClass = this.getJsClass(props.classFullName);
return new jsClass(props, this) as T;
}
/** Get the JavaScript class that handles a given entity class. */
public getJsClass<T extends typeof Entity>(classFullName: string): T {
try {
return ClassRegistry.getClass(classFullName, this) as T;
} catch (err) {
if (!ClassRegistry.isNotFoundError(err)) {
Logger.logError(loggerCategory, err.toString());
throw err;
}
this.loadMetaData(classFullName);
return ClassRegistry.getClass(classFullName, this) as T;
}
}
/** Get metadata for a class. This method will load the metadata from the iModel into the cache as a side-effect, if necessary.
* @throws [IModelError]($common) if the metadata cannot be found nor loaded.
*/