-
Notifications
You must be signed in to change notification settings - Fork 208
/
IModelDb.ts
3294 lines (2957 loc) · 153 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) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module iModels
*/
import * as fs from "fs";
import { join } from "path";
import * as touch from "touch";
import { IModelJsNative } from "@bentley/imodeljs-native";
import {
AccessToken, assert, BeEvent, BentleyStatus, ChangeSetStatus, DbChangeStage, DbConflictCause, DbConflictResolution, DbOpcode, DbResult, DbValueType, Guid, GuidString, Id64, Id64Arg, Id64Array, Id64Set, Id64String,
IModelStatus, JsonUtils, Logger, LogLevel, OpenMode, UnexpectedErrors,
} from "@itwin/core-bentley";
import {
AxisAlignedBox3d, BRepGeometryCreate, BriefcaseId, BriefcaseIdValue, CategorySelectorProps, ChangesetIdWithIndex, ChangesetIndexAndId, Code,
CodeProps, CreateEmptySnapshotIModelProps, CreateEmptyStandaloneIModelProps, CreateSnapshotIModelProps, DbQueryRequest, DisplayStyleProps,
DomainOptions, EcefLocation, ECJsNames, ECSchemaProps, ECSqlReader, ElementAspectProps, ElementGeometryRequest, ElementGraphicsRequestProps, ElementLoadProps,
ElementProps, EntityMetaData, EntityProps, EntityQueryParams, FilePropertyProps, FontId, FontMap, FontType, GeoCoordinatesRequestProps,
GeoCoordinatesResponseProps, GeometryContainmentRequestProps, GeometryContainmentResponseProps, IModel, IModelCoordinatesRequestProps,
IModelCoordinatesResponseProps, IModelError, IModelNotFoundResponse, IModelTileTreeProps, LocalFileName, MassPropertiesRequestProps,
MassPropertiesResponseProps, ModelExtentsProps, ModelLoadProps, ModelProps, ModelSelectorProps, OpenBriefcaseProps, OpenCheckpointArgs, OpenSqliteArgs,
ProfileOptions, PropertyCallback, QueryBinder, QueryOptions, QueryOptionsBuilder, QueryRowFormat, SchemaState, SheetProps, SnapRequestProps,
SnapResponseProps, SnapshotOpenOptions, SpatialViewDefinitionProps, SubCategoryResultRow, TextureData, TextureLoadProps, ThumbnailProps,
UpgradeOptions, ViewDefinition2dProps, ViewDefinitionProps, ViewIdString, ViewQueryParams, ViewStateLoadProps, ViewStateProps, ViewStoreRpc,
} from "@itwin/core-common";
import { Range2d, Range3d } from "@itwin/core-geometry";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { BriefcaseManager, PullChangesArgs, PushChangesArgs } from "./BriefcaseManager";
import { ChannelAdmin, ChannelControl } from "./ChannelControl";
import { CheckpointManager, CheckpointProps, V2CheckpointManager } from "./CheckpointManager";
import { ClassRegistry, MetaDataRegistry } from "./ClassRegistry";
import { CloudSqlite } from "./CloudSqlite";
import { CodeService } from "./CodeService";
import { CodeSpecs } from "./CodeSpecs";
import { ConcurrentQuery } from "./ConcurrentQuery";
import { ECSchemaXmlContext } from "./ECSchemaXmlContext";
import { ECSqlStatement } from "./ECSqlStatement";
import { Element, SectionDrawing, Subject } from "./Element";
import { ElementAspect } from "./ElementAspect";
import { generateElementGraphics } from "./ElementGraphics";
import { Entity, EntityClassType } from "./Entity";
import { ExportGraphicsOptions, ExportPartGraphicsOptions } from "./ExportGraphics";
import { GeoCoordConfig } from "./GeoCoordConfig";
import { IModelHost } from "./IModelHost";
import { IModelJsFs } from "./IModelJsFs";
import { IpcHost } from "./IpcHost";
import { Model } from "./Model";
import { Relationships } from "./Relationship";
import { SchemaSync } from "./SchemaSync";
import { ServerBasedLocks } from "./ServerBasedLocks";
import { SqliteStatement, StatementCache } from "./SqliteStatement";
import { TxnManager } from "./TxnManager";
import { DrawingViewDefinition, SheetViewDefinition, ViewDefinition } from "./ViewDefinition";
import { ViewStore } from "./ViewStore";
import { BaseSettings, SettingDictionary, SettingName, SettingResolver, SettingsPriority, SettingType } from "./workspace/Settings";
import { Workspace } from "./workspace/Workspace";
import { ComputeRangesForTextLayoutArgs, TextLayoutRanges } from "./TextAnnotationLayout";
import type { BlobContainer } from "./BlobContainerService";
/** @internal */
export interface ChangesetConflictArgs {
cause: DbConflictCause;
opcode: DbOpcode;
indirect: boolean;
tableName: string;
changesetFile?: string;
columnCount: number;
getForeignKeyConflicts: () => number;
dump: () => void;
setLastError: (message: string) => void;
getPrimaryKeyColumns: () => number[];
getValueType: (columnIndex: number, stage: DbChangeStage) => DbValueType | null | undefined;
getValueBinary: (columnIndex: number, stage: DbChangeStage) => Uint8Array | null | undefined;
getValueId: (columnIndex: number, stage: DbChangeStage) => Id64String | null | undefined;
getValueText: (columnIndex: number, stage: DbChangeStage) => string | null | undefined;
getValueInteger: (columnIndex: number, stage: DbChangeStage) => number | null | undefined;
getValueDouble: (columnIndex: number, stage: DbChangeStage) => number | null | undefined;
isValueNull: (columnIndex: number, stage: DbChangeStage) => boolean | undefined;
}
// spell:ignore fontid fontmap
const loggerCategory: string = BackendLoggerCategory.IModelDb;
/** Options for [[IModelDb.Models.updateModel]]
* @note To mark *only* the geometry as changed, use [[IModelDb.Models.updateGeometryGuid]] instead.
* @public
*/
export interface UpdateModelOptions extends ModelProps {
/** If defined, update the last modify time of the Model */
updateLastMod?: boolean;
/** If defined, update the GeometryGuid of the Model */
geometryChanged?: boolean;
}
/** Options supplied to [[IModelDb.computeProjectExtents]].
* @public
*/
export interface ComputeProjectExtentsOptions {
/** If true, the result will include `extentsWithOutliers`. */
reportExtentsWithOutliers?: boolean;
/** If true, the result will include `outliers`. */
reportOutliers?: boolean;
}
/** The result of [[IModelDb.computeProjectExtents]].
* @public
*/
export interface ComputedProjectExtents {
/** The computed extents, excluding any outlier elements. */
extents: Range3d;
/** If requested by caller, the computed extents, *including* any outlier elements. */
extentsWithOutliers?: Range3d;
/** If requested by caller, the Ids of outlier elements excluded from the computed extents. */
outliers?: Id64Array;
}
/**
* Interface for acquiring element locks to coordinate simultaneous edits from multiple briefcases.
* @beta
*/
export interface LockControl {
/**
* true if this LockControl uses a server-based concurrency approach.
*/
readonly isServerBased: boolean;
/**
* Close the local lock control database
* @internal
*/
close(): void;
/**
* Notification that a new element was just created. Called by [[Element.onInserted]]
* @internal
*/
elementWasCreated(id: Id64String): void;
/**
* Throw if locks are required and the exclusive lock is not held on the supplied element.
* Note: there is no need to check the shared locks on parents/models since an element cannot hold the exclusive lock without first obtaining them.
* Called by [[Element.onUpdate]], [[Element.onDelete]], etc.
* @internal
*/
checkExclusiveLock(id: Id64String, type: string, operation: string): void;
/**
* Throw if locks are required and a shared lock is not held on the supplied element.
* Called by [[Element.onInsert]] to ensure shared lock is held on model and parent.
* @internal
*/
checkSharedLock(id: Id64String, type: string, operation: string): void;
/**
* Determine whether the supplied element currently holds the exclusive lock
*/
holdsExclusiveLock(id: Id64String): boolean;
/**
* Determine whether the supplied element currently holds a shared lock
*/
holdsSharedLock(id: Id64String): boolean;
/**
* Acquire locks on one or more elements from the lock server, if required and not already held.
* If any required lock is not available, this method throws an exception and *none* of the requested locks are acquired.
* > Note: acquiring the exclusive lock on an element requires also obtaining a shared lock on all its owner elements. This method will
* attempt to acquire all necessary locks for both sets of input ids.
*/
acquireLocks(arg: {
/** if present, one or more elements to obtain shared lock */
shared?: Id64Arg;
/** if present, one or more elements to obtain exclusive lock */
exclusive?: Id64Arg;
}): Promise<void>;
/**
* Release all locks currently held by this Briefcase from the lock server.
* Not possible to release locks unless push or abandon all changes. Should only be called internally.
* @internal
*/
releaseAllLocks(): Promise<void>;
}
/**
* Options for the importing of schemas
* @public
*/
export interface SchemaImportOptions {
/**
* An [[ECSchemaXmlContext]] to use instead of building a default one.
* This can be useful in rare cases where custom schema location logic is necessary
* @internal
*/
ecSchemaXmlContext?: ECSchemaXmlContext;
}
/** A null-implementation of LockControl that does not attempt to limit access between briefcases. This relies on change-merging to resolve conflicts. */
class NoLocks implements LockControl {
public get isServerBased() { return false; }
public close(): void { }
public clearAllLocks(): void { }
public holdsExclusiveLock(): boolean { return false; }
public holdsSharedLock(): boolean { return false; }
public checkExclusiveLock(): void { }
public checkSharedLock(): void { }
public elementWasCreated(): void { }
public async acquireLocks() { }
public async releaseAllLocks(): Promise<void> { }
}
/** @internal */
export enum BriefcaseLocalValue {
StandaloneEdit = "StandaloneEdit",
NoLocking = "NoLocking"
}
// function to open an briefcaseDb, perform an operation, and then close it.
const withBriefcaseDb = async (briefcase: OpenBriefcaseArgs, fn: (_db: BriefcaseDb) => Promise<any>) => {
const db = await BriefcaseDb.open(briefcase);
try {
return await fn(db);
} finally {
db.close();
}
};
/**
* Settings for an individual iModel. May only include settings priority for iModel, iTwin and organization.
* @note if there is more than one iModel for an iTwin or organization, they will *each* hold a copy of the settings for those priorities.
*/
class IModelSettings extends BaseSettings {
protected override verifyPriority(priority: SettingsPriority) {
if (priority <= SettingsPriority.application)
throw new Error("Use IModelHost.appSettings");
}
// attempt to resolve a setting from this iModel's settings, otherwise use appWorkspace's settings, otherwise defaultValue.
public override resolveSetting<T extends SettingType>(name: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined {
return super.resolveSetting(name, resolver) ?? IModelHost.appWorkspace.settings.resolveSetting(name, resolver, defaultValue);
}
}
/** An iModel database file. The database file can either be a briefcase or a snapshot.
* @see [Accessing iModels]($docs/learning/backend/AccessingIModels.md)
* @see [About IModelDb]($docs/learning/backend/IModelDb.md)
* @public
*/
export abstract class IModelDb extends IModel {
private _initialized = false;
/** Keep track of open imodels to support `tryFind` for RPC purposes */
private static readonly _openDbs = new Map<string, IModelDb>();
public static readonly defaultLimit = 1000; // default limit for batching queries
public static readonly maxLimit = 10000; // maximum limit for batching queries
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 channels: ChannelControl = new ChannelAdmin(this);
private _relationships?: Relationships;
private readonly _statementCache = new StatementCache<ECSqlStatement>();
private readonly _sqliteStatementCache = new StatementCache<SqliteStatement>();
private _codeSpecs?: CodeSpecs;
private _classMetaDataRegistry?: MetaDataRegistry;
protected _fontMap?: FontMap;
/** @internal */
private _workspace?: Workspace;
private readonly _snaps = new Map<string, IModelJsNative.SnapRequest>();
private static _shutdownListener: VoidFunction | undefined; // so we only register listener once
/** @internal */
protected _locks?: LockControl = new NoLocks();
/** @internal */
protected _codeService?: CodeService;
/** @alpha */
public get codeService() { return this._codeService; }
/**
* Get the [[LockControl]] for this iModel.
* @beta
*/
public get locks(): LockControl { return this._locks!; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
/**
* Get the [[Workspace]] for this iModel.
* @beta
*/
public get workspace(): Workspace {
if (undefined === this._workspace)
this._workspace = Workspace.construct(new IModelSettings());
return this._workspace;
}
/** Acquire the exclusive schema lock on this iModel.
* > Note: To acquire the schema lock, all other briefcases must first release *all* their locks. No other briefcases
* will be able to acquire *any* locks while the schema lock is held.
*/
public async acquireSchemaLock(): Promise<void> {
return this.locks.acquireLocks({ exclusive: IModel.repositoryModelId });
}
/** determine whether the schema lock is currently held for this iModel. */
public get holdsSchemaLock() {
return this.locks.holdsExclusiveLock(IModel.repositoryModelId);
}
/** Event called after a changeset is applied to this IModelDb. */
public readonly onChangesetApplied = new BeEvent<() => void>();
/** @internal */
public notifyChangesetApplied() {
this.changeset = this.nativeDb.getCurrentChangeset();
this.onChangesetApplied.raiseEvent();
}
/** @internal */
public restartDefaultTxn() {
this.nativeDb.restartDefaultTxn();
}
public get fontMap(): FontMap {
return this._fontMap ?? (this._fontMap = new FontMap(this.nativeDb.readFontMap()));
}
/** @internal */
public clearFontMap(): void {
this._fontMap = undefined;
}
/**
* Add a new font name/type to the FontMap for this iModel and return its FontId.
* @param name The name of the font to add
* @param type The type of the font. Default is TrueType.
* @returns The FontId for the newly added font. If a font by that name/type already exists, this method does not fail, it returns the existing Id.
* @see [FontId and FontMap]($docs/learning/backend/Fonts.md#fontid-and-fontmap)
* @beta
*/
public addNewFont(name: string, type?: FontType): FontId {
this.locks.checkExclusiveLock(IModel.repositoryModelId, "schema", "addNewFont");
this.clearFontMap();
return this.nativeDb.addNewFont({ name, type: type ?? FontType.TrueType });
}
/** Check if this iModel has been opened read-only or not. */
public get isReadonly(): boolean { return this.openMode === OpenMode.Readonly; }
/** The Guid that identifies this iModel. */
public override get iModelId(): GuidString {
assert(undefined !== super.iModelId);
return super.iModelId;
} // GuidString | undefined for the IModel superclass, but required for all IModelDb subclasses
/** @internal*/
public readonly nativeDb: IModelJsNative.DgnDb;
/** Get the full path fileName of this iModelDb
* @note this member is only valid while the iModel is opened.
*/
public get pathName(): LocalFileName { return this.nativeDb.getFilePath(); }
/** Get the full path to this iModel's "watch file".
* A read-only briefcase opened with `watchForChanges: true` creates this file next to the briefcase file on open, if it doesn't already exist.
* A writable briefcase "touches" this file if it exists whenever it commits changes to the briefcase.
* The read-only briefcase can use a file watcher to react when the writable briefcase makes changes to the briefcase.
* This is more reliable than watching the sqlite WAL file.
* @internal
*/
public get watchFilePathName(): LocalFileName { return `${this.pathName}-watch`; }
/** @internal */
protected constructor(args: { nativeDb: IModelJsNative.DgnDb, key: string, changeset?: ChangesetIdWithIndex }) {
super({ ...args, iTwinId: args.nativeDb.getITwinId(), iModelId: args.nativeDb.getIModelId() });
this.nativeDb = args.nativeDb;
// it is illegal to create an IModelDb unless the nativeDb has been opened. Throw otherwise.
if (!this.isOpen)
throw new Error("cannot create an IModelDb unless it has already been opened");
// PR https://github.com/iTwin/imodel-native/pull/558 renamed closeIModel to closeFile because it changed its behavior.
// Ideally, nobody outside of core-backend would be calling it, but somebody important is.
// Make closeIModel available so their code doesn't break.
(this.nativeDb as any).closeIModel = () => {
if (!this.isReadonly)
this.saveChanges(); // preserve old behavior of closeIModel that was removed when renamed to closeFile
this.nativeDb.closeFile();
};
this.nativeDb.setIModelDb(this);
this.loadSettingDictionaries();
GeoCoordConfig.loadForImodel(this.workspace.settings); // load gcs data specified by iModel's settings dictionaries, must be done before calling initializeIModelDb
this.initializeIModelDb();
IModelDb._openDbs.set(this._fileKey, this);
if (undefined === IModelDb._shutdownListener) { // the first time we create an IModelDb, add a listener to close any orphan files at shutdown.
IModelDb._shutdownListener = IModelHost.onBeforeShutdown.addListener(() => {
IModelDb._openDbs.forEach((db) => { // N.B.: db.close() removes from _openedDbs
try {
db.abandonChanges();
db.close();
} catch { }
});
});
}
}
/** Close this IModel, if it is currently open, and save changes if it was opened in ReadWrite mode. */
public close(): void {
if (!this.isOpen)
return; // don't continue if already closed
this.beforeClose();
IModelDb._openDbs.delete(this._fileKey);
this._workspace?.close();
this.locks.close();
this._locks = undefined;
this._codeService?.close();
this._codeService = undefined;
if (!this.isReadonly)
this.saveChanges();
this.nativeDb.closeFile();
}
/** @internal */
public async refreshContainerForRpc(_userAccessToken: AccessToken): Promise<void> { }
/** Event called when the iModel is about to be closed. */
public readonly onBeforeClose = new BeEvent<() => void>();
/**
* Called by derived classes before closing the connection
* @internal
*/
protected beforeClose() {
this.onBeforeClose.raiseEvent();
this.clearCaches();
}
/** @internal */
protected initializeIModelDb() {
const props = this.nativeDb.getIModelProps();
super.initialize(props.rootSubject.name, props);
if (this._initialized)
return;
this._initialized = true;
const db = this.isBriefcaseDb() ? this : undefined;
if (!db || !IpcHost.isValid)
return;
db.onNameChanged.addListener(() => IpcHost.notifyTxns(db, "notifyIModelNameChanged", db.name));
db.onRootSubjectChanged.addListener(() => IpcHost.notifyTxns(db, "notifyRootSubjectChanged", db.rootSubject));
db.onProjectExtentsChanged.addListener(() => IpcHost.notifyTxns(db, "notifyProjectExtentsChanged", db.projectExtents.toJSON()));
db.onGlobalOriginChanged.addListener(() => IpcHost.notifyTxns(db, "notifyGlobalOriginChanged", db.globalOrigin.toJSON()));
db.onEcefLocationChanged.addListener(() => IpcHost.notifyTxns(db, "notifyEcefLocationChanged", db.ecefLocation?.toJSON()));
db.onGeographicCoordinateSystemChanged.addListener(() => IpcHost.notifyTxns(db, "notifyGeographicCoordinateSystemChanged", db.geographicCoordinateSystem?.toJSON()));
}
/** Returns true if this is a BriefcaseDb
* @see [[BriefcaseDb.open]]
*/
public get isBriefcase(): boolean { return false; }
/** Type guard for instanceof [[BriefcaseDb]] */
public isBriefcaseDb(): this is BriefcaseDb { return this.isBriefcase; }
/** Returns true if this is a SnapshotDb
* @see [[SnapshotDb.open]]
*/
public get isSnapshot(): boolean { return false; }
/** Type guard for instanceof [[SnapshotDb]] */
public isSnapshotDb(): this is SnapshotDb { return this.isSnapshot; }
/** Returns true if this is a *standalone* iModel
* @see [[StandaloneDb.open]]
* @internal
*/
public get isStandalone(): boolean { return false; }
/** Type guard for instanceof [[StandaloneDb]]. */
public isStandaloneDb(): this is StandaloneDb { return this.isStandalone; }
/** Return `true` if the underlying nativeDb is open and valid.
* @internal
*/
public get isOpen(): boolean { return this.nativeDb.isOpen(); }
/** Get the briefcase Id of this iModel */
public getBriefcaseId(): BriefcaseId { return this.isOpen ? this.nativeDb.getBriefcaseId() : BriefcaseIdValue.Illegal; }
/**
* Use a prepared ECSQL statement, potentially from the statement cache. If the requested statement doesn't exist
* in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
* in the statement cache so it can be reused in the future. Use this method for ECSQL statements that will be
* reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
* the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withStatement]].
* @param sql The SQLite SQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @param logErrors Determines if error will be logged if statement fail to prepare
* @returns the value returned by `callback`.
* @see [[withStatement]]
* @public
*/
public withPreparedStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors = true): T {
const stmt = this._statementCache.findAndRemove(ecsql) ?? this.prepareStatement(ecsql, logErrors);
const release = () => this._statementCache.addOrDispose(stmt);
try {
const val = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err: any) {
release();
throw err;
}
}
/**
* Prepared and execute a callback on an ECSQL statement. After the callback completes the statement is disposed.
* Use this method for ECSQL statements are either not expected to be reused, or are not expensive to prepare.
* For statements that will be reused often, instead use [[withPreparedStatement]].
* @param sql The SQLite SQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @param logErrors Determines if error will be logged if statement fail to prepare
* @returns the value returned by `callback`.
* @see [[withPreparedStatement]]
* @public
*/
public withStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors = true): T {
const stmt = this.prepareStatement(ecsql, logErrors);
const release = () => stmt.dispose();
try {
const val = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err: any) {
release();
throw err;
}
}
/** Allow to execute query and read results along with meta data. The result are streamed.
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
* - [ECSQL Row Format]($docs/learning/ECSQLRowFormat)
*
* @param params The values to bind to the parameters (if the ECSQL has any).
* @param config Allow to specify certain flags which control how query is executed.
* @returns Returns an [ECSqlReader]($common) which helps iterate over the result set and also give access to metadata.
* @public
* */
public createQueryReader(ecsql: string, params?: QueryBinder, config?: QueryOptions): ECSqlReader {
if (!this.nativeDb.isOpen())
throw new IModelError(DbResult.BE_SQLITE_ERROR, "db not open");
const executor = {
execute: async (request: DbQueryRequest) => {
return ConcurrentQuery.executeQueryRequest(this.nativeDb, request);
},
};
return new ECSqlReader(executor, ecsql, params, config);
}
/** 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 params The values to bind to the parameters (if the ECSQL has any).
* @param options Allow to specify certain flags which control how query is executed.
* @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
* 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
* @deprecated in 3.7. Use [[createQueryReader]] instead; it accepts the same parameters.
*/
public async * query(ecsql: string, params?: QueryBinder, options?: QueryOptions): AsyncIterableIterator<any> {
const builder = new QueryOptionsBuilder(options);
const reader = this.createQueryReader(ecsql, params, builder.getOptions());
while (await reader.step())
yield reader.formatCurrentRow();
}
/** 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 params The values to bind to the parameters (if the ECSQL has any).
* See "[iTwin.js Types used in ECSQL Parameter Bindings]($docs/learning/ECSQLParameterTypes)" for details.
* @returns Return row count.
* @throws [IModelError]($common) If the statement is invalid
* @deprecated in 3.7. Count the number of results using `count(*)` where the original query is a subquery instead. E.g., `SELECT count(*) FROM (<query-whose-rows-to-count>)`.
*/
public async queryRowCount(ecsql: string, params?: QueryBinder): Promise<number> {
for await (const row of this.createQueryReader(`SELECT count(*) FROM (${ecsql})`, params)) {
return row[0] as number;
}
throw new IModelError(DbResult.BE_SQLITE_ERROR, "Failed to get row count");
}
/** Cancel any previous query with same token and run execute the current specified query.
* 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 token None empty restart token. The previous query with same token would be cancelled. This would cause
* exception which user code must handle.
* @param params The values to bind to the parameters (if the ECSQL has any).
* @param options Allow to specify certain flags which control how query is executed.
* @returns Returns the query result as an *AsyncIterableIterator<any>* which lazy load result as needed. The row format is determined by *rowFormat* parameter.
* 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
* @deprecated in 3.7. Use [[createQueryReader]] instead. Pass in the restart token as part of the `config` argument; e.g., `{ restartToken: myToken }` or `new QueryOptionsBuilder().setRestartToken(myToken).getOptions()`.
*/
public async * restartQuery(token: string, ecsql: string, params?: QueryBinder, options?: QueryOptions): AsyncIterableIterator<any> {
for await (const row of this.createQueryReader(ecsql, params, new QueryOptionsBuilder(options).setRestartToken(token).getOptions())) {
yield row;
}
}
/**
* Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist
* in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
* in the statement cache so it can be reused in the future. Use this method for SQL statements that will be
* reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding
* the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].
* @param sql The SQLite SQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @param logErrors Determine if errors are logged or not
* @returns the value returned by `callback`.
* @see [[withPreparedStatement]]
* @public
*/
public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T, logErrors = true): T {
const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql, logErrors);
const release = () => this._sqliteStatementCache.addOrDispose(stmt);
try {
const val: T = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err: any) {
release();
throw err;
}
}
/**
* Prepared and execute a callback on a SQL statement. After the callback completes the statement is disposed.
* Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.
* For statements that will be reused often, instead use [[withPreparedSqliteStatement]].
* @param sql The SQLite SQL statement to execute
* @param callback the callback to invoke on the prepared statement
* @param logErrors Determine if errors are logged or not
* @returns the value returned by `callback`.
* @public
*/
public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T, logErrors = true): T {
const stmt = this.prepareSqliteStatement(sql, logErrors);
const release = () => stmt.dispose();
try {
const val: T = callback(stmt);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err: any) {
release();
throw err;
}
}
/** Prepare an SQL statement.
* @param sql The SQL statement to prepare
* @throws [[IModelError]] if there is a problem preparing the statement.
* @internal
*/
public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {
const stmt = new SqliteStatement(sql);
stmt.prepare(this.nativeDb, logErrors);
return stmt;
}
/**
* queries the BisCore.SubCategory table for the entries that are children of the passed categoryIds
* @param categoryIds categoryIds to query
* @returns array of SubCategoryResultRow
* @internal
*/
public async querySubCategories(categoryIds: Iterable<Id64String>): Promise<SubCategoryResultRow[]> {
const result: SubCategoryResultRow[] = [];
const where = [...categoryIds].join(",");
const query = `SELECT ECInstanceId as id, Parent.Id as parentId, Properties as appearance FROM BisCore.SubCategory WHERE Parent.Id IN (${where})`;
try {
for await (const row of this.createQueryReader(query, undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) {
result.push(row.toRow() as SubCategoryResultRow);
}
} catch {
// We can ignore the error here, and just return whatever we were able to query.
}
return result;
}
/** 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]] 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 (params.orderBy)
sql += ` ORDER BY ${params.orderBy}`;
if (typeof params.limit === "number" && params.limit > 0)
sql += ` LIMIT ${params.limit}`;
if (typeof params.offset === "number" && params.offset > 0)
sql += ` OFFSET ${params.offset}`;
const ids = new Set<string>();
this.withPreparedStatement(sql, (stmt) => {
if (params.bindings)
stmt.bindValues(params.bindings);
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");
}
}
}
});
return ids;
}
/** Clear all in-memory caches held in this IModelDb. */
public clearCaches() {
this._statementCache.clear();
this._sqliteStatementCache.clear();
this._classMetaDataRegistry = undefined;
}
/** Update the project extents for this iModel.
* <p><em>Example:</em>
* ``` ts
* [[include:IModelDb.updateProjectExtents]]
* ```
*/
public updateProjectExtents(newExtents: AxisAlignedBox3d) {
this.projectExtents = newExtents;
this.updateIModelProps();
}
/** Compute an appropriate project extents for this iModel based on the ranges of all spatial elements.
* Typically, the result is simply the union of the ranges of all spatial elements. However, the algorithm also detects "outlier elements",
* whose placements locate them so far from the rest of the spatial geometry that they are considered statistically insignificant. The
* range of an outlier element does not contribute to the computed extents.
* @param options Specifies the level of detail desired in the return value.
* @returns the computed extents.
* @note This method does not modify the IModel's stored project extents. @see [[updateProjectExtents]].
*/
public computeProjectExtents(options?: ComputeProjectExtentsOptions): ComputedProjectExtents {
const wantFullExtents = true === options?.reportExtentsWithOutliers;
const wantOutliers = true === options?.reportOutliers;
const result = this.nativeDb.computeProjectExtents(wantFullExtents, wantOutliers);
return {
extents: Range3d.fromJSON(result.extents),
extentsWithOutliers: result.fullExtents ? Range3d.fromJSON(result.fullExtents) : undefined,
outliers: result.outliers,
};
}
/** 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(): void {
this.nativeDb.updateIModelProps(this.toJSON());
}
/** Commit pending changes to this iModel.
* @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): void {
if (this.openMode === OpenMode.Readonly)
throw new IModelError(IModelStatus.ReadOnly, "IModelDb was opened read-only");
const stat = this.nativeDb.saveChanges(description);
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, `Could not save changes (${description})`);
}
/** Abandon pending changes in this iModel. */
public abandonChanges(): void {
this.nativeDb.abandonChanges();
}
/**
* Save all changes and perform a [checkpoint](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) on this IModelDb.
* This ensures that all changes to the database since it was opened are saved to its file and the WAL file is truncated.
* @note Checkpoint automatically happens when IModelDbs are closed. However, the checkpoint
* operation itself can take some time. It may be useful to call this method prior to closing so that the checkpoint "penalty" is paid earlier.
* @note Another use for this function is to permit the file to be copied while it is open for write. iModel files should
* rarely be copied, and even less so while they're opened. But this scenario is sometimes encountered for tests.
*/
public performCheckpoint() {
if (!this.isReadonly) {
this.saveChanges();
this.nativeDb.performCheckpoint();
}
}
/** @internal */
public reverseTxns(numOperations: number): IModelStatus {
return this.nativeDb.reverseTxns(numOperations);
}
/** @internal */
public reinstateTxn(): IModelStatus {
return this.nativeDb.reinstateTxn();
}
/** @internal */
public restartTxnSession(): void {
return this.nativeDb.restartTxnSession();
}
/** 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 IModelDb is a briefcase, this method first obtains 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 schemaFileName array of Full paths to ECSchema.xml files to be imported.
* @param {SchemaImportOptions} options - options during schema import.
* @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
* @note Changes are saved if importSchemas is successful and abandoned if not successful.
* @see querySchemaVersion
*/
public async importSchemas(schemaFileNames: LocalFileName[], options?: SchemaImportOptions): Promise<void> {
if (schemaFileNames.length === 0)
return;
const maybeCustomNativeContext = options?.ecSchemaXmlContext?.nativeContext;
if (this.nativeDb.schemaSyncEnabled()) {
await SchemaSync.withLockedAccess(this, { openMode: OpenMode.Readonly, operationName: "schema sync" }, async (syncAccess) => {
const schemaSyncDbUri = syncAccess.getUri();
this.saveChanges();
let stat = this.nativeDb.importSchemas(schemaFileNames, { schemaLockHeld: false, ecSchemaXmlContext: maybeCustomNativeContext, schemaSyncDbUri });
if (DbResult.BE_SQLITE_ERROR_SchemaLockFailed === stat) {
this.abandonChanges();
if (this.nativeDb.getITwinId() !== Guid.empty)
await this.acquireSchemaLock();
stat = this.nativeDb.importSchemas(schemaFileNames, { schemaLockHeld: true, ecSchemaXmlContext: maybeCustomNativeContext, schemaSyncDbUri });
}
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, "Error importing schema");
});
} else {
const nativeImportOptions: IModelJsNative.SchemaImportOptions = {
schemaLockHeld: true,
ecSchemaXmlContext: maybeCustomNativeContext,
};
if (this.nativeDb.getITwinId() !== Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
await this.acquireSchemaLock();
const stat = this.nativeDb.importSchemas(schemaFileNames, nativeImportOptions);
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, "Error importing schema");
}
this.clearCaches();
}
/** Import ECSchema(s) serialized to XML. On success, the schema definition is stored in the iModel.
* This method is asynchronous (must be awaited) because, in the case where this IModelDb is a briefcase, this method first obtains the schema lock from the iModel server.
* You must import a schema into an iModel before you can insert instances of the classes in that schema. See [[Element]]
* @param serializedXmlSchemas The xml string(s) created from a serialized ECSchema.
* @throws [[IModelError]] if the schema lock cannot be obtained or there is a problem importing the schema.
* @note Changes are saved if importSchemaStrings is successful and abandoned if not successful.
* @see querySchemaVersion
* @alpha
*/
public async importSchemaStrings(serializedXmlSchemas: string[]): Promise<void> {
if (serializedXmlSchemas.length === 0)
return;
if (this.nativeDb.schemaSyncEnabled()) {
await SchemaSync.withLockedAccess(this, { openMode: OpenMode.Readonly, operationName: "schemaSync" }, async (syncAccess) => {
const schemaSyncDbUri = syncAccess.getUri();
this.saveChanges();
let stat = this.nativeDb.importXmlSchemas(serializedXmlSchemas, { schemaLockHeld: false, schemaSyncDbUri });
if (DbResult.BE_SQLITE_ERROR_SchemaLockFailed === stat) {
this.abandonChanges();
if (this.nativeDb.getITwinId() !== Guid.empty)
await this.acquireSchemaLock();
stat = this.nativeDb.importXmlSchemas(serializedXmlSchemas, { schemaLockHeld: true, schemaSyncDbUri });
}
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, "Error importing schema");
});
} else {
if (this.iTwinId && this.iTwinId !== Guid.empty) // if this iModel is associated with an iTwin, importing schema requires the schema lock
await this.acquireSchemaLock();
const stat = this.nativeDb.importXmlSchemas(serializedXmlSchemas, { schemaLockHeld: true });
if (DbResult.BE_SQLITE_OK !== stat)
throw new IModelError(stat, "Error importing schema");
}
this.clearCaches();
}
/** Find an opened instance of any subclass of IModelDb, by filename
* @note this method returns an IModelDb if the filename is open for *any* subclass of IModelDb
*/
public static findByFilename(fileName: LocalFileName): IModelDb | undefined {
for (const entry of this._openDbs) {
// It shouldn't be possible for anything in _openDbs to not be open, but if so just skip them because `pathName` will throw an exception.
if (entry[1].isOpen && entry[1].pathName === fileName)
return entry[1];
}
return undefined;
}
/** Find an open IModelDb by its key.
* @note This method is mainly for use by RPC implementations.
* @throws [[IModelNotFoundResponse]] if an open IModelDb matching the key is not found.
* @see [IModel.key]($common)
*/
public static findByKey(key: string): IModelDb {
const iModelDb = this.tryFindByKey(key);
if (undefined === iModelDb)
throw new IModelNotFoundResponse(); // a very specific status for the RpcManager
return iModelDb;
}
/** Attempt to find an open IModelDb by key.
* @returns The matching IModelDb or `undefined`.
*/
public static tryFindByKey(key: string): IModelDb | undefined {
return this._openDbs.get(key);
}
/** @internal */
public static openDgnDb(file: { path: LocalFileName, key?: string }, openMode: OpenMode, upgradeOptions?: UpgradeOptions, props?: SnapshotOpenOptions & CloudContainerArgs & OpenSqliteArgs): IModelJsNative.DgnDb {
file.key = file.key ?? Guid.createValue();
if (this.tryFindByKey(file.key))
throw new IModelError(IModelStatus.AlreadyOpen, `key [${file.key}] for file [${file.path}] is already in use`);
const isUpgradeRequested = upgradeOptions?.domain === DomainOptions.Upgrade || upgradeOptions?.profile === ProfileOptions.Upgrade;
if (isUpgradeRequested && openMode !== OpenMode.ReadWrite)
throw new IModelError(IModelStatus.UpgradeFailed, "Cannot upgrade a Readonly Db");
try {
const nativeDb = new IModelHost.platform.DgnDb();
const container = props?.container;
if (container) {
// temp files for cloud-based Dbs should be in the profileDir in a subdirectory named for their container
const baseDir = join(IModelHost.profileDir, "CloudDbTemp", container.containerId);
IModelJsFs.recursiveMkDirSync(baseDir);
props = { ...props, tempFileBase: join(baseDir, file.path) };
}
nativeDb.openIModel(file.path, openMode, upgradeOptions, props, props?.container, props);
return nativeDb;
} catch (err: any) {