-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathIModelDb.ts
More file actions
4416 lines (3965 loc) · 205 KB
/
Copy pathIModelDb.ts
File metadata and controls
4416 lines (3965 loc) · 205 KB
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, SchemaWriteStatus } from "@bentley/imodeljs-native";
import {
AccessToken, assert, BeEvent, BentleyStatus, ChangeSetStatus, DbChangeStage, DbConflictCause, DbConflictResolution, DbResult,
Guid, GuidString, Id64, Id64Arg, Id64Array, Id64Set, Id64String, IModelStatus, JsonUtils, Logger, LogLevel, LRUMap, OpenMode
} from "@itwin/core-bentley";
import {
AxisAlignedBox3d, BRepGeometryCreate, BriefcaseConnectionProps, BriefcaseId, BriefcaseIdValue, CategorySelectorProps, ChangesetHealthStats, ChangesetIdWithIndex, ChangesetIndexAndId, Code,
CodeProps, CreateEmptySnapshotIModelProps, CreateEmptyStandaloneIModelProps, CreateSnapshotIModelProps, DbQueryRequest, DisplayStyleProps,
DomainOptions, EcefLocation, ECJsNames, ECSchemaProps, ECSqlReader, EditTxnError, ElementAspectProps, ElementGeometryCacheOperationRequestProps, ElementGeometryCacheRequestProps, ElementGeometryCacheResponseProps, ElementGeometryRequest, ElementGraphicsRequestProps, ElementLoadProps, ElementProps, EntityMetaData, EntityProps, EntityQueryParams, FilePropertyProps,
FontMap, GeoCoordinatesRequestProps, GeoCoordinatesResponseProps, GeometryContainmentRequestProps, GeometryContainmentResponseProps, IModel,
IModelCoordinatesRequestProps, IModelCoordinatesResponseProps, IModelError, IModelNotFoundResponse, IModelTileTreeProps, LocalFileName,
MassPropertiesRequestProps, MassPropertiesResponseProps, ModelExtentsProps, ModelLoadProps, ModelProps, ModelSelectorProps, OpenBriefcaseProps,
OpenCheckpointArgs, OpenSqliteArgs, ProfileOptions, PropertyCallback, QueryBinder, QueryOptions, QueryRowFormat, SaveChangesArgs, SchemaState,
SheetProps, SnapRequestProps, SnapResponseProps, SnapshotOpenOptions, SpatialViewDefinitionProps, SubCategoryResultRow, TextureData,
TextureLoadProps, ThumbnailProps, UpgradeOptions, ViewDefinition2dProps, ViewDefinitionProps, ViewIdString, ViewQueryParams,
ViewStateLoadProps, ViewStateProps, ViewStoreError, ViewStoreRpc
} from "@itwin/core-common";
import { Range2d, Range3d } from "@itwin/core-geometry";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { BriefcaseManager, PullChangesArgs, PushChangesArgs, RevertChangesArgs } from "./BriefcaseManager";
import { ChannelControl, ChannelUpgradeOptions } from "./ChannelControl";
import { createChannelControl } from "./internal/ChannelAdmin";
import { CheckpointManager, CheckpointProps, V2CheckpointManager } from "./CheckpointManager";
import { ClassRegistry, EntityJsClassMap, 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 { ECSqlRow, 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 { createServerBasedLocks } from "./internal/ServerBasedLocks";
import { SqliteStatement, StatementCache } from "./SqliteStatement";
import { ComputeRangesForTextLayoutArgs, TextLayoutRanges } from "./annotations/TextBlockLayout";
import { TxnManager } from "./TxnManager";
import { EditTxn } from "./EditTxn";
import { DrawingViewDefinition, SheetViewDefinition, ViewDefinition } from "./ViewDefinition";
import { ViewStore } from "./ViewStore";
import { Setting, SettingsContainer, SettingsDictionary, SettingsPriority } from "./workspace/Settings";
import { Workspace, WorkspaceDbLoadError, WorkspaceDbLoadErrors, WorkspaceDbSettingsProps, WorkspaceSettingNames } from "./workspace/Workspace";
import { constructWorkspace, OwnedWorkspace, throwWorkspaceDbLoadErrors } from "./internal/workspace/WorkspaceImpl";
import { SettingsImpl } from "./internal/workspace/SettingsImpl";
import { DbMergeChangesetConflictArgs } from "./internal/ChangesetConflictArgs";
import { LockControl } from "./LockControl";
import { IModelNative } from "./internal/NativePlatform";
import type { BlobContainer } from "./BlobContainerService";
import { createNoOpLockControl } from "./internal/NoLocks";
import { IModelDbFonts } from "./IModelDbFonts";
import { createIModelDbFonts } from "./internal/IModelDbFontsImpl";
import { _activeTxn, _cache, _close, _hubAccess, _implicitTxn, _instanceKeyCache, _nativeDb, _releaseAllLocks, _resetIModelDb } from "./internal/Symbols";
import { ECVersion, SchemaContext, SchemaJsonLocater } from "@itwin/ecschema-metadata";
import { SchemaMap } from "./Schema";
import { ElementLRUCache, InstanceKeyLRUCache } from "./internal/ElementLRUCache";
import { IModelIncrementalSchemaLocater } from "./IModelIncrementalSchemaLocater";
import { ECSqlRowExecutor } from "./ECSqlRowExecutor";
import { IntegrityCheckKey, IntegrityCheckResult, integrityCheckTypeMap, performQuickIntegrityCheck, performSpecificIntegrityCheck } from "./internal/IntegrityCheck";
import { ECSqlSyncReader, SynchronousQueryOptions } from "./ECSqlSyncReader";
// spell:ignore fontid fontmap
const loggerCategory: string = BackendLoggerCategory.IModelDb;
/**
* Internal write surface used to preserve legacy implicit-transaction mutators while callers migrate to explicit [[EditTxn]] scopes.
*
* Unlike an explicit [[EditTxn]], this transaction is always available for writable iModels and cannot be manually started or ended.
* When implicit-write enforcement is enabled, attempts to write through this transaction are logged or rejected.
*/
class ImplicitWriteTxn extends EditTxn {
public constructor(iModel: IModelDb) {
super(iModel, "implicit");
}
public override start(): never {
throw new Error("ImplicitWriteTxn cannot be started");
}
public override end(_mode: "save" | "abandon" = "save", _args?: string | SaveChangesArgs): never {
throw new Error("ImplicitWriteTxn cannot be ended");
}
public override verifyWriteable(): void {
const enforcement = EditTxn.implicitWriteEnforcement;
if (enforcement === "allow")
return;
try {
EditTxnError.throwError("implicit-txn-write-disallowed", "Implicit transaction write is disallowed. Use an explicit EditTxn instead", this.iModel.key);
} catch (err) {
if (enforcement === "log") {
Logger.logError(loggerCategory, err);
return;
}
throw err;
}
}
}
/** 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 supposed to [[IModelDb.Elements.insertElement]].
* @public
*/
export interface InsertElementOptions {
/** If true, instead of assigning a new, unique Id to the inserted element, the inserted element will use the Id specified by the supplied [ElementProps]($common).
* This is chiefly useful when applying a filtering transformation - i.e., copying some elements from a source iModel to a target iModel and adding no new elements.
* If this option is `true` then [ElementProps.id]($common) must be a valid Id that is not already used by an element in the iModel.
* @beta
*/
forceUseId?: boolean;
}
/** Options supplied to [[IModelDb.clearCaches]].
* @beta
*/
export interface ClearCachesOptions {
/** If true, clear only instance caches. Otherwise, clear all caches. */
instanceCachesOnly?: 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;
}
/**
* Options for performing integrity checks on an iModel.
* @beta
*/
export interface IntegrityCheckOptions {
/** If true, perform a quick integrity check that only reports whether each check passed or failed, without detailed results. */
quickCheck?: boolean;
/** Options for performing specific integrity checks with detailed results. */
specificChecks?: {
/** If true, checks if all the required columns exist in data tables. Issues are returned as a list of those tables/columns. */
checkDataColumns?: boolean;
/** If true, checks if the profile table, indexes, and triggers are present. Does not check be_* tables. Issues are returned as a list of tables/indexes/triggers which were not found or have different DDL. */
checkECProfile?: boolean;
/** If true, checks if RelClassId of a Navigation property is a valid ECClassId. It does not check the value to match the relationship class. */
checkNavigationClassIds?: boolean;
/** If true, checks if Id of a Navigation property matches a valid row primary class. */
checkNavigationIds?: boolean;
/** If true, checks if SourceECClassId or TargetECClassId of a link table matches a valid ECClassId. */
checkLinktableForeignKeyClassIds?: boolean;
/** If true, checks if SourceECInstanceId or TargetECInstanceId of a link table matches a valid row in primary class. */
checkLinktableForeignKeyIds?: boolean;
/** If true, checks persisted ECClassId in all data tables and makes sure they are valid. */
checkClassIds?: boolean;
/** If true, checks if all the required data tables and indexes exist for mapped classes. Issues are returned as a list of tables/columns which were not found or have different DDL. */
checkDataSchema?: boolean;
/** If true, checks if all schemas can be loaded into memory. */
checkSchemaLoad?: boolean;
/** If true, checks if all child rows have a corresponding parent row. */
checkMissingChildRows?: boolean;
}
}
/**
* Options for the importing of schemas
* @public
*/
export interface SchemaImportOptions<T = any> {
/**
* 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;
/**
* Optional callbacks for pre/post schema import operations.
* @beta
*/
schemaImportCallbacks?: SchemaImportCallbacks;
/**
* Optional.
* Called before any schema import operations.
*
* Use this to prepare the channel for schema changes.
* This is where you should perform channel-specific upgrades that the schema import/upgrade might depend on.
*
* @note User is responsible to acquiring the necessary locks before performing the channel upgrades.
* @beta
*/
channelUpgrade?: ChannelUpgradeOptions;
/**
* Optional application-specific data to be used by the channel upgrade or the schema import callbacks.
* @beta
*/
data?: T
}
/** @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 an independent copy of the settings for those priorities.
*/
class IModelSettings extends SettingsImpl {
protected override verifyPriority(priority: SettingsPriority) {
if (priority <= SettingsPriority.application)
throw new Error("Use IModelHost.appSettings to access settings of priority 'application' or lower");
}
public override * getSettingEntries<T extends Setting>(name: string): Iterable<{ value: T, dictionary: SettingsDictionary }> {
yield* super.getSettingEntries(name);
yield* IModelHost.appWorkspace.settings.getSettingEntries(name);
}
}
/** Arguments supplied to [[IModelDb.exportSchema]] specifying which ECSchema to write to what location on the local file system.
* @beta
*/
export interface ExportSchemaArgs {
/** The name of the ECSchema to export. */
schemaName: string;
/** The directory in which to place the created schema file. */
outputDirectory: LocalFileName;
/** Optionally, the name of the file to create in [[outputDirectory]].
* Defaults to <SchemaName>.<SchemaVersion>.ecschema.xml
*/
outputFileName?: string;
}
/** Arguments supplied to [[IModelDb.simplifyElementGeometry]].
* @beta
*/
export interface SimplifyElementGeometryArgs {
/** The Id of the [[GeometricElement]] or [[GeometryPart]] whose geometry is to be simplified. */
id: Id64String;
/** If true, simplify by converting each [BRepEntity]($common) in the element's geometry stream to a high-resolution
* mesh or curve geometry.
*/
convertBReps?: boolean;
}
/** The output of [[IModelDb.inlineGeometryParts]].
* If [[numCandidateParts]], [[numRefsInlined]], and [[numPartsDeleted ]] are all the same, the operation was fully successful.
* Otherwise, some errors occurred inlining and/or deleting one or more parts.
* A part will not be deleted unless it is first successfully inlined.
* @beta
*/
export interface InlineGeometryPartsResult {
/** The number of parts that were determined to have exactly one reference, making them candidates for inlining. */
numCandidateParts: number;
/** The number of part references successfully inlined. */
numRefsInlined: number;
/** The number of candidate parts that were successfully deleted after inlining. */
numPartsDeleted: number;
}
/**
* Strategy for transforming data during schema import.
* @beta
*/
export enum DataTransformationStrategy {
/** No data transformation will be performed after schema import. */
None = "None",
/** Data transformation will be performed using a temporary snapshot created before schema import.
* Useful for complex transformations requiring full read access to complete pre-import state for lazy conversion.
* Note: Creates a complete copy of the briefcase file, which may be large.
*/
Snapshot = "Snapshot",
/** Data transformation will be performed using in-memory cached data created before schema import.
* Useful for lightweight transformations involving limited data.
*/
InMemory = "InMemory",
}
/**
* Context provided to the beforeImport callback.
* @beta
*/
export interface PreImportContext<T = any> {
/** The iModel being modified */
iModel: IModelDb;
/** Schemas about to be imported */
schemaData: LocalFileName[] | string[];
/** Optional user-provided data for pre-import operations */
data?: T;
}
/**
* Result of the pre-import callback.
* @beta
*/
export interface PreImportCallbackResult<T = any> {
transformStrategy: DataTransformationStrategy;
/** Optional cached data for in-memory strategy */
cachedData?: T;
}
/**
* Resources available for after schema import data transformation.
* @beta
*/
export interface DataTransformationResources extends PreImportCallbackResult {
/** Optional snapshot for snapshot strategy */
snapshot?: SnapshotDb;
}
/**
* Context provided to the afterImport callback.
* @beta
*/
export interface PostImportContext<T = any> {
/** The iModel being modified */
iModel: IModelDb;
/** Resources for data transformation */
resources: DataTransformationResources;
/** Optional user-provided data for post-import operations */
data?: T;
}
/**
* Callbacks for schema import operations.
* @beta
*/
export interface SchemaImportCallbacks<T = any> {
/**
* Will be executed before schemas are imported but after channel upgrades.
* Use this to make any pre import changes to the iModel or use it to cache data or create snapshots for data transformation after the schema import/upgrade.
*
* @note User is responsible to acquiring the necessary locks before making any changes.
*
* @returns Strategy and optional cached data for transformation
*/
preSchemaImportCallback?: (context: PreImportContext) => Promise<PreImportCallbackResult<T>>;
/**
* Will be executed after schemas are imported, while schema lock is still held.
* Use this to transform data to match the new schema.
*
* @note Schema lock is already held after doing a schema import. No lock acquisition is necessary by the user.
*
* @throws If transformation fails, any changes done after the schema import are abandoned and snapshot is cleared.
*/
postSchemaImportCallback?: (context: PostImportContext) => Promise<void>;
}
/** Options for closing an iModelDb.
* @public
*/
export interface CloseIModelArgs {
/** Runs the Sqlite vacuum and analyze commands before closing to defragment the database and update query optimizer statistics */
optimize?: boolean;
}
/** 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 = createChannelControl(this);
private _relationships?: Relationships;
// eslint-disable-next-line @typescript-eslint/no-deprecated
private readonly _statementCache = new StatementCache<ECSqlStatement>();
private readonly _sqliteStatementCache = new StatementCache<SqliteStatement>();
private _codeSpecs?: CodeSpecs;
// eslint-disable-next-line @typescript-eslint/no-deprecated
private _classMetaDataRegistry?: MetaDataRegistry;
private _jsClassMap?: EntityJsClassMap;
private _schemaMap?: SchemaMap;
private _schemaContext?: SchemaContext;
/** @deprecated in 5.0.0 - will not be removed until after 2026-06-13. Use [[fonts]]. */
protected _fontMap?: FontMap; // eslint-disable-line @typescript-eslint/no-deprecated
private readonly _fonts: IModelDbFonts = createIModelDbFonts(this);
private _workspace?: OwnedWorkspace;
private readonly _snaps = new Map<string, IModelJsNative.SnapRequest>();
private static _shutdownListener: VoidFunction | undefined; // so we only register listener once
/** @internal */
protected _locks?: LockControl = createNoOpLockControl();
/** @internal */
protected _codeService?: CodeService;
/**
* The always-available implicit transaction for this iModel.
*
* Legacy mutating APIs route through this transaction for backwards compatibility until they are fully migrated to explicit [[EditTxn]] usage.
* @internal
*/
public readonly [_implicitTxn]: EditTxn;
/** @internal */
public [_activeTxn]: EditTxn | undefined;
/** Returns the active [[EditTxn]] if one is current, otherwise the implicit transaction.
* Use this inside element and relationship callbacks that may be invoked either during an explicit transaction or
* during indirect change processing.
* @note This method is a temporary workaround until [[OnElementArg]] (and related callback arg types) are updated
* to carry the transaction directly in a future PR.
* @internal
*/
public getIndirectTxn(): EditTxn {
return this[_activeTxn] ?? this[_implicitTxn];
}
/** @alpha */
public get codeService() { return this._codeService; }
/** The [[LockControl]] that orchestrates [concurrent editing]($docs/learning/backend/ConcurrencyControl.md) of this iModel. */
public get locks(): LockControl { return this._locks!; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
/** Provides methods for interacting with [font-related information]($docs/learning/backend/Fonts.md) stored in this iModel.
* @beta
*/
public get fonts(): IModelDbFonts { return this._fonts; }
/**
* Get the [[Workspace]] for this iModel.
* @beta
*/
public get workspace(): Workspace {
if (undefined === this._workspace)
this._workspace = constructWorkspace(new IModelSettings());
return this._workspace;
}
/**
* get the cloud container for this iModel, if it was opened from one
* @beta
*/
public get cloudContainer(): CloudSqlite.CloudContainer | undefined {
return this[_nativeDb].cloudContainer;
}
/** 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();
}
/** @deprecated in 5.0.0 - will not be removed until after 2026-06-13. Use [[fonts]]. */
public get fontMap(): FontMap { // eslint-disable-line @typescript-eslint/no-deprecated
return this._fontMap ?? (this._fontMap = new FontMap(this[_nativeDb].readFontMap())); // eslint-disable-line @typescript-eslint/no-deprecated
}
/** @internal */
public clearFontMap(): void {
this._fontMap = undefined; // eslint-disable-line @typescript-eslint/no-deprecated
this[_nativeDb].invalidateFontMap();
}
/** 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[_nativeDb].saveChanges(); // preserve old behavior of closeIModel that was removed when renamed to closeFile
this[_activeTxn] = undefined;
this[_nativeDb].closeFile();
};
this[_nativeDb].setIModelDb(this);
this[_resetIModelDb]();
IModelDb._openDbs.set(this._fileKey, this);
this[_implicitTxn] = new ImplicitWriteTxn(this);
this[_activeTxn] = undefined;
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[_nativeDb].abandonChanges();
db.close();
} catch { }
});
});
}
}
/** @internal */
public [_resetIModelDb]() {
this.loadIModelSettings();
GeoCoordConfig.loadForImodel(this.workspace.settings); // load gcs data specified by iModel's settings dictionaries, must be done before calling initializeIModelDb
this.initializeIModelDb();
}
/**
* Attach an iModel file to this connection and load and register its schemas.
* @note There are some reserve tablespace names that cannot be used. They are 'main', 'schema_sync_db', 'ecchange' & 'temp'
* @param fileName IModel file name
* @param alias identifier for the attached file. This identifier is used to access schema from the attached file. e.g. if alias is 'abc' then schema can be accessed using 'abc.MySchema.MyClass'
* @example
* [[include:IModelDb_attachDb.code]]
*/
public attachDb(fileName: string, alias: string): void {
if (alias.toLowerCase() === "main" || alias.toLowerCase() === "schema_sync_db" || alias.toLowerCase() === "ecchange" || alias.toLowerCase() === "temp") {
throw new IModelError(DbResult.BE_SQLITE_ERROR, "Reserved tablespace name cannot be used");
}
this[_nativeDb].attachDb(fileName, alias);
}
/**
* Detach the attached file from this connection. The attached file is closed and its schemas are unregistered.
* @note There are some reserved table names that cannot be used. They are 'main', 'schema_sync_db', 'ecchange' & 'temp'
* @param alias identifier that was used in the call to [[attachDb]]
*
* @example [[include:IModelDb_attachDb.code]]
*
*/
public detachDb(alias: string): void {
if (alias.toLowerCase() === "main" || alias.toLowerCase() === "schema_sync_db" || alias.toLowerCase() === "ecchange" || alias.toLowerCase() === "temp") {
throw new IModelError(DbResult.BE_SQLITE_ERROR, "Reserved tablespace name cannot be used");
}
this.clearCaches();
this[_nativeDb].detachDb(alias);
}
/** Close this IModel, if it is currently open, and save changes if it was opened in ReadWrite mode.
* @param options Options for closing the iModel.
*/
public close(options?: CloseIModelArgs): void {
if (!this.isOpen)
return; // don't continue if already closed
// Give the active txn a chance to save or abandon before beforeClose() cleanup runs.
// StandaloneDb.beforeClose() saves any unsaved changes, so onClose() must run first so
// subclasses that override onClose() to abandon changes can do so before that save.
if (!this.isReadonly)
(this[_activeTxn] ?? this[_implicitTxn]).onClose();
this.beforeClose();
this[_activeTxn] = undefined;
if (options?.optimize)
this.optimize();
IModelDb._openDbs.delete(this._fileKey);
this._workspace?.close();
this.locks[_close]();
this._locks = undefined;
this._codeService?.close();
this._codeService = undefined;
this[_nativeDb].closeFile();
}
private saveSchemaChanges(args?: string): void {
if (!this[_nativeDb].hasUnsavedChanges())
return;
const saveArgs = typeof args === "string" ? { description: args } : args;
saveArgs === undefined ? this[_nativeDb].saveChanges() : this[_nativeDb].saveChanges(JSON.stringify(saveArgs));
}
private abandonSchemaChanges(): void {
if (!this[_nativeDb].hasUnsavedChanges())
return;
this.clearCaches({ instanceCachesOnly: true });
this[_nativeDb].abandonChanges();
}
/** Optimize this iModel by vacuuming, and analyzing.
*
* @note This operation requires exclusive access to the database and may take some time on large files.
* @beta
*/
public optimize(): void {
// Vacuum to reclaim space and defragment
this.vacuum();
// Analyze to update statistics for query optimizer
this.analyze();
}
/**
* Vacuum the model to reclaim space and defragment.
* @throws [[IModelError]] if the iModel is not open or is read-only.
* @beta
*/
public vacuum(): void {
if (!this.isOpen || this.isReadonly)
throw new IModelError(IModelStatus.BadRequest, "IModel is not open or is read-only");
this[_nativeDb].clearECDbCache();
this[_nativeDb].vacuum();
}
/**
* Update SQLite query optimizer statistics for this iModel.
* This helps SQLite choose better query plans.
*
* @throws [[IModelError]] if the iModel is not open or is read-only.
* @beta
*/
public analyze() {
if (!this.isOpen || this.isReadonly)
throw new IModelError(IModelStatus.BadRequest, "IModel is not open or is read-only");
this[_nativeDb].analyze();
}
/**
* Performs integrity checks on this iModel.
* Types of integrity checks that can be performed are:
*
* Default Check:
* - Quick Check: Runs all integrity checks below and returns whether each check passed or failed, without detailed results.
*
* Specific Checks:
* - Data Columns Check: Checks if all the required columns exist in data tables. Issues are returned as a list of those tables/columns.
* - EC Profile Check: Checks if the profile table, indexes, and triggers are present. Does not check be_* tables. Issues are returned as a list of tables/indexes/triggers which were not found or have different DDL.
* - Navigation Class Ids Check: Checks if RelClassId of a Navigation property is a valid ECClassId. It does not check the value to match the relationship class.
* - Navigation Ids Check: Checks if Id of a Navigation property matches a valid row primary class.
* - Linktable Foreign Key Class Ids Check: Checks if SourceECClassId or TargetECClassId of a link table matches a valid ECClassId.
* - Linktable Foreign Key Ids Check: Checks if SourceECInstanceId or TargetECInstanceId of a link table matches a valid row in primary class.
* - Class Ids Check: Checks persisted ECClassId in all data tables and makes sure they are valid.
* - Data Schema Check: Checks if all the required data tables and indexes exist for mapped classes. Issues are returned as a list of tables/columns which were not found or have different DDL.
* - Schema Load Check: Checks if all schemas can be loaded into memory.
* - Missing Child Rows Check: Checks if all child rows have a corresponding parent row.
*
* @param options Options specifying which integrity checks to perform. If no options are provided or all options are false, a quick check will be performed by default.
* @returns An array of integrity check results.
* @throws [[IModelError]] if the iModel is not open.
* @beta
*/
public async integrityCheck(options?: IntegrityCheckOptions): Promise<IntegrityCheckResult[]> {
if (!this.isOpen)
throw new IModelError(IModelStatus.BadRequest, "IModel is not open");
// Default to quick check if no options provided at all, or if not explicitly set and no specific checks are enabled
if (!options || (!options.quickCheck && (!options.specificChecks || !Object.values(options.specificChecks).some(Boolean)))) {
options = { ...options, quickCheck: true };
}
const integrityCheckResults: IntegrityCheckResult[] = [];
// Perform a quick check if requested
if (options.quickCheck) {
const results = await performQuickIntegrityCheck(this);
const passed = results.every((result) => result.passed);
integrityCheckResults.push({ check: "Quick Check", passed, results });
}
// Perform all specific checks requested
if (options.specificChecks) {
for (const [checkKey, checkParams] of Object.entries(integrityCheckTypeMap)) {
if (options.specificChecks[checkKey as keyof typeof options.specificChecks]) {
const results = await performSpecificIntegrityCheck(this, checkKey as IntegrityCheckKey);
const passed = results.length === 0;
integrityCheckResults.push({ check: checkParams.name, passed, results });
}
}
}
return integrityCheckResults;
}
/** @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(when?: "pullMerge") {
const props = this[_nativeDb].getIModelProps(when);
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
* @deprecated in 4.11 - will not be removed until after 2026-06-13. Use [[createQueryReader]] instead.
*/
// eslint-disable-next-line @typescript-eslint/no-deprecated
public withPreparedStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors = true): T {
// eslint-disable-next-line @typescript-eslint/no-deprecated
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
* @deprecated in 4.11 - will not be removed until after 2026-06-13. Use [[createQueryReader]] instead.
*/
// eslint-disable-next-line @typescript-eslint/no-deprecated
public withStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors = true): T {
// eslint-disable-next-line @typescript-eslint/no-deprecated
const stmt = this.prepareStatement(ecsql, logErrors);
const release = () => stmt[Symbol.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.
* Should be used when we donot want true step by step behaviour and want to take advantage of caching capabilities of the reader.
* @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);
}
/** Allow to execute query and read results along with meta data. The result are stepped one by one.
*
* See also:
* - [ECSQL Overview]($docs/learning/backend/ExecutingECSQL)
* - [Code Examples]($docs/learning/backend/ECSQLCodeExamples)
* - [ECSQL Row Format]($docs/learning/ECSQLRowFormat)
* @param ecsql The ECSQL query to execute.
* @param callback the callback to invoke on the prepared ECSqlReader
* @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 the value returned by `callback`.
* @throws IModelError if db is not open.
* Should be used when we want true step by step behaviour from the reader without any intermediate caching involved.
* @beta
* */
public withQueryReader<T>(ecsql: string, callback: (reader: ECSqlSyncReader) => T, params?: QueryBinder, config?: SynchronousQueryOptions): T {
if (!this[_nativeDb].isOpen())
throw new IModelError(DbResult.BE_SQLITE_ERROR, "db not open");
const executor = new ECSqlRowExecutor(this);
const reader = new ECSqlSyncReader(executor, ecsql, params, config);
const release = () => executor[Symbol.dispose]();
try {
const val = callback(reader);
if (val instanceof Promise) {
val.then(release, release);
} else {
release();
}
return val;
} catch (err: any) {
release();
throw err;
}
}
/**
* 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 {