UNPKG

@itwin/core-backend

Version:
920 lines • 113 kB
/** @packageDocumentation * @module iModels */ import { IModelJsNative } from "@bentley/imodeljs-native"; import { AccessToken, BeEvent, BentleyStatus, DbResult, GuidString, Id64Arg, Id64Array, Id64Set, Id64String, IModelStatus, LRUMap, OpenMode } from "@itwin/core-bentley"; import { AxisAlignedBox3d, BRepGeometryCreate, BriefcaseConnectionProps, BriefcaseId, ChangesetHealthStats, ChangesetIdWithIndex, Code, CodeProps, CreateEmptySnapshotIModelProps, CreateEmptyStandaloneIModelProps, CreateSnapshotIModelProps, EcefLocation, ECSchemaProps, ECSqlReader, ElementAspectProps, ElementGeometryCacheOperationRequestProps, ElementGeometryCacheRequestProps, ElementGeometryCacheResponseProps, ElementGeometryRequest, ElementGraphicsRequestProps, ElementLoadProps, ElementProps, EntityMetaData, EntityProps, EntityQueryParams, FilePropertyProps, FontMap, GeoCoordinatesRequestProps, GeoCoordinatesResponseProps, GeometryContainmentRequestProps, GeometryContainmentResponseProps, IModel, IModelCoordinatesRequestProps, IModelCoordinatesResponseProps, IModelTileTreeProps, LocalFileName, MassPropertiesRequestProps, MassPropertiesResponseProps, ModelExtentsProps, ModelProps, OpenBriefcaseProps, OpenCheckpointArgs, OpenSqliteArgs, PropertyCallback, QueryBinder, QueryOptions, SaveChangesArgs, SchemaState, SnapRequestProps, SnapResponseProps, SnapshotOpenOptions, SubCategoryResultRow, TextureData, TextureLoadProps, ThumbnailProps, UpgradeOptions, ViewDefinitionProps, ViewIdString, ViewQueryParams, ViewStateLoadProps, ViewStateProps } from "@itwin/core-common"; import { Range3d } from "@itwin/core-geometry"; import { PullChangesArgs, PushChangesArgs, RevertChangesArgs } from "./BriefcaseManager"; import { ChannelControl, ChannelUpgradeOptions } from "./ChannelControl"; import { CheckpointProps } from "./CheckpointManager"; import { EntityJsClassMap, MetaDataRegistry } from "./ClassRegistry"; import { CloudSqlite } from "./CloudSqlite"; import { CodeService } from "./CodeService"; import { CodeSpecs } from "./CodeSpecs"; import { ECSchemaXmlContext } from "./ECSchemaXmlContext"; import { ECSqlStatement } from "./ECSqlStatement"; import { Element, Subject } from "./Element"; import { ElementAspect } from "./ElementAspect"; import { Entity, EntityClassType } from "./Entity"; import { ExportGraphicsOptions, ExportPartGraphicsOptions } from "./ExportGraphics"; import { Model } from "./Model"; import { Relationships } from "./Relationship"; import { SqliteStatement } from "./SqliteStatement"; import { ComputeRangesForTextLayoutArgs, TextLayoutRanges } from "./annotations/TextBlockLayout"; import { TxnManager } from "./TxnManager"; import { BulkDeleteElementsArgs, BulkDeleteElementsResult, EditTxn } from "./EditTxn"; import { ViewDefinition } from "./ViewDefinition"; import { ViewStore } from "./ViewStore"; import { SettingsContainer } from "./workspace/Settings"; import { Workspace } from "./workspace/Workspace"; import { LockControl } from "./LockControl"; import type { BlobContainer } from "./BlobContainerService"; import { IModelDbFonts } from "./IModelDbFonts"; import { _activeTxn, _cache, _implicitTxn, _instanceKeyCache, _nativeDb, _resetIModelDb } from "./internal/Symbols"; import { ECSpecVersion, ECVersion, type GetSchemaViewArgs, SchemaContext, SchemaView } from "@itwin/ecschema-metadata"; import { SchemaMap } from "./Schema"; import { ElementLRUCache, InstanceKeyLRUCache } from "./internal/ElementLRUCache"; import { IntegrityCheckResult } from "./internal/IntegrityCheck"; import { ECSqlSyncReader, SynchronousQueryOptions } from "./ECSqlSyncReader"; /** 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 for [[EditTxn.changeElementParent]]. * Changes the parent of an element within its model. The new parent must be in the same model as the * element; cross-model reparenting is not allowed. * * See [[EditTxn.changeElementParent]] for the allowed and blocked cases. * @beta */ export interface ChangeElementParentProps { /** The Id of the element to reparent. */ id: Id64String; /** The Id of the new parent element. Must be in the same model as the element. */ parentId: Id64String; } /** Options for [[EditTxn.changeElementModel]]. * Changes the model of a root element (one with no parent), making it a root element in the new model. * The element's entire subtree moves with it, preserving the parent-child hierarchy. * * See [[EditTxn.changeElementModel]] for the allowed and blocked cases. * @beta */ export interface ChangeElementModelProps { /** The Id of the element to move. Must be a root element (no parent). */ id: Id64String; /** The Id of the target model. The element becomes a root element (no parent) in this model. */ modelId: Id64String; } /** 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 declare enum BriefcaseLocalValue { StandaloneEdit = "StandaloneEdit", NoLocking = "NoLocking" } /** 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 declare 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 declare abstract class IModelDb extends IModel { private _initialized; /** Keep track of open imodels to support `tryFind` for RPC purposes */ private static readonly _openDbs; static readonly defaultLimit = 1000; static readonly maxLimit = 10000; readonly models: IModelDb.Models; readonly elements: IModelDb.Elements; readonly views: IModelDb.Views; readonly tiles: IModelDb.Tiles; /** @beta */ readonly channels: ChannelControl; private _relationships?; private readonly _statementCache; private readonly _sqliteStatementCache; private _codeSpecs?; private _classMetaDataRegistry?; private _jsClassMap?; private _schemaMap?; private _schemaContext?; private _schemaViewManager?; /** @deprecated in 5.0.0 - might be removed in next major version. Use [[fonts]]. */ protected _fontMap?: FontMap; private readonly _fonts; private _workspace?; private readonly _snaps; private static _shutdownListener; /** @internal */ protected _locks?: LockControl; /** @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 */ readonly [_implicitTxn]: EditTxn; /** @internal */ [_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 */ getIndirectTxn(): EditTxn; /** @alpha */ get codeService(): CodeService | undefined; /** The [[LockControl]] that orchestrates [concurrent editing]($docs/learning/backend/ConcurrencyControl.md) of this iModel. */ get locks(): LockControl; /** Provides methods for interacting with [font-related information]($docs/learning/backend/Fonts.md) stored in this iModel. * @beta */ get fonts(): IModelDbFonts; /** * Get the [[Workspace]] for this iModel. * @beta */ get workspace(): Workspace; /** * get the cloud container for this iModel, if it was opened from one * @beta */ get cloudContainer(): CloudSqlite.CloudContainer | undefined; /** 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. */ acquireSchemaLock(): Promise<void>; /** determine whether the schema lock is currently held for this iModel. */ get holdsSchemaLock(): boolean; /** Event called after a changeset is applied to this IModelDb. */ readonly onChangesetApplied: BeEvent<() => void>; /** @internal */ notifyChangesetApplied(): void; /** @internal */ restartDefaultTxn(): void; /** @deprecated in 5.0.0 - might be removed in next major version. Use [[fonts]]. */ get fontMap(): FontMap; /** @internal */ clearFontMap(): void; /** Check if this iModel has been opened read-only or not. */ get isReadonly(): boolean; /** The Guid that identifies this iModel. */ get iModelId(): GuidString; /** @internal*/ readonly [_nativeDb]: IModelJsNative.DgnDb; /** Get the full path fileName of this iModelDb * @note this member is only valid while the iModel is opened. */ get pathName(): LocalFileName; /** 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 */ get watchFilePathName(): LocalFileName; /** @internal */ protected constructor(args: { nativeDb: IModelJsNative.DgnDb; key: string; changeset?: ChangesetIdWithIndex; }); /** @internal */ [_resetIModelDb](): void; /** * 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]] */ attachDb(fileName: string, alias: string): void; /** * 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]] * */ detachDb(alias: string): void; /** 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. */ close(options?: CloseIModelArgs): void; private saveSchemaChanges; private abandonSchemaChanges; /** 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 */ optimize(): void; /** * Vacuum the model to reclaim space and defragment. * @throws [[IModelError]] if the iModel is not open or is read-only. * @beta */ vacuum(): void; /** * 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 */ analyze(): void; /** * 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 */ integrityCheck(options?: IntegrityCheckOptions): Promise<IntegrityCheckResult[]>; /** @internal */ refreshContainerForRpc(_userAccessToken: AccessToken): Promise<void>; /** Event called when the iModel is about to be closed. */ readonly onBeforeClose: BeEvent<() => void>; /** * Called by derived classes before closing the connection * @internal */ protected beforeClose(): void; /** @internal */ protected initializeIModelDb(when?: "pullMerge"): void; /** Returns true if this is a BriefcaseDb * @see [[BriefcaseDb.open]] */ get isBriefcase(): boolean; /** Type guard for instanceof [[BriefcaseDb]] */ isBriefcaseDb(): this is BriefcaseDb; /** Returns true if this is a SnapshotDb * @see [[SnapshotDb.open]] */ get isSnapshot(): boolean; /** Type guard for instanceof [[SnapshotDb]] */ isSnapshotDb(): this is SnapshotDb; /** Returns true if this is a *standalone* iModel * @see [[StandaloneDb.open]] * @internal */ get isStandalone(): boolean; /** Type guard for instanceof [[StandaloneDb]]. */ isStandaloneDb(): this is StandaloneDb; /** Return `true` if the underlying nativeDb is open and valid. * @internal */ get isOpen(): boolean; /** Get the briefcase Id of this iModel */ getBriefcaseId(): BriefcaseId; /** * 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 - might be removed in next major version. Use [[createQueryReader]] instead. */ withPreparedStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors?: boolean): T; /** * 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 - might be removed in next major version. Use [[createQueryReader]] instead. */ withStatement<T>(ecsql: string, callback: (stmt: ECSqlStatement) => T, logErrors?: boolean): T; /** 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 * */ createQueryReader(ecsql: string, params?: QueryBinder, config?: QueryOptions): ECSqlReader; /** 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. * Use this method for true step-by-step row consumption without intermediate result or page caching. * The prepared ECSQL statement may be reused from the statement cache between completed calls. * @beta * */ withQueryReader<T>(ecsql: string, callback: (reader: ECSqlSyncReader) => T, params?: QueryBinder, config?: SynchronousQueryOptions): T; /** * 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 */ withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T, logErrors?: boolean): T; /** * 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 */ withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T, logErrors?: boolean): T; /** Prepare an SQL statement. * @param sql The SQL statement to prepare * @throws [[IModelError]] if there is a problem preparing the statement. * @internal */ prepareSqliteStatement(sql: string, logErrors?: boolean): SqliteStatement; /** * queries the BisCore.SubCategory table for entries that are children of used spatial categories and 3D elements. * @returns array of SubCategoryResultRow * @internal */ queryAllUsedSpatialSubCategories(): Promise<SubCategoryResultRow[]>; /** * 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 */ querySubCategories(categoryIds: Iterable<Id64String>): Promise<SubCategoryResultRow[]>; /** 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]] * ``` */ queryEntityIds(params: EntityQueryParams): Id64Set; /** Clear all in-memory caches held in this IModelDb. * @public */ clearCaches(): void; /** Clear all in-memory caches held in this IModelDb. * @param params Options that control which caches to clear. If not specified, all caches are cleared. * @beta */ clearCaches(params?: ClearCachesOptions): void; /** Update the project extents for this iModel. * <p><em>Example:</em> * ``` ts * [[include:IModelDb.updateProjectExtents]] * ``` * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.updateProjectExtents instead, within an explicit EditTxn scope (or via withEditTxn). See EditTxn documentation for migration help. */ updateProjectExtents(newExtents: AxisAlignedBox3d): void; /** 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]]. */ computeProjectExtents(options?: ComputeProjectExtentsOptions): ComputedProjectExtents; /** Update the [EcefLocation]($docs/learning/glossary#eceflocation) of this iModel. * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.updateEcefLocation instead, within an explicit EditTxn scope (or via withEditTxn). See EditTxn documentation for migration help. */ updateEcefLocation(ecef: EcefLocation): void; /** Update the IModelProps of this iModel in the database. * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.updateIModelProps instead, within an explicit EditTxn scope (or via withEditTxn). */ updateIModelProps(): void; /** Commit unsaved changes in memory as a Txn to this iModelDb. * @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. * @note This will not push changes to the iModelHub. * @note This method should not be called from {TxnManager.withIndirectTxnModeAsync}, {TxnManager.withIndirectTxnMode} or {RebaseHandler.recompute}. * @see [[IModelDb.pushChanges]] to push changes to the iModelHub. * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.saveChanges instead, within an explicit EditTxn scope (or via withEditTxn). See EditTxn documentation for migration help. */ saveChanges(description?: string): void; /** Commit unsaved changes in memory as a Txn to this iModelDb. This is preferable for case where application like to store additional structured information with the change that could be useful later when rebasing. * @alpha * @param args Provide [[SaveChangesArgs]] of the changes. * @throws [[IModelError]] if there is a problem saving changes or if there are pending, un-processed lock or code requests. * @note This will not push changes to the iModelHub. * @note This method should not be called from {TxnManager.withIndirectTxnModeAsync}, {TxnManager.withIndirectTxnMode} or {RebaseHandler.recompute}. * @see [[IModelDb.pushChanges]] to push changes to the iModelHub. * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.saveChanges instead, within an explicit EditTxn scope (or via withEditTxn). See EditTxn documentation for migration help. */ saveChanges(args: SaveChangesArgs): void; /** Abandon changes in memory that have not been saved as a Txn to this iModelDb. * @deprecated in 5.9.0 - will not be removed until after 2027-05-04. Use EditTxn.abandonChanges instead, within an explicit EditTxn scope (or via withEditTxn). See EditTxn documentation for migration help. */ abandonChanges(): void; /** * 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. */ performCheckpoint(): void; /** @internal * @deprecated in 4.8 - might be removed in next major version. Use `txns.reverseTxns`. */ reverseTxns(numOperations: number): IModelStatus; /** @internal */ reinstateTxn(): IModelStatus; /** @internal */ restartTxnSession(): void; /** * Get the class full name from a class Id. * @param classId the Id of the class to look up * @returns the full name of the class (e.g. "BisCore:Element") * @throws IModelError if the classId is invalid or the class is not found. * @internal */ getClassNameFromId(classId: string): Id64String; /** Removes unused schemas from the database. * * If the removal was successful, the database is automatically saved to disk. * @param schemaNames Array of schema names to drop * @throws [[IModelError]] if the operation fails. * @alpha */ dropSchemas(schemaNames: string[]): Promise<void>; /** Helper to clean up snapshot resources safely * @internal */ private cleanupSnapshot; private preSchemaImportCallback; private postSchemaImportCallback; /** Shared implementation for importing schemas from file or string. */ private importSchemasInternal; /** Import ECSchema(s). 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 schemaFileNames Files containing serialized ECSchemas. * @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. * @note To turn on native logging, use NativeLoggerCategory and a console appender. * - For metadata differences between existing and imported schemas, turn on "ECDb" category. * - For import details, turn on "SchemaImport" category. * - You can use NativeLoggerCategory to turn on the native logs. You can also control [what exactly is logged by the loggers](https://www.itwinjs.org/learning/common/logging/#controlling-what-is-logged). * - See [Schema Versioning]($docs/bis/guide/schema-evolution/schema-versioning-and-generations.md) for more information on acceptable changes to schemas. * @note This method should not be called from {TxnManager.withIndirectTxnModeAsync} or {RebaseHandler.recompute}. * @see querySchemaVersion */ importSchemas(schemaFileNames: LocalFileName[], options?: SchemaImportOptions): Promise<void>; /** 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. * @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 importSchemaStrings is successful and abandoned if not successful. * @note This method should not be called from {TxnManager.withIndirectTxnModeAsync} or {RebaseHandler.recompute}. * @see querySchemaVersion * @alpha */ importSchemaStrings(serializedXmlSchemas: string[], options?: SchemaImportOptions): Promise<void>; /** 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 */ static findByFilename(fileName: LocalFileName): IModelDb | 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) */ static findByKey(key: string): IModelDb; /** Attempt to find an open IModelDb by key. * @returns The matching IModelDb or `undefined`. */ static tryFindByKey(key: string): IModelDb | undefined; /** @internal */ static openDgnDb(file: { path: LocalFileName; key?: string; }, openMode: OpenMode, upgradeOptions?: UpgradeOptions, props?: SnapshotOpenOptions & CloudContainerArgs & OpenSqliteArgs): IModelJsNative.DgnDb; /** * Determines if the schemas in the Db must or can be upgraded by comparing them with those included in the * current version of the software. * @param filePath Full name of the briefcase including path * @param forReadWrite Pass true if validating for read-write scenarios - note that the schema version requirements * for opening the DgnDb read-write is more stringent than when opening the database read-only * @throws [[IModelError]] If the Db was in an invalid state and that causes a problem with validating schemas * @see [[BriefcaseDb.upgradeSchemas]] or [[StandaloneDb.upgradeSchemas]] * @see ($docs/learning/backend/IModelDb.md#upgrading-schemas-in-an-imodel) */ static validateSchemas(filePath: LocalFileName, forReadWrite: boolean): SchemaState; /** The registry of entity metadata for this iModel. * @internal * @deprecated in 5.0 - might be removed in next major version. Use `getSchemaView()` from the `iModel` instead. * * @example * ```typescript * // Current usage: * const classMetaData: EntityMetaData | undefined = iModel.classMetaDataRegistry.find("SchemaName:ClassName"); * * // Replacement: * const view = await imodel.getSchemaView(); * const cls = view.findClass("SchemaName:ClassName"); * ``` */ get classMetaDataRegistry(): MetaDataRegistry; /** * Allows registering js classes mapped to ECClasses */ get jsClassMap(): EntityJsClassMap; /** * Allows locally registering a schema for this imodel, in contrast to [Schemas.registerSchema] which is a global operation */ get schemaMap(): SchemaMap; /** * Gets the context that allows accessing the metadata (`@itwin/ecschema-metadata` package) of this iModel. * * For runtime read-only access - class/property iteration, IS-A checks, navigating relationships, KOQ lookups - * prefer [[getSchemaView]]. `schemaContext` remains the right choice when you need schema authoring * (via `@itwin/ecschema-editing`), custom-attribute deserialization, or the full ecschema-metadata object graph. * @public @preview */ get schemaContext(): SchemaContext; /** Get the schema view for this iModel. The view is built lazily on * first call by fetching compact binary schema data through * the ConcurrentQuery thread pool. * * The returned `SchemaView` is a lightweight, read-only, synchronous API for * navigating schema metadata - classes, properties, relationships, enumerations, etc. * It is the recommended default for runtime read-only metadata access and is significantly * faster and lower-memory than [[schemaContext]]. Use [[schemaContext]] for schema authoring, * custom-attribute deserialization, or anywhere you need the full ecschema-metadata object graph. * * Every call shares one accumulating view instance and concurrent calls are serialized, so a * caller never observes a partially loaded view. The instance is discarded by [[clearCaches]], * for example after a schema import; the next call builds a new one. See * [GetSchemaViewArgs]($ecschema-metadata) for the arguments. * @beta */ getSchemaView(args?: GetSchemaViewArgs): Promise<SchemaView>; /** The [SchemaViewDataProvider]($ecschema-metadata) backing this iModel's [[getSchemaView]]: the * transport-specific half of schema-view loading. The backend always uses the latest blob version * since it is strictly coupled with native code. */ private _createSchemaViewDataProvider; /** Fetch one schema-view blob (full or fragment). Both `PRAGMA schema_view` and * `PRAGMA schema_view_fragment` return a single row with the same columns. */ private _fetchSchemaBlob; /** Get the linkTableRelationships for this IModel */ get relationships(): Relationships; /** Get the CodeSpecs in this IModel. */ get codeSpecs(): CodeSpecs; /** Prepare an ECSQL statement. * @param sql The ECSQL statement to prepare * @param logErrors Determines if error will be logged if statement fail to prepare * @throws [[IModelError]] if there is a problem preparing the statement. * @deprecated in 4.11 - might be removed in next major version. Use [IModelDb.createQueryReader]($backend) or [ECDb.createQueryReader]($backend) to query. */ prepareStatement(sql: string, logErrors?: boolean): ECSqlStatement; /** Prepare an ECSQL statement. * @param sql The ECSQL statement to prepare * @returns `undefined` if there is a problem preparing the statement. * @deprecated in 4.11 - might be removed in next major version. Use [IModelDb.createQueryReader]($backend) or [ECDb.createQueryReader]($backend) to query. */ tryPrepareStatement(sql: string): ECSqlStatement | undefined; /** Construct an entity (Element or Model) from an iModel. * @throws [[IModelError]] if the entity cannot be constructed. */ constructEntity<T extends Entity, P extends EntityProps = EntityProps>(props: P): T; /** Get the JavaScript class that handles a given entity class. */ getJsClass<T extends typeof Entity>(classFullName: string): T; /** Constructs a ResolveInstanceKeyArgs from given parameters * @throws [[IModelError]] if the combination of supplied parameters is invalid. * @internal */ getInstanceArgs(instanceId?: Id64String, baseClassName?: string, federationGuid?: GuidString, code?: CodeProps): IModelJsNative.ResolveInstanceKeyArgs; /** Get metadata for a class. This method will load the metadata from the iModel into the cache as a side-effect, if necessary. * @throws [[IModelError]] if the metadata cannot be found nor loaded. * @deprecated in 5.0 - might be removed in next major version. Use `getSchemaView()` on the iModel and call `view.findClass(...)` instead. * * @example * * ```typescript * // Current usage: * const metaData: EntityMetaData = imodel.getMetaData("SchemaName:ClassName"); * * // Replacement: * const view = await imodel.getSchemaView(); * const cls = view.findClass("SchemaName:ClassName"); * ``` */ getMetaData(classFullName: string): EntityMetaData; /** Identical to [[getMetaData]], except it returns `undefined` instead of throwing an error if the metadata cannot be found nor loaded. * @deprecated in 5.0 - might be removed in next major version. Use `getSchemaView()` on the iModel and call `view.findClass(...)` instead. * * @example * * ```typescript * // Current usage: * const metaData: EntityMetaData | undefined = imodel.tryGetMetaData("SchemaName:ClassName"); * * // Replacement: * const view = await imodel.getSchemaView(); * const cls = view.findClass("SchemaName:ClassName"); * ``` */ tryGetMetaData(classFullName: string): EntityMetaData | undefined; /** Invoke a callback on each property of the specified class, optionally including superclass properties. * @param iModel The IModel that contains the schema * @param classFullName The full class name to load the metadata, if necessary * @param wantSuper If true, superclass properties will also be processed * @param func The callback to be invoked on each property * @param includeCustom If true (default), include custom-handled properties in the iteration. Otherwise, skip custom-handled properties. * @note Custom-handled properties are core properties that have behavior enforced by C++ handlers. * @deprecated in 5.0 - might be removed in next major version. Use `getSchemaVi