@itwin/core-backend 5.16.0-dev.6 → 5.16.0-dev.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteDb.js","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,yBAAyB;AACzB,+BAA+B;AAC/B,iCAAiC;AAEjC,sDAAyD;AACzD,oDAAgE;AAChE,+CAA4C;AAC5C,8DAAyD;AACzD,6CAA0C;AAC1C,uDAAoE;AACpE,gDAA+C;AAE/C,0CAA0C;AAE1C;;;GAGG;AACH,MAAa,QAAQ;IACnB,gBAAgB;IACA,CAAC,mBAAS,CAAC,GAAG,IAAI,6BAAY,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;IAC3D,qBAAqB,GAAG,IAAI,gCAAc,EAAmB,CAAC;IAEtE,gBAAgB;IACT,MAAM,CAAC,YAAY;QACxB,OAAO,IAAI,6BAAY,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC5C,CAAC;IAED;;OAEG;IACI,OAAO;QACZ,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAQM,QAAQ,CAAC,MAAc,EAAE,SAAsC,EAAE,MAA8B;QACpG,IAAI,CAAC,mBAAS,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IACtD,CAAC;IAWM,MAAM,CAAC,MAAc,EAAE,QAAwC,EAAE,SAAsC;QAC5G,IAAI,CAAC,mBAAS,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IACtD,CAAC;IAED;;OAEG;IACI,OAAO,CAAC,WAAqB;QAClC,IAAI,WAAW,IAAI,IAAI,CAAC,MAAM;YA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6DAAa,CAAA;IACf,CAAC,EATW,cAAc,GAAd,uBAAc,KAAd,uBAAc,QASzB;AAgDH,CAAC,EAjIgB,QAAQ,wBAAR,QAAQ,QAiIxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLiteDb\r\n */\r\n\r\nimport * as fs from \"fs\";\r\nimport { dirname } from \"path\";\r\nimport * as semver from \"semver\";\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { DbResult, OpenMode } from \"@itwin/core-bentley\";\r\nimport { LocalFileName, SqliteError } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { IModelNative } from \"./internal/NativePlatform\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\r\nimport { _nativeDb } from \"./internal/Symbols\";\r\n\r\n// cspell:ignore savepoint julianday rowid\r\n\r\n/**\r\n * A \"generic\" SQLiteDb. This class may be used to access local files or databases in a cloud container.\r\n * @public\r\n */\r\nexport class SQLiteDb {\r\n /** @internal */\r\n public readonly [_nativeDb] = new IModelNative.platform.SQLiteDb();\r\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\r\n\r\n /** @internal */\r\n public static createBlobIO(): SQLiteDb.BlobIO {\r\n return new IModelNative.platform.BlobIO();\r\n }\r\n\r\n /** alias for closeDb.\r\n * @deprecated in 4.0 - might be removed in next major version. Use [[closeDb]]\r\n */\r\n public dispose(): void {\r\n this.closeDb();\r\n }\r\n\r\n /** Create a SQLiteDb\r\n * @param dbName The path to the SQLiteDb file to create.\r\n */\r\n public createDb(dbName: string): void;\r\n /** @beta */\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\r\n this[_nativeDb].createDb(dbName, container, params);\r\n }\r\n\r\n /** Open a SQLiteDb.\r\n * @param dbName The path to the SQLiteDb file to open\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\r\n /**\r\n * @param container optional CloudContainer holding database\r\n * @beta\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\r\n this[_nativeDb].openDb(dbName, openMode, container);\r\n }\r\n\r\n /** Close SQLiteDb.\r\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\r\n */\r\n public closeDb(saveChanges?: boolean): void {\r\n if (saveChanges && this.isOpen)\r\n this.saveChanges();\r\n this._sqliteStatementCache.clear();\r\n this[_nativeDb].closeDb();\r\n }\r\n\r\n /** Returns true if this SQLiteDb is open */\r\n public get isOpen(): boolean { return this[_nativeDb].isOpen(); }\r\n\r\n /** Returns true if this SQLiteDb is open readonly */\r\n public get isReadonly(): boolean { return this[_nativeDb].isReadonly(); }\r\n\r\n /** Create a new table in this database. */\r\n protected createTable(args: {\r\n /** The name of the table to create. */\r\n tableName: string;\r\n /** all of the columns in the table. */\r\n columns: string;\r\n /** any unique or foreign key constraints */\r\n constraints?: string;\r\n /** if true, add a \"lastMod\" timestamp column and triggers to automatically update it. */\r\n addTimestamp?: boolean;\r\n }) {\r\n const timestampCol = args.addTimestamp ? \",lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))\" : \"\";\r\n const constraints = args.constraints ? `,${args.constraints}` : \"\";\r\n this.executeSQL(`CREATE TABLE ${args.tableName}(${args.columns}${timestampCol}${constraints})`);\r\n if (args.addTimestamp)\r\n this.executeSQL(`CREATE TRIGGER ${args.tableName}_timestamp AFTER UPDATE ON ${args.tableName} WHEN old.lastMod=new.lastMod AND old.lastMod != julianday('now') BEGIN UPDATE ${args.tableName} SET lastMod=julianday('now') WHERE rowid=new.rowid; END`);\r\n }\r\n\r\n /**\r\n * Get the last modified date for a row in a table of this database.\r\n * @note the table must have been created with `addTimestamp: true`\r\n */\r\n public readLastModTime(tableName: string, rowId: number): Date {\r\n return this.withSqliteStatement(`SELECT lastMod from ${tableName} WHERE rowid=?`, (stmt) => {\r\n stmt.bindInteger(1, rowId);\r\n return stmt.getValueDate(0);\r\n });\r\n }\r\n\r\n /**\r\n * Open a database, perform an operation, then close the database.\r\n *\r\n * Details:\r\n * - if database is open, throw an error\r\n * - open a database\r\n * - call a function with the database opened. If it is async, await its return.\r\n * - if function throws, abandon all changes, close database, and rethrow\r\n * - save all changes\r\n * - close the database\r\n * @return value from operation\r\n */\r\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\r\n if (this.isOpen)\r\n SqliteError.throwError(\"already-open\", \"database is already open\", args.dbName);\r\n\r\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\r\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\r\n try {\r\n const result = operation();\r\n result instanceof Promise ? result.then(save, abandon) : save();\r\n return result;\r\n } catch (e) {\r\n abandon();\r\n throw e;\r\n }\r\n }\r\n\r\n /** The cloud container backing this SQLite database, if any.\r\n * @beta\r\n */\r\n public get cloudContainer(): CloudSqlite.CloudContainer | undefined {\r\n return this[_nativeDb].cloudContainer;\r\n }\r\n\r\n /** Returns the Id of the most-recently-inserted row in this database, per [sqlite3_last_insert_rowid](https://www.sqlite.org/c3ref/last_insert_rowid.html). */\r\n public getLastInsertRowId(): number {\r\n return this[_nativeDb].getLastInsertRowId();\r\n }\r\n\r\n /**\r\n * Perform an operation on a database in a CloudContainer with the write lock held.\r\n *\r\n * Details:\r\n * - acquire the write lock on a CloudContainer\r\n * - call `withOpenDb` with openMode `ReadWrite`\r\n * - upload changes\r\n * - release the write lock\r\n * @param args arguments to lock the container and open the database\r\n * @param operation an operation performed on the database with the write lock held.\r\n * @return value from operation\r\n * @internal\r\n */\r\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => Promise<T>) {\r\n return CloudSqlite.withWriteLock(args, async () => this.withOpenDb({ ...args, openMode: args.openMode ?? OpenMode.ReadWrite }, operation));\r\n }\r\n\r\n /** vacuum this database\r\n * @see https://www.sqlite.org/lang_vacuum.html\r\n */\r\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\r\n this[_nativeDb].vacuum(args);\r\n }\r\n\r\n /** Commit the outermost transaction, writing changes to the file. Then, restart the default transaction. */\r\n public saveChanges(): void {\r\n this[_nativeDb].saveChanges();\r\n }\r\n\r\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the default transaction. */\r\n public abandonChanges(): void {\r\n this[_nativeDb].abandonChanges();\r\n }\r\n\r\n /**\r\n * Apply a raw sqlite changeset file - the plain, uncompressed byte stream produced by the sqlite session\r\n * extension - to this SQLiteDb. This is *not* the same on-disk format used for iModel changesets.\r\n * Unlike `BriefcaseDb.pullChanges`, this does *not* perform any iModel-style changeset relationship validation (e.g. parentId/changesetId)\r\n * against the current state of the database (raw sqlite changesets have no header) - it simply applies the changes it contains. It also does *not*\r\n * support DDL/schema changes - raw sqlite changesets cannot represent them. If applying the changeset\r\n * encounters any conflict, or otherwise fails, this method throws (conflicts are never resolved\r\n * automatically).\r\n * @note this method only throws on failure - it does *not* commit or abandon any changes itself. If it\r\n * throws, some (but not necessarily all) of the changeset's changes may have already been applied to the\r\n * current transaction. It is the caller's responsibility to call [[saveChanges]] or [[abandonChanges]]\r\n * as appropriate after catching an error from this method.\r\n * @param changesetFile the local file name of the changeset to apply.\r\n * @internal\r\n */\r\n public applyChangeset(changesetFile: LocalFileName): void {\r\n this[_nativeDb].applyChangeset(changesetFile);\r\n }\r\n\r\n /**\r\n * Begin capturing data changes made to this SQLiteDb, so they may later be saved via [[createChangeset]].\r\n * Intended only to produce changeset files for testing [[applyChangeset]] - not for any other purpose.\r\n * @note DDL/schema changes are *not* captured - the raw sqlite changeset format produced by [[createChangeset]]\r\n * cannot represent them. [[createChangeset]] throws if any DDL was executed via [[executeDdl]] since tracking began.\r\n * @internal\r\n */\r\n public startChangeTracking(): void {\r\n this[_nativeDb].startChangeTracking();\r\n }\r\n\r\n /**\r\n * Execute a DDL statement (e.g. `CREATE TABLE`). DDL cannot be represented in the raw sqlite changeset format\r\n * produced by [[createChangeset]], so it is never included in a changeset regardless of how it is executed.\r\n * However, unlike DDL executed via [[executeSQL]], DDL executed via this method *is* recorded by change\r\n * tracking (see [[startChangeTracking]]) for detection purposes: if any DDL is executed via this method while\r\n * tracking is active, [[createChangeset]] throws rather than silently producing a changeset that omits the\r\n * schema change.\r\n * @internal\r\n */\r\n public executeDdl(ddl: string): void {\r\n this[_nativeDb].executeDdl(ddl);\r\n }\r\n\r\n /**\r\n * Write out the changes captured since [[startChangeTracking]] was called to a changeset file, holding the\r\n * raw sqlite changeset (the plain, uncompressed byte stream produced by the sqlite session extension). This\r\n * is *not* the same on-disk format used for iModel changesets. Throws if any DDL/schema changes were captured,\r\n * since raw sqlite changesets cannot represent them.\r\n * @param changesetFile the local file name to write the changeset to.\r\n * @internal\r\n */\r\n public createChangeset(changesetFile: LocalFileName): void {\r\n this[_nativeDb].createChangeset(changesetFile);\r\n }\r\n\r\n /**\r\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\r\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\r\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\r\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\r\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\r\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Prepare and execute a callback on a SQL statement. After the callback completes the statement is disposed.\r\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\r\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this.prepareSqliteStatement(sql);\r\n const release = () => stmt[Symbol.dispose]();\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\r\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\r\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\r\n */\r\n public withSavePoint(savePointName: string, operation: () => void) {\r\n if (this.isReadonly)\r\n SqliteError.throwError(\"readonly\", \"database is readonly\", this[_nativeDb].getFilePath());\r\n\r\n this.executeSQL(`SAVEPOINT ${savePointName}`);\r\n try {\r\n operation();\r\n this.executeSQL(`RELEASE ${savePointName}`);\r\n } catch (e) {\r\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\r\n throw e;\r\n }\r\n }\r\n\r\n /** Prepare an SQL statement.\r\n * @param sql The SQLite SQL statement to prepare\r\n * @param logErrors Determine if errors are logged or not\r\n * @internal\r\n */\r\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\r\n const stmt = new SqliteStatement(sql);\r\n stmt.prepare(this[_nativeDb], logErrors);\r\n return stmt;\r\n }\r\n\r\n /** execute an SQL statement */\r\n public executeSQL(sql: string): DbResult {\r\n using stmt = this.prepareSqliteStatement(sql);\r\n return stmt.step();\r\n }\r\n}\r\n\r\n/**\r\n * Abstract base class for a SQLite database that has [[SQLiteDb.RequiredVersionRanges]] stored in it.\r\n * This class provides version checking when the database is opened, to guarantee that a valid version of software is\r\n * always used for access.\r\n *\r\n * Notes:\r\n * - This class may be used either to access a local file, or one stored in a cloud container.\r\n * - Subclasses must provide a `myVersion` member indicating the version of its software, and implement the `createDDL` member to create its\r\n * tables.\r\n * @beta\r\n */\r\nexport abstract class VersionedSqliteDb extends SQLiteDb {\r\n protected static _versionProps = { namespace: \"SQLiteDb\", name: \"versions\" } as const;\r\n\r\n /** The current semver \"persistence version\" of this class.\r\n * @note This value should only be changed when logic in its code is modified in a way that affects the operation of extant copies.\r\n * If this value is outside of the range of accepted versions of a to-be-opened VersionedSqliteDb, the operation will fail. In this manner, if\r\n * changes are made to the format of a VersionedSqliteDb, or if bug fixes are necessary, the `requiredVersions` property in a VersionedSqliteDb may be updated\r\n * and immediately old versions of the package will refuse to open the VersionedSqliteDb, with a message to the user that they need to upgrade their\r\n * software. Likewise, if a new version of the package is asked to open an older VersionedSqliteDb that has not been upgraded to the lowest version\r\n * supported by it, the user will be informed that they need to upgrade their software.\r\n * @note this identifier is independent of versions in `package.json` files.\r\n */\r\n public abstract myVersion: string;\r\n\r\n /**\r\n * Change the \"versions required to open this database\" property stored in this database. After this call,\r\n * versions of software that don't meet the supplied ranges will fail.\r\n * @param versions the new versions required for reading and writing this database.\r\n * @note the database must be opened for write access.\r\n */\r\n public setRequiredVersions(versions: SQLiteDb.RequiredVersionRanges) {\r\n // NOTE: It might look tempting to just stringify the supplied `versions` object, but we only include required members - there may be others.\r\n this[_nativeDb].saveFileProperty(VersionedSqliteDb._versionProps, JSON.stringify({ readVersion: versions.readVersion, writeVersion: versions.writeVersion }));\r\n }\r\n\r\n /** Get the required version ranges necessary to open this VersionedSqliteDb. */\r\n public getRequiredVersions() {\r\n const checkIsString = (value: any) => {\r\n if (typeof value !== \"string\")\r\n SqliteError.throwError(\"invalid-versions-property\", `CloudDb has invalid \"versions\" property`, this[_nativeDb].getFilePath());\r\n return value;\r\n };\r\n const versionJson = checkIsString(this[_nativeDb].queryFileProperty(VersionedSqliteDb._versionProps, true));\r\n const versionRanges = JSON.parse(versionJson) as SQLiteDb.RequiredVersionRanges;\r\n checkIsString(versionRanges.readVersion);\r\n checkIsString(versionRanges.writeVersion);\r\n return versionRanges;\r\n }\r\n\r\n /**\r\n * Implement this method to create all tables for this subclass of `VersionedSqliteDb` when a new database file is created. Called from [[createNewDb]].\r\n */\r\n protected abstract createDDL(args: any): void;\r\n\r\n /**\r\n * Create a new database file for the subclass of VersionedSqliteDb.\r\n * @note The required versions are saved as [[myVersion]] or newer for both read and write.\r\n */\r\n public static createNewDb(fileName: LocalFileName, setupArgs?: any) {\r\n const db = new (this as any)() as VersionedSqliteDb; // \"as any\" necessary because VersionedSqliteDb is abstract\r\n IModelJsFs.recursiveMkDirSync(dirname(fileName));\r\n if (fs.existsSync(fileName))\r\n fs.unlinkSync(fileName);\r\n\r\n db.createDb(fileName);\r\n db.createDDL(setupArgs);\r\n const minVer = `^${db.myVersion}`;\r\n db.setRequiredVersions({ readVersion: minVer, writeVersion: minVer });\r\n db.closeDb(true);\r\n }\r\n\r\n /**\r\n * Verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\r\n * Throws otherwise.\r\n */\r\n protected verifyVersions() {\r\n const versions = this.getRequiredVersions();\r\n const isReadonly = this.isReadonly; // so we can tell read/write after the file is closed.\r\n const range = isReadonly ? versions.readVersion : versions.writeVersion;\r\n if (semver.satisfies(this.myVersion, range))\r\n return;\r\n\r\n this.closeDb();\r\n const tooNew = semver.gtr(this.myVersion, range);\r\n SqliteError.throwError(\"incompatible-version\", `requires ${tooNew ? \"older\" : \"newer\"} version of ${this.constructor.name} for ${isReadonly ? \"read\" : \"write\"}`, this[_nativeDb].getFilePath());\r\n\r\n }\r\n\r\n /**\r\n * Open this database and verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\r\n * Throws otherwise.\r\n * @see [[SqliteDb.openDb]] for argument types\r\n */\r\n public override openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer) {\r\n super.openDb(dbName, openMode, container);\r\n this.verifyVersions();\r\n }\r\n\r\n public async upgradeSchema(arg: { dbName: string, lockContainer?: { container: CloudSqlite.CloudContainer, user: string }, upgradeFn: () => void }) {\r\n // can't use \"this\" because it checks for version, which we don't want here\r\n return (arg.lockContainer) ?\r\n super.withLockedContainer({ dbName: arg.dbName, ...arg.lockContainer }, async () => arg.upgradeFn) :\r\n super.withOpenDb({ ...arg, openMode: OpenMode.ReadWrite }, arg.upgradeFn);\r\n }\r\n}\r\n\r\n/** @public */\r\nexport namespace SQLiteDb {\r\n /** A semver version range.\r\n * @see https://docs.npmjs.com/cli/v6/using-npm/semver\r\n */\r\n export type VersionRange = string;\r\n\r\n /**\r\n * A pair of semver [[SQLiteDb.VersionRange]]s, one for read and one for write, required to access a [[VersionedSqliteDb]].\r\n * If the version of the software attempting to read or write the database does not satisfy the range, access is denied.\r\n */\r\n export interface RequiredVersionRanges {\r\n /** a range of acceptable persistence versions for reading from a VersionedSqliteDb. */\r\n readonly readVersion: VersionRange;\r\n /** a range of acceptable persistence versions for writing to a VersionedSqliteDb. */\r\n readonly writeVersion: VersionRange;\r\n }\r\n\r\n /** interface for reading and writing to a blob in a SQLiteDb\r\n * @internal\r\n */\r\n export interface BlobIO {\r\n /** Close this BlobIO if it is opened.\r\n * @note this BlobIO *may* be reused after this call by calling `open` again.\r\n */\r\n close(): void;\r\n /** get the total number of bytes in the blob */\r\n getNumBytes(): number;\r\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\r\n isValid(): boolean;\r\n /** Open this BlobIO against a table/row/column in a Db */\r\n open(\r\n /** The database for the blob */\r\n db: IModelJsNative.AnyDb,\r\n args: {\r\n /** the name of the table for the blob*/\r\n tableName: string;\r\n /** the name of the column for the blob */\r\n columnName: string;\r\n /** The rowId of the blob */\r\n row: number;\r\n /** If true, open this BlobIO for write access */\r\n writeable?: boolean;\r\n }): void;\r\n /** Read from a blob\r\n * @returns the contents of the requested byte range\r\n */\r\n read(args: {\r\n /** The number of bytes to read */\r\n numBytes: number;\r\n /** starting offset within the blob to read */\r\n offset: number;\r\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\r\n blob?: ArrayBuffer;\r\n }): Uint8Array;\r\n /** Reposition this BlobIO to a new rowId\r\n * @note this BlobIO must be valid when this methods is called.\r\n */\r\n changeRow(row: number): void;\r\n /** Write to a blob */\r\n write(args: {\r\n /** The number of bytes to write */\r\n numBytes: number;\r\n /** starting offset within the blob to write */\r\n offset: number;\r\n /** the value to write */\r\n blob: ArrayBuffer;\r\n }): void;\r\n }\r\n\r\n /** Default transaction mode for SQLiteDbs.\r\n * @see https://www.sqlite.org/lang_transaction.html\r\n */\r\n export enum DefaultTxnMode {\r\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\r\n None = 0,\r\n /** A deferred transaction is started when the file is first opened. This is the default. */\r\n Deferred = 1,\r\n /** An immediate transaction is started when the file is first opened. */\r\n Immediate = 2,\r\n /** An exclusive transaction is started when the file is first opened. */\r\n Exclusive = 3\r\n }\r\n\r\n /** parameters common to opening or creating a new SQLiteDb */\r\n export interface OpenOrCreateParams {\r\n /** If true, do not require that the `be_Prop` table exist */\r\n rawSQLite?: boolean;\r\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\r\n immutable?: boolean;\r\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\r\n skipFileCheck?: boolean;\r\n /** the default transaction mode\r\n * @see [[SQLiteDb.DefaultTxnMode]]\r\n */\r\n defaultTxn?: 0 | 1 | 2 | 3;\r\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\r\n queryParam?: string;\r\n }\r\n\r\n /** Parameters for opening an existing SQLiteDb */\r\n export interface OpenParams extends OpenOrCreateParams {\r\n /** use OpenMode.ReadWrite to open the file with write access */\r\n openMode: OpenMode;\r\n }\r\n\r\n /** Size of a SQLiteDb page in bytes */\r\n export interface PageSize {\r\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\r\n pageSize?: number;\r\n }\r\n\r\n /** Parameters for creating a new SQLiteDb */\r\n export type CreateParams = OpenOrCreateParams & PageSize;\r\n\r\n /** Arguments for `SqliteDb.withOpenDb` */\r\n export interface WithOpenDbArgs {\r\n /** The name of the database to open */\r\n dbName: string;\r\n /** either an object with the open parameters or just OpenMode value. */\r\n openMode?: OpenMode | SQLiteDb.OpenParams;\r\n /** @internal */\r\n container?: CloudSqlite.CloudContainer;\r\n }\r\n\r\n /** Arguments for `SQLiteDb.vacuum` */\r\n export interface VacuumDbArgs extends PageSize {\r\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\r\n into?: LocalFileName;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"SQLiteDb.js","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,yBAAyB;AACzB,+BAA+B;AAC/B,iCAAiC;AAEjC,sDAA+E;AAC/E,oDAAgE;AAChE,+CAA4C;AAC5C,8DAAyD;AACzD,6CAA0C;AAC1C,uDAAoE;AACpE,gDAA+C;AAE/C,0CAA0C;AAE1C;;;GAGG;AACH,MAAa,QAAQ;IACnB,gBAAgB;IACA,CAAC,mBAAS,CAAC,GAAG,IAAI,6BAAY,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;IAC3D,qBAAqB,GAAG,IAAI,gCAAc,EAAmB,CAAC;IAEtE,gBAAgB;IACT,MAAM,CAAC,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QAChJ,2EAA2E;QAC3E,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC;YAC1B,KAAK,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,aAAa,EAAE,EAAE,KAAK,IAAI,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;YACpG,KAAK,CAAC,UAAU,CAAC,EAAE,GAAG,GAAG,EAAE,QAAQ,EAAE,uBAAQ,CAAC,SAAS,EAAE,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9E,CAAC;;AA7FH,8CA8FC;AAED,cAAc;AACd,WAAiB,QAAQ;IACvB;;OAEG;IACH,IAAY,mBAWX;IAXD,WAAY,mBAAmB;QAC7B,oCAAoC;QACpC,6DAAQ,CAAA;QACR,0CAA0C;QAC1C,iEAAU,CAAA;QACV,kGAAkG;QAClG,yEAAc,CAAA;QACd,0GAA0G;QAC1G,yEAAc,CAAA;QACd,qFAAqF;QACrF,6EAAgB,CAAA;IAClB,CAAC,EAXW,mBAAmB,GAAnB,4BAAmB,KAAnB,4BAAmB,QAW9B;IAED;;OAEG;IACH,IAAY,uBAUX;IAVD,WAAY,uBAAuB;QACjC,kDAAkD;QAClD,iGAAsB,CAAA;QACtB;;;;;WAKG;QACH,yFAAkB,CAAA;IACpB,CAAC,EAVW,uBAAuB,GAAvB,gCAAuB,KAAvB,gCAAuB,QAUlC;IAsFD;;OAEG;IACH,IAAY,cASX;IATD,WAAY,cAAc;QACxB,4GAA4G;QAC5G,mDAAQ,CAAA;QACR,4FAA4F;QAC5F,2DAAY,CAAA;QACZ,yEAAyE;QACzE,6DAAa,CAAA;QACb,yEAAyE;QACzE,6DAAa,CAAA;IACf,CAAC,EATW,cAAc,GAAd,uBAAc,KAAd,uBAAc,QASzB;AAgDH,CAAC,EAhLgB,QAAQ,wBAAR,QAAQ,QAgLxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLiteDb\r\n */\r\n\r\nimport * as fs from \"fs\";\r\nimport { dirname } from \"path\";\r\nimport * as semver from \"semver\";\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { DbConflictResolution, DbResult, OpenMode } from \"@itwin/core-bentley\";\r\nimport { LocalFileName, SqliteError } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { IModelNative } from \"./internal/NativePlatform\";\r\nimport { IModelJsFs } from \"./IModelJsFs\";\r\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\r\nimport { _nativeDb } from \"./internal/Symbols\";\r\n\r\n// cspell:ignore savepoint julianday rowid\r\n\r\n/**\r\n * A \"generic\" SQLiteDb. This class may be used to access local files or databases in a cloud container.\r\n * @public\r\n */\r\nexport class SQLiteDb {\r\n /** @internal */\r\n public readonly [_nativeDb] = new IModelNative.platform.SQLiteDb();\r\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\r\n\r\n /** @internal */\r\n public static createBlobIO(): SQLiteDb.BlobIO {\r\n return new IModelNative.platform.BlobIO();\r\n }\r\n\r\n /** alias for closeDb.\r\n * @deprecated in 4.0 - might be removed in next major version. Use [[closeDb]]\r\n */\r\n public dispose(): void {\r\n this.closeDb();\r\n }\r\n\r\n /** Create a SQLiteDb\r\n * @param dbName The path to the SQLiteDb file to create.\r\n */\r\n public createDb(dbName: string): void;\r\n /** @beta */\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\r\n this[_nativeDb].createDb(dbName, container, params);\r\n }\r\n\r\n /** Open a SQLiteDb.\r\n * @param dbName The path to the SQLiteDb file to open\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\r\n /**\r\n * @param container optional CloudContainer holding database\r\n * @beta\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\r\n this[_nativeDb].openDb(dbName, openMode, container);\r\n }\r\n\r\n /** Close SQLiteDb.\r\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\r\n */\r\n public closeDb(saveChanges?: boolean): void {\r\n if (saveChanges && this.isOpen)\r\n this.saveChanges();\r\n this._sqliteStatementCache.clear();\r\n this[_nativeDb].closeDb();\r\n }\r\n\r\n /** Returns true if this SQLiteDb is open */\r\n public get isOpen(): boolean { return this[_nativeDb].isOpen(); }\r\n\r\n /** Returns true if this SQLiteDb is open readonly */\r\n public get isReadonly(): boolean { return this[_nativeDb].isReadonly(); }\r\n\r\n /** Create a new table in this database. */\r\n protected createTable(args: {\r\n /** The name of the table to create. */\r\n tableName: string;\r\n /** all of the columns in the table. */\r\n columns: string;\r\n /** any unique or foreign key constraints */\r\n constraints?: string;\r\n /** if true, add a \"lastMod\" timestamp column and triggers to automatically update it. */\r\n addTimestamp?: boolean;\r\n }) {\r\n const timestampCol = args.addTimestamp ? \",lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))\" : \"\";\r\n const constraints = args.constraints ? `,${args.constraints}` : \"\";\r\n this.executeSQL(`CREATE TABLE ${args.tableName}(${args.columns}${timestampCol}${constraints})`);\r\n if (args.addTimestamp)\r\n this.executeSQL(`CREATE TRIGGER ${args.tableName}_timestamp AFTER UPDATE ON ${args.tableName} WHEN old.lastMod=new.lastMod AND old.lastMod != julianday('now') BEGIN UPDATE ${args.tableName} SET lastMod=julianday('now') WHERE rowid=new.rowid; END`);\r\n }\r\n\r\n /**\r\n * Get the last modified date for a row in a table of this database.\r\n * @note the table must have been created with `addTimestamp: true`\r\n */\r\n public readLastModTime(tableName: string, rowId: number): Date {\r\n return this.withSqliteStatement(`SELECT lastMod from ${tableName} WHERE rowid=?`, (stmt) => {\r\n stmt.bindInteger(1, rowId);\r\n return stmt.getValueDate(0);\r\n });\r\n }\r\n\r\n /**\r\n * Open a database, perform an operation, then close the database.\r\n *\r\n * Details:\r\n * - if database is open, throw an error\r\n * - open a database\r\n * - call a function with the database opened. If it is async, await its return.\r\n * - if function throws, abandon all changes, close database, and rethrow\r\n * - save all changes\r\n * - close the database\r\n * @return value from operation\r\n */\r\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\r\n if (this.isOpen)\r\n SqliteError.throwError(\"already-open\", \"database is already open\", args.dbName);\r\n\r\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\r\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\r\n try {\r\n const result = operation();\r\n result instanceof Promise ? result.then(save, abandon) : save();\r\n return result;\r\n } catch (e) {\r\n abandon();\r\n throw e;\r\n }\r\n }\r\n\r\n /** The cloud container backing this SQLite database, if any.\r\n * @beta\r\n */\r\n public get cloudContainer(): CloudSqlite.CloudContainer | undefined {\r\n return this[_nativeDb].cloudContainer;\r\n }\r\n\r\n /** Returns the Id of the most-recently-inserted row in this database, per [sqlite3_last_insert_rowid](https://www.sqlite.org/c3ref/last_insert_rowid.html). */\r\n public getLastInsertRowId(): number {\r\n return this[_nativeDb].getLastInsertRowId();\r\n }\r\n\r\n /**\r\n * Perform an operation on a database in a CloudContainer with the write lock held.\r\n *\r\n * Details:\r\n * - acquire the write lock on a CloudContainer\r\n * - call `withOpenDb` with openMode `ReadWrite`\r\n * - upload changes\r\n * - release the write lock\r\n * @param args arguments to lock the container and open the database\r\n * @param operation an operation performed on the database with the write lock held.\r\n * @return value from operation\r\n * @internal\r\n */\r\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => Promise<T>) {\r\n return CloudSqlite.withWriteLock(args, async () => this.withOpenDb({ ...args, openMode: args.openMode ?? OpenMode.ReadWrite }, operation));\r\n }\r\n\r\n /** vacuum this database\r\n * @see https://www.sqlite.org/lang_vacuum.html\r\n */\r\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\r\n this[_nativeDb].vacuum(args);\r\n }\r\n\r\n /** Commit the outermost transaction, writing changes to the file. Then, restart the default transaction. */\r\n public saveChanges(): void {\r\n this[_nativeDb].saveChanges();\r\n }\r\n\r\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the default transaction. */\r\n public abandonChanges(): void {\r\n this[_nativeDb].abandonChanges();\r\n }\r\n\r\n /**\r\n * Apply a raw sqlite changeset file - the plain, uncompressed byte stream produced by the sqlite session\r\n * extension - to this SQLiteDb. This is *not* the same on-disk format used for iModel changesets.\r\n * Unlike `BriefcaseDb.pullChanges`, this does *not* perform any iModel-style changeset relationship validation (e.g. parentId/changesetId)\r\n * against the current state of the database (raw sqlite changesets have no header) - it simply applies the changes it contains. It also does *not*\r\n * support DDL/schema changes - raw sqlite changesets cannot represent them. Conflicts abort by default.\r\n * A built-in policy or custom handler can resolve conflicts; unresolved conflicts and other failures throw.\r\n * @note this method only throws on failure - it does *not* commit or abandon any changes itself. If it\r\n * throws, some (but not necessarily all) of the changeset's changes may have already been applied to the\r\n * current transaction. It is the caller's responsibility to call [[saveChanges]] or [[abandonChanges]]\r\n * as appropriate after catching an error from this method.\r\n * @param changesetFile the local file name of the changeset to apply.\r\n * @param flags Independent apply options. Defaults to [[SQLiteDb.ApplyChangesetFlags.None]].\r\n * @param conflictHandler Defaults to [[SQLiteDb.ChangesetConflictPolicy.AbortOnAnyConflict]].\r\n * Use [[SQLiteDb.ChangesetConflictPolicy.NoLocalChanges]] for the generic iModel policy without\r\n * table-specific rules, or supply a synchronous custom handler. This does not enable any apply flags:\r\n * to suppress cascades, also pass [[SQLiteDb.ApplyChangesetFlags.FkNoAction]].\r\n * @internal\r\n */\r\n public applyChangeset(changesetFile: LocalFileName, flags?: SQLiteDb.ApplyChangesetFlags, conflictHandler?: SQLiteDb.ChangesetConflictPolicy | SQLiteDb.ChangesetConflictHandler): void {\r\n this[_nativeDb].applyChangeset(changesetFile, flags, conflictHandler);\r\n }\r\n\r\n /**\r\n * Begin capturing data changes made to this SQLiteDb, so they may later be saved via [[createChangeset]].\r\n * Intended only to produce changeset files for testing [[applyChangeset]] - not for any other purpose.\r\n * @note DDL/schema changes are *not* captured - the raw sqlite changeset format produced by [[createChangeset]]\r\n * cannot represent them. [[createChangeset]] throws if any DDL was executed via [[executeDdl]] since tracking began.\r\n * @internal\r\n */\r\n public startChangeTracking(): void {\r\n this[_nativeDb].startChangeTracking();\r\n }\r\n\r\n /**\r\n * Execute a DDL statement (e.g. `CREATE TABLE`). DDL cannot be represented in the raw sqlite changeset format\r\n * produced by [[createChangeset]], so it is never included in a changeset regardless of how it is executed.\r\n * However, unlike DDL executed via [[executeSQL]], DDL executed via this method *is* recorded by change\r\n * tracking (see [[startChangeTracking]]) for detection purposes: if any DDL is executed via this method while\r\n * tracking is active, [[createChangeset]] throws rather than silently producing a changeset that omits the\r\n * schema change.\r\n * @internal\r\n */\r\n public executeDdl(ddl: string): void {\r\n this[_nativeDb].executeDdl(ddl);\r\n }\r\n\r\n /**\r\n * Write out the changes captured since [[startChangeTracking]] was called to a changeset file, holding the\r\n * raw sqlite changeset (the plain, uncompressed byte stream produced by the sqlite session extension). This\r\n * is *not* the same on-disk format used for iModel changesets. Throws if any DDL/schema changes were captured,\r\n * since raw sqlite changesets cannot represent them.\r\n * @param changesetFile the local file name to write the changeset to.\r\n * @internal\r\n */\r\n public createChangeset(changesetFile: LocalFileName): void {\r\n this[_nativeDb].createChangeset(changesetFile);\r\n }\r\n\r\n /**\r\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\r\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\r\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\r\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\r\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\r\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Prepare and execute a callback on a SQL statement. After the callback completes the statement is disposed.\r\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\r\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this.prepareSqliteStatement(sql);\r\n const release = () => stmt[Symbol.dispose]();\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\r\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\r\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\r\n */\r\n public withSavePoint(savePointName: string, operation: () => void) {\r\n if (this.isReadonly)\r\n SqliteError.throwError(\"readonly\", \"database is readonly\", this[_nativeDb].getFilePath());\r\n\r\n this.executeSQL(`SAVEPOINT ${savePointName}`);\r\n try {\r\n operation();\r\n this.executeSQL(`RELEASE ${savePointName}`);\r\n } catch (e) {\r\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\r\n throw e;\r\n }\r\n }\r\n\r\n /** Prepare an SQL statement.\r\n * @param sql The SQLite SQL statement to prepare\r\n * @param logErrors Determine if errors are logged or not\r\n * @internal\r\n */\r\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\r\n const stmt = new SqliteStatement(sql);\r\n stmt.prepare(this[_nativeDb], logErrors);\r\n return stmt;\r\n }\r\n\r\n /** execute an SQL statement */\r\n public executeSQL(sql: string): DbResult {\r\n using stmt = this.prepareSqliteStatement(sql);\r\n return stmt.step();\r\n }\r\n}\r\n\r\n/**\r\n * Abstract base class for a SQLite database that has [[SQLiteDb.RequiredVersionRanges]] stored in it.\r\n * This class provides version checking when the database is opened, to guarantee that a valid version of software is\r\n * always used for access.\r\n *\r\n * Notes:\r\n * - This class may be used either to access a local file, or one stored in a cloud container.\r\n * - Subclasses must provide a `myVersion` member indicating the version of its software, and implement the `createDDL` member to create its\r\n * tables.\r\n * @beta\r\n */\r\nexport abstract class VersionedSqliteDb extends SQLiteDb {\r\n protected static _versionProps = { namespace: \"SQLiteDb\", name: \"versions\" } as const;\r\n\r\n /** The current semver \"persistence version\" of this class.\r\n * @note This value should only be changed when logic in its code is modified in a way that affects the operation of extant copies.\r\n * If this value is outside of the range of accepted versions of a to-be-opened VersionedSqliteDb, the operation will fail. In this manner, if\r\n * changes are made to the format of a VersionedSqliteDb, or if bug fixes are necessary, the `requiredVersions` property in a VersionedSqliteDb may be updated\r\n * and immediately old versions of the package will refuse to open the VersionedSqliteDb, with a message to the user that they need to upgrade their\r\n * software. Likewise, if a new version of the package is asked to open an older VersionedSqliteDb that has not been upgraded to the lowest version\r\n * supported by it, the user will be informed that they need to upgrade their software.\r\n * @note this identifier is independent of versions in `package.json` files.\r\n */\r\n public abstract myVersion: string;\r\n\r\n /**\r\n * Change the \"versions required to open this database\" property stored in this database. After this call,\r\n * versions of software that don't meet the supplied ranges will fail.\r\n * @param versions the new versions required for reading and writing this database.\r\n * @note the database must be opened for write access.\r\n */\r\n public setRequiredVersions(versions: SQLiteDb.RequiredVersionRanges) {\r\n // NOTE: It might look tempting to just stringify the supplied `versions` object, but we only include required members - there may be others.\r\n this[_nativeDb].saveFileProperty(VersionedSqliteDb._versionProps, JSON.stringify({ readVersion: versions.readVersion, writeVersion: versions.writeVersion }));\r\n }\r\n\r\n /** Get the required version ranges necessary to open this VersionedSqliteDb. */\r\n public getRequiredVersions() {\r\n const checkIsString = (value: any) => {\r\n if (typeof value !== \"string\")\r\n SqliteError.throwError(\"invalid-versions-property\", `CloudDb has invalid \"versions\" property`, this[_nativeDb].getFilePath());\r\n return value;\r\n };\r\n const versionJson = checkIsString(this[_nativeDb].queryFileProperty(VersionedSqliteDb._versionProps, true));\r\n const versionRanges = JSON.parse(versionJson) as SQLiteDb.RequiredVersionRanges;\r\n checkIsString(versionRanges.readVersion);\r\n checkIsString(versionRanges.writeVersion);\r\n return versionRanges;\r\n }\r\n\r\n /**\r\n * Implement this method to create all tables for this subclass of `VersionedSqliteDb` when a new database file is created. Called from [[createNewDb]].\r\n */\r\n protected abstract createDDL(args: any): void;\r\n\r\n /**\r\n * Create a new database file for the subclass of VersionedSqliteDb.\r\n * @note The required versions are saved as [[myVersion]] or newer for both read and write.\r\n */\r\n public static createNewDb(fileName: LocalFileName, setupArgs?: any) {\r\n const db = new (this as any)() as VersionedSqliteDb; // \"as any\" necessary because VersionedSqliteDb is abstract\r\n IModelJsFs.recursiveMkDirSync(dirname(fileName));\r\n if (fs.existsSync(fileName))\r\n fs.unlinkSync(fileName);\r\n\r\n db.createDb(fileName);\r\n db.createDDL(setupArgs);\r\n const minVer = `^${db.myVersion}`;\r\n db.setRequiredVersions({ readVersion: minVer, writeVersion: minVer });\r\n db.closeDb(true);\r\n }\r\n\r\n /**\r\n * Verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\r\n * Throws otherwise.\r\n */\r\n protected verifyVersions() {\r\n const versions = this.getRequiredVersions();\r\n const isReadonly = this.isReadonly; // so we can tell read/write after the file is closed.\r\n const range = isReadonly ? versions.readVersion : versions.writeVersion;\r\n if (semver.satisfies(this.myVersion, range))\r\n return;\r\n\r\n this.closeDb();\r\n const tooNew = semver.gtr(this.myVersion, range);\r\n SqliteError.throwError(\"incompatible-version\", `requires ${tooNew ? \"older\" : \"newer\"} version of ${this.constructor.name} for ${isReadonly ? \"read\" : \"write\"}`, this[_nativeDb].getFilePath());\r\n\r\n }\r\n\r\n /**\r\n * Open this database and verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\r\n * Throws otherwise.\r\n * @see [[SqliteDb.openDb]] for argument types\r\n */\r\n public override openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer) {\r\n super.openDb(dbName, openMode, container);\r\n this.verifyVersions();\r\n }\r\n\r\n public async upgradeSchema(arg: { dbName: string, lockContainer?: { container: CloudSqlite.CloudContainer, user: string }, upgradeFn: () => void }) {\r\n // can't use \"this\" because it checks for version, which we don't want here\r\n return (arg.lockContainer) ?\r\n super.withLockedContainer({ dbName: arg.dbName, ...arg.lockContainer }, async () => arg.upgradeFn) :\r\n super.withOpenDb({ ...arg, openMode: OpenMode.ReadWrite }, arg.upgradeFn);\r\n }\r\n}\r\n\r\n/** @public */\r\nexport namespace SQLiteDb {\r\n /** Independent flags for applying a raw SQLite changeset. Combine with bitwise OR.\r\n * @internal\r\n */\r\n export enum ApplyChangesetFlags {\r\n /** Apply with no optional flags. */\r\n None = 0,\r\n /** Apply the inverse of the changeset. */\r\n Invert = 1,\r\n /** Skip changes that would leave the database unchanged without invoking the conflict handler. */\r\n IgnoreNoop = 2,\r\n /** Treat all foreign-key actions as NO ACTION, including CASCADE, RESTRICT, SET NULL, and SET DEFAULT. */\r\n FkNoAction = 4,\r\n /** Report cyclic UNIQUE updates as constraint conflicts instead of retrying them. */\r\n NoUpdateLoop = 8,\r\n }\r\n\r\n /** Built-in conflict policies, independent of apply flags.\r\n * @internal\r\n */\r\n export enum ChangesetConflictPolicy {\r\n /** Abort on any conflict. This is the default. */\r\n AbortOnAnyConflict = 0,\r\n /** Generic iModel policy with no local changes: skip missing rows and constraint conflicts,\r\n * replace data and primary-key insert conflicts, and abort on foreign-key violations.\r\n * Indirect data conflicts are replaced without warnings except for sqlite_stat1 conflicts.\r\n * Primary-key insert conflicts are replaced with a warning even for indirect changes.\r\n * Does not include iModel-specific table rules or disable foreign-key actions.\r\n */\r\n NoLocalChanges = 1,\r\n }\r\n\r\n /** Copied conflict metadata, safe to retain after the callback returns.\r\n * Row conflicts include table, operation, column count, and primary-key indices.\r\n * Foreign-key conflicts only include their cause and violation count because SQLite provides no associated row.\r\n * @internal\r\n */\r\n export type ChangesetConflictArgs = IModelJsNative.SQLiteChangesetConflictArgs;\r\n\r\n /** A synchronous callback returning Skip, Replace, or Abort. Exceptions abort application and\r\n * propagate to the caller, who remains responsible for abandoning any partially applied changes.\r\n * Replace is valid only for data and primary-key insert conflicts.\r\n * The handler may query this database, but must not modify it (including through prepared\r\n * statements), close it, change its transaction, or recursively apply another changeset to it.\r\n * @internal\r\n */\r\n export type ChangesetConflictHandler = (args: ChangesetConflictArgs) => DbConflictResolution;\r\n\r\n /** A semver version range.\r\n * @see https://docs.npmjs.com/cli/v6/using-npm/semver\r\n */\r\n export type VersionRange = string;\r\n\r\n /**\r\n * A pair of semver [[SQLiteDb.VersionRange]]s, one for read and one for write, required to access a [[VersionedSqliteDb]].\r\n * If the version of the software attempting to read or write the database does not satisfy the range, access is denied.\r\n */\r\n export interface RequiredVersionRanges {\r\n /** a range of acceptable persistence versions for reading from a VersionedSqliteDb. */\r\n readonly readVersion: VersionRange;\r\n /** a range of acceptable persistence versions for writing to a VersionedSqliteDb. */\r\n readonly writeVersion: VersionRange;\r\n }\r\n\r\n /** interface for reading and writing to a blob in a SQLiteDb\r\n * @internal\r\n */\r\n export interface BlobIO {\r\n /** Close this BlobIO if it is opened.\r\n * @note this BlobIO *may* be reused after this call by calling `open` again.\r\n */\r\n close(): void;\r\n /** get the total number of bytes in the blob */\r\n getNumBytes(): number;\r\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\r\n isValid(): boolean;\r\n /** Open this BlobIO against a table/row/column in a Db */\r\n open(\r\n /** The database for the blob */\r\n db: IModelJsNative.AnyDb,\r\n args: {\r\n /** the name of the table for the blob*/\r\n tableName: string;\r\n /** the name of the column for the blob */\r\n columnName: string;\r\n /** The rowId of the blob */\r\n row: number;\r\n /** If true, open this BlobIO for write access */\r\n writeable?: boolean;\r\n }): void;\r\n /** Read from a blob\r\n * @returns the contents of the requested byte range\r\n */\r\n read(args: {\r\n /** The number of bytes to read */\r\n numBytes: number;\r\n /** starting offset within the blob to read */\r\n offset: number;\r\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\r\n blob?: ArrayBuffer;\r\n }): Uint8Array;\r\n /** Reposition this BlobIO to a new rowId\r\n * @note this BlobIO must be valid when this methods is called.\r\n */\r\n changeRow(row: number): void;\r\n /** Write to a blob */\r\n write(args: {\r\n /** The number of bytes to write */\r\n numBytes: number;\r\n /** starting offset within the blob to write */\r\n offset: number;\r\n /** the value to write */\r\n blob: ArrayBuffer;\r\n }): void;\r\n }\r\n\r\n /** Default transaction mode for SQLiteDbs.\r\n * @see https://www.sqlite.org/lang_transaction.html\r\n */\r\n export enum DefaultTxnMode {\r\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\r\n None = 0,\r\n /** A deferred transaction is started when the file is first opened. This is the default. */\r\n Deferred = 1,\r\n /** An immediate transaction is started when the file is first opened. */\r\n Immediate = 2,\r\n /** An exclusive transaction is started when the file is first opened. */\r\n Exclusive = 3\r\n }\r\n\r\n /** parameters common to opening or creating a new SQLiteDb */\r\n export interface OpenOrCreateParams {\r\n /** If true, do not require that the `be_Prop` table exist */\r\n rawSQLite?: boolean;\r\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\r\n immutable?: boolean;\r\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\r\n skipFileCheck?: boolean;\r\n /** the default transaction mode\r\n * @see [[SQLiteDb.DefaultTxnMode]]\r\n */\r\n defaultTxn?: 0 | 1 | 2 | 3;\r\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\r\n queryParam?: string;\r\n }\r\n\r\n /** Parameters for opening an existing SQLiteDb */\r\n export interface OpenParams extends OpenOrCreateParams {\r\n /** use OpenMode.ReadWrite to open the file with write access */\r\n openMode: OpenMode;\r\n }\r\n\r\n /** Size of a SQLiteDb page in bytes */\r\n export interface PageSize {\r\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\r\n pageSize?: number;\r\n }\r\n\r\n /** Parameters for creating a new SQLiteDb */\r\n export type CreateParams = OpenOrCreateParams & PageSize;\r\n\r\n /** Arguments for `SqliteDb.withOpenDb` */\r\n export interface WithOpenDbArgs {\r\n /** The name of the database to open */\r\n dbName: string;\r\n /** either an object with the open parameters or just OpenMode value. */\r\n openMode?: OpenMode | SQLiteDb.OpenParams;\r\n /** @internal */\r\n container?: CloudSqlite.CloudContainer;\r\n }\r\n\r\n /** Arguments for `SQLiteDb.vacuum` */\r\n export interface VacuumDbArgs extends PageSize {\r\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\r\n into?: LocalFileName;\r\n }\r\n}\r\n"]}
@@ -10,11 +10,11 @@ import type { ChangeElementModelProps, ChangeElementParentProps, IModelDb, Inser
10
10
  import type { SettingsContainer } from "./workspace/Settings";
11
11
  /** Options for bulk deleting elements from an iModelDb.
12
12
  * @beta
13
- * @deprecated Options are no longer used and [[EditTxn.deleteElements]] ignores this argument.
13
+ * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Options are no longer used and [[EditTxn.deleteElements]] ignores this argument.
14
14
  */
15
15
  export interface BulkDeleteElementsArgs {
16
16
  /**
17
- * @deprecated Skipping FK constraint validation is no longer supported.
17
+ * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Skipping FK constraint validation is no longer supported.
18
18
  */
19
19
  skipFKConstraintValidations?: boolean;
20
20
  }
@@ -65,7 +65,7 @@ export interface BulkDeleteElementsResult {
65
65
  * Nothing was deleted, including requested ids that are not listed.
66
66
  * - On `DeletionFailed`: every requested id (the iModel may be partially modified; abandon the current txn).
67
67
  * - On `Success`: empty.
68
- * @deprecated Use `failures` for a more detailed failure report.
68
+ * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Use `failures` for a more detailed failure report.
69
69
  */
70
70
  failedIds: Id64Set;
71
71
  }
@@ -1 +1 @@
1
- {"version":3,"file":"EditTxn.js","sourceRoot":"","sources":["../../src/EditTxn.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F;;GAEG;AAEH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAA2C,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC1I,OAAO,EAAE,YAAY,EAAqB,YAAY,EAAsB,YAAY,EAAmC,WAAW,EAAkD,MAAM,oBAAoB,CAAC;AACnN,OAAO,EAAE,OAAO,EAAgB,MAAM,sBAAsB,CAAC;AAK7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,iBAAiB,EAAE,SAAS,EAAE,kCAAkC,EAAE,kBAAkB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAa/K;;;GAGG;AACH,MAAM,CAAN,IAAY,uBASX;AATD,WAAY,uBAAuB;IACjC,8FAA8F;IAC9F,yGAA0B,CAAA;IAC1B,+EAA+E;IAC/E,2FAAmB,CAAA;IACnB,6IAA6I;IAC7I,6FAAoB,CAAA;IACpB,oDAAoD;IACpD,yFAAkB,CAAA;AACpB,CAAC,EATW,uBAAuB,KAAvB,uBAAuB,QASlC;AAyCD;;;GAGG;AACH,MAAM,CAAN,IAAY,wBAOX;AAPD,WAAY,wBAAwB;IAClC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gBACP,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,MAAM,YAAY,OAAO,EAAE,CAAC;YAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;gBAC3B,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;gBAC1B,OAAO,KAAK,CAAC;YACf,CAAC,EAAE,cAAc,CAAC,CAAC;QACrB,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\n/** @packageDocumentation\r\n * @module iModels\r\n */\r\n\r\nimport { DbResult, Id64, Id64Arg, Id64Array, Id64Set, Id64String, IModelStatus, ITwinError, Logger, OpenMode } from \"@itwin/core-bentley\";\r\nimport { EcefLocation, EcefLocationProps, EditTxnError, ElementAspectProps, ElementError, ElementProps, FilePropertyProps, IModelError, ModelProps, RelationshipProps, SaveChangesArgs } from \"@itwin/core-common\";\r\nimport { Range3d, Range3dProps } from \"@itwin/core-geometry\";\r\nimport type { CloudSqlite } from \"./CloudSqlite\";\r\nimport type { ImplicitWriteEnforcement } from \"./IModelHost\";\r\nimport type { ChangeElementModelProps, ChangeElementParentProps, IModelDb, InsertElementOptions, UpdateModelOptions } from \"./IModelDb\";\r\nimport type { SettingsContainer } from \"./workspace/Settings\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { _activeTxn, _cache, _instanceKeyCache, _nativeDb, _refreshGeographicCoordinateSystem, _updateIModelProps, _verifyChannel, _verifyTxnWrite } from \"./internal/Symbols\";\r\n\r\n/** Options for bulk deleting elements from an iModelDb.\r\n * @beta\r\n * @deprecated Options are no longer used and [[EditTxn.deleteElements]] ignores this argument.\r\n */\r\nexport interface BulkDeleteElementsArgs {\r\n /**\r\n * @deprecated Skipping FK constraint validation is no longer supported.\r\n */\r\n skipFKConstraintValidations?: boolean;\r\n}\r\n\r\n/**\r\n * Why an element could not be deleted by [[EditTxn.deleteElements]].\r\n * @beta\r\n */\r\nexport enum BulkDeleteFailureReason {\r\n /** A row outside the delete set references it via a NO ACTION / RESTRICT / SET DEFAULT FK. */\r\n ReferencedByForeignKey = 0,\r\n /** It is a DefinitionElement still used by elements outside the delete set. */\r\n DefinitionInUse = 1,\r\n /** It is one of the elements every iModel must keep: the root Subject, the DictionaryModel partition or the RealityDataSources partition. */\r\n ProtectedElement = 2,\r\n /** Its handler belongs to a read-only DgnDomain. */\r\n ReadOnlyDomain = 3,\r\n}\r\n\r\n/**\r\n * One element that could not be deleted by [[EditTxn.deleteElements]], and why.\r\n * @beta\r\n */\r\nexport interface BulkDeleteFailure {\r\n /** The id of the element that could not be deleted. */\r\n elementId: Id64String;\r\n /** Why the element could not be deleted. */\r\n reason: BulkDeleteFailureReason;\r\n}\r\n\r\n/**\r\n * Result of a bulk element delete operation.\r\n * @beta\r\n */\r\nexport interface BulkDeleteElementsResult {\r\n /** Overall status of the bulk delete operation. See [[BulkDeleteElementsStatus]]. */\r\n status: BulkDeleteElementsStatus;\r\n /** The raw SQLite result code from the underlying SQL DELETE. Only meaningful when `status === DeletionFailed`. */\r\n sqlDeleteStatus: DbResult;\r\n /**\r\n * One entry per element that blocks the deletion, with the reason. Only populated on `ConstraintViolation`.\r\n * Empty on `Success` and `DeletionFailed`.\r\n * Because the whole expanded delete set is validated, a reported element may be a child or sub-model member\r\n * that was not in the requested ids; its requested ancestor is not listed separately.\r\n */\r\n failures: BulkDeleteFailure[];\r\n /**\r\n * The set of element ids that could not be deleted.\r\n * - On `ConstraintViolation`: the unique element ids appearing in `failures`. May include cascaded descendants\r\n * that were not in the requested ids, so this is not guaranteed to be a subset of the input. Never empty.\r\n * Nothing was deleted, including requested ids that are not listed.\r\n * - On `DeletionFailed`: every requested id (the iModel may be partially modified; abandon the current txn).\r\n * - On `Success`: empty.\r\n * @deprecated Use `failures` for a more detailed failure report.\r\n */\r\n failedIds: Id64Set;\r\n}\r\n\r\n/**\r\n * Status of a bulk element delete operation, mirroring the C++ `BulkDeleteStatus` enum.\r\n * @beta\r\n */\r\nexport enum BulkDeleteElementsStatus {\r\n /** All supplied elements were deleted successfully. */\r\n Success = 0,\r\n /** Nothing was deleted because some elements in the (expanded) delete set are still referenced from outside the set; see `failures` for the violators. */\r\n ConstraintViolation = 1,\r\n /** An internal error occurred. The iModel may be partially modified; the caller must abandon the current txn. `failures` will be empty. */\r\n DeletionFailed = 2,\r\n}\r\n\r\n/**\r\n * Represents an explicit editing transaction for an iModel.\r\n *\r\n * An explicit EditTxn lets callers define a deliberate unit of work by choosing when editing\r\n * starts (`start`) and how it ends (`end()` / `end(\"save\")` or `end(\"abandon\")`). This avoids mixing\r\n * unrelated edits into one implicit unit of work and makes save/rollback boundaries explicit.\r\n *\r\n * Explicit EditTxn instances must be active before mutating operations are performed, regardless of enforcement level.\r\n * In other words, explicit transaction behavior is independent of `implicitWriteEnforcement`.\r\n *\r\n * @see [EditTxn transaction model and migration guidance]($docs/learning/backend/EditTxn.md)\r\n *\r\n * *During indirect changes (commit processing):* Use callback args (`indirectEditTxn`) in callbacks like\r\n * [[Relationship.onRootChangedArg]] and [[Relationship.onDeletedDependencyArg]] that fire during indirect processing.\r\n *\r\n * @beta\r\n */\r\nexport class EditTxn {\r\n /** Controls how writes through the implicit transaction are handled.\r\n *\r\n * This does not relax activation requirements for explicit transactions: explicit EditTxn writes\r\n * must always come from the active EditTxn.\r\n *\r\n * - `allow`: allow implicit writes for backwards compatibility, even while an explicit EditTxn is active.\r\n * - `log`: allow implicit writes but log `implicit-txn-write-disallowed` errors.\r\n * - `throw`: reject implicit writes with `implicit-txn-write-disallowed`.\r\n *\r\n * This is initialized from [[IModelHostOptions.implicitWriteEnforcement]] during [[IModelHost.startup]].\r\n *\r\n * Defaults to `allow` for backwards compatibility.\r\n * @beta\r\n */\r\n public static implicitWriteEnforcement: ImplicitWriteEnforcement = \"allow\";\r\n\r\n /** The iModel this EditTxn may modify. */\r\n public readonly iModel: IModelDb;\r\n\r\n /** Default description passed to [[saveChanges]] when saving this transaction. */\r\n public description: string;\r\n\r\n /** True if this transaction currently owns the iModel write surface. */\r\n public get isActive(): boolean {\r\n return this.iModel[_activeTxn] === this;\r\n }\r\n\r\n public constructor(iModel: IModelDb, description: string) {\r\n this.iModel = iModel;\r\n this.description = description;\r\n }\r\n\r\n public verifyWriteable(): void {\r\n this.iModel[_verifyTxnWrite]();\r\n // Explicit transactions must always be active before writing.\r\n if (!this.isActive)\r\n EditTxnError.throwError(\"not-active\", \"EditTxn is not active\", this.iModel.key);\r\n }\r\n\r\n /** Start this EditTxn, making it the active transaction for the iModel.\r\n * @throws EditTxnError if this EditTxn is already active, another EditTxn is already active, or if unsaved changes are present.\r\n * @throws IModelError if the geographic coordinate system is being restored.\r\n */\r\n public start(): void {\r\n this.iModel[_verifyTxnWrite]();\r\n if (this.isActive)\r\n EditTxnError.throwError(\"already-active\", \"This EditTxn is already active\", this.iModel.key);\r\n\r\n const activeTxn = this.iModel[_activeTxn];\r\n if (undefined !== activeTxn)\r\n EditTxnError.throwError(\"already-active\", \"Cannot start EditTxn while another EditTxn is active\", this.iModel.key, activeTxn.description);\r\n\r\n if (this.iModel[_nativeDb].hasUnsavedChanges())\r\n EditTxnError.throwError(\"unsaved-changes\", \"Cannot start a new EditTxn with unsaved changes\", this.iModel.key);\r\n\r\n this.iModel[_activeTxn] = this;\r\n }\r\n\r\n /** End this EditTxn, either by saving or abandoning the changes.\r\n * @param mode Whether to \"save\" or \"abandon\" the changes. Defaults to \"save\".\r\n * @param args Save changes arguments when saving.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if saving changes fails.\r\n * @throws Re-throws any error propagated by a geographic coordinate system restoration listener after completing abandonment.\r\n */\r\n public end(): void;\r\n public end(mode: \"save\" | \"abandon\", args?: string | SaveChangesArgs): void;\r\n public end(mode: \"save\" | \"abandon\" = \"save\", args?: string | SaveChangesArgs): void {\r\n if (!this.isActive)\r\n EditTxnError.throwError(\"not-active\", \"EditTxn is not active\", this.iModel.key);\r\n\r\n if (mode === \"save\") {\r\n this.saveChanges(args);\r\n } else {\r\n this.abandonDatabaseChanges();\r\n }\r\n this.iModel[_activeTxn] = undefined;\r\n if (mode === \"abandon\")\r\n this.iModel[_refreshGeographicCoordinateSystem]();\r\n }\r\n\r\n /** Invoked when the owning iModel is closing.\r\n * The base implementation commits unsaved changes. Subclasses may override to customize how\r\n * their changes are handled before the iModel closes.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if saving on close fails.\r\n */\r\n public onClose(): void {\r\n if (!this.iModel.isReadonly && this.iModel[_nativeDb].hasUnsavedChanges())\r\n this.saveChanges();\r\n }\r\n\r\n /** Abandon database changes while keeping this EditTxn active.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public abandonChanges(): void {\r\n this.abandonDatabaseChanges();\r\n this.iModel[_refreshGeographicCoordinateSystem]();\r\n }\r\n\r\n private abandonDatabaseChanges(): void {\r\n this.verifyWriteable();\r\n this.iModel.clearCaches({ instanceCachesOnly: true });\r\n this.iModel[_nativeDb].abandonChanges();\r\n }\r\n\r\n /** Save changes with additional arguments.\r\n * @param args Save changes arguments.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the iModel is readonly, if indirect changes are active, or if the native save fails.\r\n */\r\n public saveChanges(args?: string | SaveChangesArgs): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n if (iModel.openMode === OpenMode.Readonly)\r\n throw new IModelError(IModelStatus.ReadOnly, \"IModelDb was opened read-only\");\r\n\r\n if (iModel.isBriefcaseDb() && iModel.txns.isIndirectChanges)\r\n throw new IModelError(IModelStatus.BadRequest, \"Cannot save changes while in an indirect change scope\");\r\n\r\n args ??= this.description;\r\n const saveArgs = typeof args === \"string\" ? { description: args } : args;\r\n const stat = iModel[_nativeDb].saveChanges(JSON.stringify(saveArgs));\r\n if (DbResult.BE_SQLITE_ERROR_PropagateChangesFailed === stat)\r\n throw new IModelError(stat, \"Could not save changes due to propagation failure.\");\r\n\r\n if (DbResult.BE_SQLITE_OK !== stat)\r\n throw new IModelError(stat, `Could not save changes (${saveArgs.description})`);\r\n }\r\n\r\n /** Insert a new element into the iModel.\r\n * @param elProps The properties of the new element.\r\n * @returns The newly inserted element's Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if insertion fails.\r\n */\r\n public insertElement(elProps: ElementProps, options?: InsertElementOptions): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n options ??= {};\r\n this.iModel.elements[_cache].delete({\r\n id: elProps.id,\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n return elProps.id = this.iModel[_nativeDb].insertElement(elProps, options);\r\n } catch (err: any) {\r\n err.message = `Error inserting element [${err.message}]`;\r\n err.metadata = { elProps };\r\n throw err;\r\n }\r\n }\r\n\r\n /** Update an existing element in the iModel.\r\n * @param elProps The properties to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if update fails.\r\n */\r\n public updateElement<T extends ElementProps>(elProps: Partial<T>): void {\r\n this.verifyWriteable();\r\n try {\r\n if (elProps.id) {\r\n this.iModel.elements[_instanceKeyCache].deleteById(elProps.id);\r\n } else {\r\n this.iModel.elements[_instanceKeyCache].delete({\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n }\r\n this.iModel.elements[_cache].delete({\r\n id: elProps.id,\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n this.iModel[_nativeDb].updateElement(elProps);\r\n } catch (err: any) {\r\n err.message = `Error updating element [${err.message}], id: ${elProps.id}`;\r\n err.metadata = { elProps };\r\n throw err;\r\n }\r\n }\r\n\r\n /** Delete elements from the iModel.\r\n * @param ids The Ids of the elements to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if deletion fails.\r\n */\r\n public deleteElement(ids: Id64Arg): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n Id64.toIdSet(ids).forEach((id) => {\r\n try {\r\n this.iModel.elements[_cache].delete({ id });\r\n this.iModel.elements[_instanceKeyCache].deleteById(id);\r\n iModel[_nativeDb].deleteElement(id);\r\n } catch (err: any) {\r\n err.message = `Error deleting element [${err.message}], id: ${id}`;\r\n err.metadata = { elementId: id };\r\n throw err;\r\n }\r\n });\r\n }\r\n\r\n /** Change the parent of an element within its model.\r\n *\r\n * The new parent must be in the same model as the element. Cross-model reparenting is not allowed;\r\n * use [[changeElementModel]] only to move root elements between models.\r\n * Only the target element is reparented — its children and their model membership are unaffected.\r\n *\r\n * **Blocked cases** (will throw):\r\n * - The new parent is in a different model than the element.\r\n * - Element has a `ParentElement`-scoped code (code uniqueness is tied to the parent; use delete+insert instead).\r\n *\r\n * **Allowed cases**:\r\n * - Element has a `Repository`-scoped code (unique across entire iModel — unaffected by the parent change).\r\n * - Element has a `RelatedElement`-scoped code (scope element is independent of the parent).\r\n * - Element has a `Model`-scoped code (the model does not change, so the code remains valid).\r\n * - Element has no meaningful code (empty code).\r\n *\r\n * Channel verification is performed on the element's model.\r\n * Lock enforcement: requires an exclusive lock on the element, and a shared lock on the new parent.\r\n * @param props The reparent parameters: element id and new parent id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if the operation fails.\r\n * @beta\r\n */\r\n public changeElementParent(props: ChangeElementParentProps): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n\r\n // Lock enforcement: exclusive lock on the element being reparented, shared lock on the new parent.\r\n iModel.locks.checkExclusiveLock(props.id, \"element\", \"changeParent\");\r\n iModel.locks.checkSharedLock(props.parentId, \"parent\", \"changeParent\");\r\n\r\n // The new parent must be in the same model as the element. Cross-model reparenting is not\r\n // allowed here; changeElementModel only moves root elements between models. Check this up\r\n // front so consumers get a clear error instead of the addon's lower-level \"wrong model\" status.\r\n const sourceModelId = iModel.elements.getElementProps({ id: props.id }).model;\r\n const parentModelId = iModel.elements.getElementProps({ id: props.parentId }).model;\r\n if (sourceModelId !== parentModelId)\r\n ElementError.throwError(\"invalid-arguments\", `cannot reparent element '${props.id}' to a parent in a different model ('${parentModelId}' != '${sourceModelId}'); changeElementModel only moves root elements between models`);\r\n\r\n // Channel verification on the element's model.\r\n iModel.channels[_verifyChannel](sourceModelId);\r\n\r\n // Invalidate caches for the element being reparented.\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n\r\n try {\r\n iModel[_nativeDb].changeElementParent({ id: props.id, parentId: props.parentId });\r\n } catch (err: any) {\r\n err.message = `Error changing element parent [${err.message}], id: ${props.id}, parentId: ${props.parentId}`;\r\n err.metadata = { props };\r\n throw err;\r\n }\r\n\r\n // The model is unchanged and descendants are not moved, so only the reparented element's cache is stale.\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n }\r\n\r\n /** Change the model of a root element, making it a root element in the new model.\r\n *\r\n * The element must not have a parent.\r\n * The element's entire subtree moves with it: BIS requires a parent and all of its children to reside\r\n * in the same model, so every descendant of the element is relocated into the target model as well.\r\n * The parent-child hierarchy is preserved. The whole subtree is validated before anything is moved, so\r\n * a rejected change leaves the iModel untouched.\r\n *\r\n * **Blocked cases** (will throw):\r\n * - Element has a parent (only root elements can be moved between models).\r\n * - Any element in the subtree has a `Model`-scoped code (code uniqueness is tied to the source model; use delete+insert instead).\r\n * - The moved (root) element has a `ParentElement`-scoped code (use delete+insert instead). A descendant's `ParentElement`-scoped code is allowed, because its parent moves with it.\r\n *\r\n * **Allowed cases** (for any element in the subtree):\r\n * - A `Repository`-scoped code (unique across entire iModel — unaffected by the model change).\r\n * - A `RelatedElement`-scoped code (scope element is independent of the model).\r\n * - No meaningful code (empty code).\r\n *\r\n * The source and target models must be of the same class (classFullName must match exactly).\r\n * Channel verification is performed on both the source and target models.\r\n * Lock enforcement: requires an exclusive lock on every element in the moved subtree, and a shared lock on the target model.\r\n * @param props The model change parameters: element id and target model id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if the operation fails.\r\n * @beta\r\n */\r\n public changeElementModel(props: ChangeElementModelProps): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n\r\n // Resolve the source model\r\n const sourceModelId = iModel.elements.getElementProps({ id: props.id }).model;\r\n\r\n // Channel verification on the source model\r\n iModel.channels[_verifyChannel](sourceModelId);\r\n\r\n // Model type check: source and target models must be the same class\r\n const sourceModel = iModel.models.getModel(sourceModelId);\r\n const targetModel = iModel.models.getModel(props.modelId);\r\n if (sourceModel.classFullName !== targetModel.classFullName)\r\n ElementError.throwError(\"model-type-mismatch\", `cannot move element from model of type '${sourceModel.classFullName}' to model of type '${targetModel.classFullName}'`);\r\n\r\n // Shared lock on target model\r\n iModel.locks.checkSharedLock(props.modelId, \"model\", \"changeModel\");\r\n\r\n // Lock enforcement: every element in the subtree is updated by the native bulk move.\r\n const subtreeIds = this.collectSubtreeIds(props.id);\r\n for (const id of subtreeIds)\r\n iModel.locks.checkExclusiveLock(id, \"element\", \"changeModel\");\r\n\r\n // Channel verification on the target model\r\n iModel.channels[_verifyChannel](props.modelId);\r\n\r\n // Invalidate caches\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n\r\n try {\r\n iModel[_nativeDb].changeElementModel({ id: props.id, modelId: props.modelId });\r\n } catch (err: any) {\r\n err.message = `Error changing element model [${err.message}], id: ${props.id}, modelId: ${props.modelId}`;\r\n err.metadata = { props };\r\n throw err;\r\n }\r\n\r\n // The move relocates the element's entire subtree into the target model (BIS requires a parent and\r\n // its children to reside in the same model). Every descendant's cached props therefore hold a stale\r\n // `model`, so invalidate the whole subtree rather than just the target element.\r\n for (const id of subtreeIds) {\r\n iModel.elements[_cache].delete({ id });\r\n iModel.elements[_instanceKeyCache].deleteById(id);\r\n }\r\n\r\n // Moving the subtree changes the membership - and therefore the geometry-derived state such as\r\n // GeometricModel.geometryGuid - of both the source and target models. Element insert/update/delete\r\n // invalidate models[_cache] via Element.onInserted/onUpdated/onDeleted for the same reason, but the\r\n // native changeElementModel does not fire those element callbacks, so invalidate both affected models\r\n // here to keep the model cache contract local to this wrapper.\r\n iModel.models[_cache].delete(sourceModelId);\r\n iModel.models[_cache].delete(props.modelId);\r\n }\r\n\r\n /** Collect an element together with all of its descendants by walking the `ElementOwnsChildElements`\r\n * hierarchy depth-first. Used to invalidate the cached props of every element affected by a subtree move.\r\n */\r\n private collectSubtreeIds(rootId: Id64String): Id64String[] {\r\n const ids: Id64String[] = [];\r\n const stack: Id64String[] = [rootId];\r\n for (let id = stack.pop(); undefined !== id; id = stack.pop()) {\r\n ids.push(id);\r\n for (const childId of this.iModel.elements.queryChildren(id))\r\n stack.push(childId);\r\n }\r\n return ids;\r\n }\r\n\r\n /**\r\n * Delete multiple elements from the iModel in a single bulk operation.\r\n *\r\n * Child elements and sub-model contents of the requested elements are deleted along with them.\r\n *\r\n * The operation is all-or-nothing:\r\n * - On `Success`, all elements (and their children / sub-model contents) were deleted.\r\n * - On `ConstraintViolation`, nothing was deleted and [[BulkDeleteElementsResult.failures]] lists every element in the\r\n * expanded delete set that is still referenced from outside the set, and why. Fix or include those referencing elements and retry.\r\n * - On `DeletionFailed` (an unexpected SQLite error) the iModel may be partially modified and the caller must abandon the current txn.\r\n *\r\n * @param ids The ids of the elements to delete. All ids must be well-formed and valid [[Id64String]]s.\r\n * @param _deleteOptions Deprecated and ignored; kept for backward compatibility of the signature.\r\n * @returns A result object describing the outcome of the operation and the elements that block it (if any).\r\n * @throws [[ITwinError]] if any of the supplied ids are not well-formed/valid [[Id64String]]s.\r\n * @beta\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-deprecated\r\n public deleteElements(ids: Id64Array, _deleteOptions?: BulkDeleteElementsArgs): BulkDeleteElementsResult {\r\n this.verifyWriteable();\r\n const invalidIds: Id64Set = new Set<Id64String>();\r\n for (const id of ids) {\r\n if (!Id64.isValidId64(id))\r\n invalidIds.add(id);\r\n }\r\n\r\n if (invalidIds.size > 0)\r\n ITwinError.throwError({ message: `Invalid element ids: ${Array.from(invalidIds).join(\", \")}`, iTwinErrorId: { scope: \"imodel\", key: \"invalid-arguments\" } });\r\n\r\n const nativeResult = this.iModel[_nativeDb].deleteElements(ids);\r\n\r\n // When deletion fails with `DeletionFailed`, all requested ids are returned to maintain backward compatibilty.\r\n // Once `failedIds` is deprecated, we will change this to throw instead as this is a SQLite failure.\r\n const failedIds = nativeResult.status === BulkDeleteElementsStatus.DeletionFailed\r\n ? new Set<Id64String>(ids)\r\n : new Set<Id64String>(nativeResult.failures.map((failure: BulkDeleteFailure) => failure.elementId));\r\n\r\n const result: BulkDeleteElementsResult = {\r\n status: nativeResult.status,\r\n sqlDeleteStatus: nativeResult.sqlDeleteStatus,\r\n failures: nativeResult.failures,\r\n // `failedIds` is deprecated. `failures` provides a more comprehensive error report.\r\n // We still need to return the deprecated `failedIds` to maintain backward compatibility.\r\n failedIds,\r\n };\r\n\r\n // Nothing was deleted on ConstraintViolation; on DeletionFailed the caller must abandon the txn, which restores the cached state.\r\n if (result.status !== BulkDeleteElementsStatus.Success)\r\n return result;\r\n\r\n // Native deletion also nulls logical navigation properties on surviving elements that referenced the deleted ones,\r\n // so evicting only the requested ids would leave stale cached referrers. Clear all instance caches.\r\n this.iModel.clearCaches({ instanceCachesOnly: true });\r\n\r\n return result;\r\n }\r\n\r\n /** Insert a new aspect into the iModel.\r\n * @param aspectProps The properties of the new aspect.\r\n * @returns The newly inserted aspect Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if insertion fails.\r\n */\r\n public insertAspect(aspectProps: ElementAspectProps): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n return this.iModel[_nativeDb].insertElementAspect(aspectProps);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error inserting ElementAspect [${err.message}], class: ${aspectProps.classFullName}`, aspectProps);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update an existing aspect in the iModel.\r\n * @param aspectProps The properties of the aspect to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if update fails.\r\n */\r\n public updateAspect(aspectProps: ElementAspectProps): void {\r\n this.verifyWriteable();\r\n try {\r\n this.iModel[_nativeDb].updateElementAspect(aspectProps);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error updating ElementAspect [${err.message}], id: ${aspectProps.id}`, aspectProps);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Delete one or more aspects from the iModel.\r\n * @param aspectInstanceIds The Ids of the aspects to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if deletion fails.\r\n */\r\n public deleteAspect(aspectInstanceIds: Id64Arg): void {\r\n this.verifyWriteable();\r\n Id64.toIdSet(aspectInstanceIds).forEach((aspectInstanceId) => {\r\n try {\r\n this.iModel[_nativeDb].deleteElementAspect(aspectInstanceId);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error deleting ElementAspect [${err.message}], id: ${aspectInstanceId}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n });\r\n }\r\n\r\n /** Delete definition elements from the iModel when they are not referenced.\r\n * @param definitionElementIds The Ids of the definition elements to attempt to delete.\r\n * @returns The set of definition elements that were still in use and therefore not deleted.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if usage queries fail.\r\n */\r\n public deleteDefinitionElements(definitionElementIds: Id64Array): Id64Set {\r\n this.verifyWriteable();\r\n const usageInfo = this.iModel[_nativeDb].queryDefinitionElementUsage(definitionElementIds);\r\n if (!usageInfo)\r\n throw new IModelError(IModelStatus.BadRequest, \"Error querying for DefinitionElement usage\");\r\n\r\n const usedIdSet = usageInfo.usedIds ? Id64.toIdSet(usageInfo.usedIds) : new Set<Id64String>();\r\n const deleteIfUnused = (ids: Id64Array | undefined, used: Id64Set): void => {\r\n ids?.forEach((id) => {\r\n if (!used.has(id))\r\n this.deleteElement(id);\r\n });\r\n };\r\n\r\n try {\r\n this.iModel[_nativeDb].beginPurgeOperation();\r\n deleteIfUnused(usageInfo.spatialCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.drawingCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.viewDefinitionIds, usedIdSet);\r\n deleteIfUnused(usageInfo.geometryPartIds, usedIdSet);\r\n deleteIfUnused(usageInfo.lineStyleIds, usedIdSet);\r\n deleteIfUnused(usageInfo.renderMaterialIds, usedIdSet);\r\n deleteIfUnused(usageInfo.subCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.textureIds, usedIdSet);\r\n deleteIfUnused(usageInfo.displayStyleIds, usedIdSet);\r\n deleteIfUnused(usageInfo.categorySelectorIds, usedIdSet);\r\n deleteIfUnused(usageInfo.modelSelectorIds, usedIdSet);\r\n if (usageInfo.otherDefinitionElementIds)\r\n this.deleteElement(usageInfo.otherDefinitionElementIds);\r\n } finally {\r\n this.iModel[_nativeDb].endPurgeOperation();\r\n }\r\n\r\n if (usageInfo.viewDefinitionIds) {\r\n // Recheck view-related definitions after deleting view definitions that may have been their last reference.\r\n let viewRelatedIds: Id64Array = [];\r\n if (usageInfo.displayStyleIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.displayStyleIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (usageInfo.categorySelectorIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.categorySelectorIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (usageInfo.modelSelectorIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.modelSelectorIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (viewRelatedIds.length > 0) {\r\n const viewRelatedUsageInfo = this.iModel[_nativeDb].queryDefinitionElementUsage(viewRelatedIds);\r\n if (viewRelatedUsageInfo) {\r\n const usedViewRelatedIdSet: Id64Set = viewRelatedUsageInfo.usedIds ? Id64.toIdSet(viewRelatedUsageInfo.usedIds) : new Set<Id64String>();\r\n try {\r\n this.iModel[_nativeDb].beginPurgeOperation();\r\n deleteIfUnused(viewRelatedUsageInfo.displayStyleIds, usedViewRelatedIdSet);\r\n deleteIfUnused(viewRelatedUsageInfo.categorySelectorIds, usedViewRelatedIdSet);\r\n deleteIfUnused(viewRelatedUsageInfo.modelSelectorIds, usedViewRelatedIdSet);\r\n } finally {\r\n this.iModel[_nativeDb].endPurgeOperation();\r\n }\r\n\r\n viewRelatedIds.forEach((id) => {\r\n if (!usedViewRelatedIdSet.has(id))\r\n usedIdSet.delete(id);\r\n });\r\n }\r\n }\r\n }\r\n\r\n return usedIdSet;\r\n }\r\n\r\n /** Insert a new model into the iModel.\r\n * @param props The data for the new model.\r\n * @returns The newly inserted model's Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if insertion fails.\r\n */\r\n public insertModel(props: ModelProps): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n return props.id = this.iModel[_nativeDb].insertModel(props);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error inserting model [${err.message}], class=${props.classFullName}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update an existing model in the iModel.\r\n * @param props the properties of the model to change\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if update fails.\r\n */\r\n public updateModel(props: UpdateModelOptions): void {\r\n this.verifyWriteable();\r\n try {\r\n if (props.id)\r\n this.iModel.models[_cache].delete(props.id);\r\n\r\n this.iModel[_nativeDb].updateModel(props);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error updating model [${err.message}], id: ${props.id}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update the geometry guid of a model.\r\n * @param modelId The Id of the model to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the update fails.\r\n */\r\n public updateGeometryGuid(modelId: Id64String): void {\r\n this.verifyWriteable();\r\n this.iModel.models[_cache].delete(modelId);\r\n const error = this.iModel[_nativeDb].updateModelGeometryGuid(modelId);\r\n if (error !== IModelStatus.Success)\r\n throw new IModelError(error, `Error updating geometry guid for model ${modelId}`);\r\n }\r\n\r\n /** Delete models from the iModel.\r\n * @param ids The Ids of the models to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if deletion fails.\r\n */\r\n public deleteModel(ids: Id64Arg): void {\r\n this.verifyWriteable();\r\n Id64.toIdSet(ids).forEach((id) => {\r\n try {\r\n this.iModel.models[_cache].delete(id);\r\n this.iModel.models[_instanceKeyCache].deleteById(id);\r\n this.iModel[_nativeDb].deleteModel(id);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error deleting model [${err.message}], id: ${id}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n });\r\n }\r\n\r\n /** Insert a new relationship into the iModel.\r\n * @param props The properties of the new relationship.\r\n * @returns The Id of the newly inserted relationship.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the class is invalid for link-table insertion.\r\n */\r\n public insertRelationship(props: RelationshipProps): Id64String {\r\n this.verifyWriteable();\r\n if (!this.iModel[_nativeDb].isLinkTableRelationship(props.classFullName.replace(\".\", \":\")))\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Class '${props.classFullName}' must be a relationship class and it should be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.`);\r\n\r\n return props.id = this.iModel[_nativeDb].insertLinkTableRelationship(props);\r\n }\r\n\r\n /** Update an existing relationship in the iModel.\r\n * @param props the properties of the relationship to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateRelationship(props: RelationshipProps): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].updateLinkTableRelationship(props);\r\n }\r\n\r\n /** Delete a relationship from the iModel.\r\n * @param props The properties of the relationship to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteRelationship(props: RelationshipProps): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].deleteLinkTableRelationship(props);\r\n }\r\n\r\n /** Delete multiple relationships from the iModel.\r\n * @param props The properties of the relationships to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteRelationships(props: ReadonlyArray<RelationshipProps>): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].deleteLinkTableRelationships(props);\r\n }\r\n\r\n\r\n /** Save a file property to the iModel.\r\n * @param prop The file property to save.\r\n * @param strValue String value.\r\n * @param blobVal Blob value.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public saveFileProperty(prop: FilePropertyProps, strValue: string | undefined, blobVal?: Uint8Array): void {\r\n this.verifyWriteable();\r\n const imodel = this.iModel;\r\n if (imodel.isBriefcaseDb()) {\r\n if (imodel.txns.isIndirectChanges) {\r\n throw new IModelError(IModelStatus.BadRequest, \"Cannot save file property while in an indirect change scope\");\r\n }\r\n }\r\n imodel[_nativeDb].saveFileProperty(prop, strValue, blobVal);\r\n }\r\n\r\n /** Delete a file property from the iModel.\r\n * @param prop The file property to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteFileProperty(prop: FilePropertyProps): void {\r\n this.saveFileProperty(prop, undefined, undefined);\r\n }\r\n\r\n /** Update the project extents of the iModel.\r\n * @param newExtents The new project extents.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if extents are invalid.\r\n */\r\n public updateProjectExtents(newExtents: Range3dProps): void {\r\n this.verifyWriteable();\r\n const extents = Range3d.fromJSON(newExtents);\r\n if (extents.isNull)\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, \"Invalid project extents\");\r\n\r\n this.iModel.projectExtents = extents;\r\n this.updateIModelProps();\r\n }\r\n\r\n /** Update the ECEF location of the iModel.\r\n * @param ecef The new ECEF location.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateEcefLocation(ecef: EcefLocationProps): void {\r\n this.verifyWriteable();\r\n this.iModel.setEcefLocation(new EcefLocation(ecef));\r\n this.updateIModelProps();\r\n }\r\n\r\n /** Update the iModel props in the database from the current in-memory state.\r\n * An unchanged geographic coordinate system is not replaced or re-resolved from its dictionary identifiers.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateIModelProps(): void {\r\n this.verifyWriteable();\r\n this.iModel[_updateIModelProps]();\r\n }\r\n\r\n private static readonly _settingPropNamespace = \"settings\";\r\n private static readonly _viewStoreProperty: FilePropertyProps = { namespace: \"itwinjs\", name: \"DefaultViewStore\" };\r\n\r\n /** Save a `SettingDictionary` in this iModel.\r\n * @param name The name for the SettingDictionary. If a dictionary by that name already exists, its value is replaced.\r\n * @param dict The SettingDictionary object to stringify and save.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public saveSettingDictionary(name: string, dict: SettingsContainer): void {\r\n this.verifyWriteable();\r\n this.iModel.withSqliteStatement(\"REPLACE INTO be_Prop(id,SubId,TxnMode,Namespace,Name,strData) VALUES(0,0,0,?,?,?)\", (stmt) => {\r\n stmt.bindString(1, EditTxn._settingPropNamespace);\r\n stmt.bindString(2, name);\r\n stmt.bindString(3, JSON.stringify(dict));\r\n stmt.stepForWrite();\r\n });\r\n this.saveChanges(\"add settings\");\r\n }\r\n\r\n /** Delete a SettingDictionary from this iModel.\r\n * @param name The name of the dictionary to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public deleteSettingDictionary(name: string): void {\r\n this.verifyWriteable();\r\n this.iModel.withSqliteStatement(\"DELETE FROM be_Prop WHERE Namespace=? AND Name=?\", (stmt) => {\r\n stmt.bindString(1, EditTxn._settingPropNamespace);\r\n stmt.bindString(2, name);\r\n stmt.stepForWrite();\r\n });\r\n this.saveChanges(\"delete settings\");\r\n }\r\n\r\n /** Save a default ViewStore container reference in this iModel.\r\n * @param arg The cloud container properties for the ViewStore.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public saveDefaultViewStore(arg: CloudSqlite.ContainerProps): void {\r\n this.verifyWriteable();\r\n const props = { baseUri: arg.baseUri, containerId: arg.containerId, storageType: arg.storageType }; // sanitize to only known properties\r\n this.saveFileProperty(EditTxn._viewStoreProperty, JSON.stringify(props));\r\n this.saveChanges(\"update default ViewStore\");\r\n }\r\n}\r\n\r\n/** Execute a callback within an explicit editing transaction. A new [[EditTxn]] is created, started,\r\n * and passed to `fn`. If `fn` returns normally (or its returned Promise resolves), the transaction\r\n * is committed. If `fn` throws (or its returned Promise rejects), the transaction is abandoned —\r\n * none of the changes made during the callback are saved — and the error is re-thrown.\r\n * If abandonment also throws, logging that secondary error is attempted without allowing a logging failure to replace the callback error.\r\n *\r\n * This is the recommended way to perform a scoped unit of work on an iModel. It ensures that\r\n * edits are committed atomically on success and rolled back on failure, without the caller needing\r\n * to manage `start` / `end` manually.\r\n *\r\n * @param iModel The iModel to edit.\r\n * @param fn A callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns The value returned by `fn`.\r\n * @throws EditTxnError if the transaction cannot be started (e.g. unsaved changes or another EditTxn is active).\r\n * @throws Re-throws any error thrown by `fn` after abandoning the transaction.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, fn: (txn: EditTxn) => T): T;\r\n/** Execute a callback within an explicit editing transaction, supplying commit arguments.\r\n * @param iModel The iModel to edit.\r\n * @param saveArgs Description or structured arguments passed to [[EditTxn.saveChanges]] on save.\r\n * @param fn A callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns The value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgs: string | SaveChangesArgs, fn: (txn: EditTxn) => T): T;\r\n/** Execute an async callback within an explicit editing transaction.\r\n * @param iModel The iModel to edit.\r\n * @param fn An async callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns A Promise that resolves to the value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, fn: (txn: EditTxn) => Promise<T>): Promise<T>;\r\n/** Execute an async callback within an explicit editing transaction, supplying commit arguments.\r\n * @param iModel The iModel to edit.\r\n * @param saveArgs Description or structured arguments passed to [[EditTxn.saveChanges]] on save.\r\n * @param fn An async callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns A Promise that resolves to the value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgs: string | SaveChangesArgs, fn: (txn: EditTxn) => Promise<T>): Promise<T>;\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgsOrFn: string | SaveChangesArgs | ((txn: EditTxn) => T | Promise<T>), maybeFn?: (txn: EditTxn) => T | Promise<T>): T | Promise<T> {\r\n const saveArgs = \"function\" === typeof saveArgsOrFn ? undefined : saveArgsOrFn;\r\n const fn = \"function\" === typeof saveArgsOrFn ? saveArgsOrFn : maybeFn;\r\n\r\n if (undefined === fn)\r\n throw new Error(\"withEditTxn requires a callback\");\r\n\r\n const txn = new EditTxn(iModel, \"\");\r\n txn.start();\r\n\r\n const abandonOnError = (error: unknown): never => {\r\n try {\r\n if (txn.isActive)\r\n txn.end(\"abandon\");\r\n } catch (abandonError) {\r\n try {\r\n Logger.logError(BackendLoggerCategory.IModelDb, abandonError);\r\n } catch {\r\n throw error;\r\n }\r\n }\r\n throw error;\r\n };\r\n\r\n try {\r\n const result = fn(txn);\r\n if (result instanceof Promise) {\r\n return result.then((value) => {\r\n txn.end(\"save\", saveArgs);\r\n return value;\r\n }, abandonOnError);\r\n }\r\n\r\n txn.end(\"save\", saveArgs);\r\n return result;\r\n } catch (err) {\r\n return abandonOnError(err);\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"EditTxn.js","sourceRoot":"","sources":["../../src/EditTxn.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F;;GAEG;AAEH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAA2C,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC1I,OAAO,EAAE,YAAY,EAAqB,YAAY,EAAsB,YAAY,EAAmC,WAAW,EAAkD,MAAM,oBAAoB,CAAC;AACnN,OAAO,EAAE,OAAO,EAAgB,MAAM,sBAAsB,CAAC;AAK7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,iBAAiB,EAAE,SAAS,EAAE,kCAAkC,EAAE,kBAAkB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAa/K;;;GAGG;AACH,MAAM,CAAN,IAAY,uBASX;AATD,WAAY,uBAAuB;IACjC,8FAA8F;IAC9F,yGAA0B,CAAA;IAC1B,+EAA+E;IAC/E,2FAAmB,CAAA;IACnB,6IAA6I;IAC7I,6FAAoB,CAAA;IACpB,oDAAoD;IACpD,yFAAkB,CAAA;AACpB,CAAC,EATW,uBAAuB,KAAvB,uBAAuB,QASlC;AAyCD;;;GAGG;AACH,MAAM,CAAN,IAAY,wBAOX;AAPD,WAAY,wBAAwB;IAClC,uDAAuD;IACvD,6EAAW,CAAA;IACX,0JAA0J;IAC1J,qGAAuB,CAAA;IACvB,2IAA2I;IAC3I,2FAAkB,CAAA;AACpB,CAAC,EAPW,wBAAwB,KAAxB,wBAAwB,QAOnC;AAED;;;;;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vB,IAAI,MAAM,YAAY,OAAO,EAAE,CAAC;YAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;gBAC3B,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;gBAC1B,OAAO,KAAK,CAAC;YACf,CAAC,EAAE,cAAc,CAAC,CAAC;QACrB,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\n/** @packageDocumentation\r\n * @module iModels\r\n */\r\n\r\nimport { DbResult, Id64, Id64Arg, Id64Array, Id64Set, Id64String, IModelStatus, ITwinError, Logger, OpenMode } from \"@itwin/core-bentley\";\r\nimport { EcefLocation, EcefLocationProps, EditTxnError, ElementAspectProps, ElementError, ElementProps, FilePropertyProps, IModelError, ModelProps, RelationshipProps, SaveChangesArgs } from \"@itwin/core-common\";\r\nimport { Range3d, Range3dProps } from \"@itwin/core-geometry\";\r\nimport type { CloudSqlite } from \"./CloudSqlite\";\r\nimport type { ImplicitWriteEnforcement } from \"./IModelHost\";\r\nimport type { ChangeElementModelProps, ChangeElementParentProps, IModelDb, InsertElementOptions, UpdateModelOptions } from \"./IModelDb\";\r\nimport type { SettingsContainer } from \"./workspace/Settings\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { _activeTxn, _cache, _instanceKeyCache, _nativeDb, _refreshGeographicCoordinateSystem, _updateIModelProps, _verifyChannel, _verifyTxnWrite } from \"./internal/Symbols\";\r\n\r\n/** Options for bulk deleting elements from an iModelDb.\r\n * @beta\r\n * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Options are no longer used and [[EditTxn.deleteElements]] ignores this argument.\r\n */\r\nexport interface BulkDeleteElementsArgs {\r\n /**\r\n * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Skipping FK constraint validation is no longer supported.\r\n */\r\n skipFKConstraintValidations?: boolean;\r\n}\r\n\r\n/**\r\n * Why an element could not be deleted by [[EditTxn.deleteElements]].\r\n * @beta\r\n */\r\nexport enum BulkDeleteFailureReason {\r\n /** A row outside the delete set references it via a NO ACTION / RESTRICT / SET DEFAULT FK. */\r\n ReferencedByForeignKey = 0,\r\n /** It is a DefinitionElement still used by elements outside the delete set. */\r\n DefinitionInUse = 1,\r\n /** It is one of the elements every iModel must keep: the root Subject, the DictionaryModel partition or the RealityDataSources partition. */\r\n ProtectedElement = 2,\r\n /** Its handler belongs to a read-only DgnDomain. */\r\n ReadOnlyDomain = 3,\r\n}\r\n\r\n/**\r\n * One element that could not be deleted by [[EditTxn.deleteElements]], and why.\r\n * @beta\r\n */\r\nexport interface BulkDeleteFailure {\r\n /** The id of the element that could not be deleted. */\r\n elementId: Id64String;\r\n /** Why the element could not be deleted. */\r\n reason: BulkDeleteFailureReason;\r\n}\r\n\r\n/**\r\n * Result of a bulk element delete operation.\r\n * @beta\r\n */\r\nexport interface BulkDeleteElementsResult {\r\n /** Overall status of the bulk delete operation. See [[BulkDeleteElementsStatus]]. */\r\n status: BulkDeleteElementsStatus;\r\n /** The raw SQLite result code from the underlying SQL DELETE. Only meaningful when `status === DeletionFailed`. */\r\n sqlDeleteStatus: DbResult;\r\n /**\r\n * One entry per element that blocks the deletion, with the reason. Only populated on `ConstraintViolation`.\r\n * Empty on `Success` and `DeletionFailed`.\r\n * Because the whole expanded delete set is validated, a reported element may be a child or sub-model member\r\n * that was not in the requested ids; its requested ancestor is not listed separately.\r\n */\r\n failures: BulkDeleteFailure[];\r\n /**\r\n * The set of element ids that could not be deleted.\r\n * - On `ConstraintViolation`: the unique element ids appearing in `failures`. May include cascaded descendants\r\n * that were not in the requested ids, so this is not guaranteed to be a subset of the input. Never empty.\r\n * Nothing was deleted, including requested ids that are not listed.\r\n * - On `DeletionFailed`: every requested id (the iModel may be partially modified; abandon the current txn).\r\n * - On `Success`: empty.\r\n * @deprecated in 5.15.0 - will not be removed until after 2027-11-05. Use `failures` for a more detailed failure report.\r\n */\r\n failedIds: Id64Set;\r\n}\r\n\r\n/**\r\n * Status of a bulk element delete operation, mirroring the C++ `BulkDeleteStatus` enum.\r\n * @beta\r\n */\r\nexport enum BulkDeleteElementsStatus {\r\n /** All supplied elements were deleted successfully. */\r\n Success = 0,\r\n /** Nothing was deleted because some elements in the (expanded) delete set are still referenced from outside the set; see `failures` for the violators. */\r\n ConstraintViolation = 1,\r\n /** An internal error occurred. The iModel may be partially modified; the caller must abandon the current txn. `failures` will be empty. */\r\n DeletionFailed = 2,\r\n}\r\n\r\n/**\r\n * Represents an explicit editing transaction for an iModel.\r\n *\r\n * An explicit EditTxn lets callers define a deliberate unit of work by choosing when editing\r\n * starts (`start`) and how it ends (`end()` / `end(\"save\")` or `end(\"abandon\")`). This avoids mixing\r\n * unrelated edits into one implicit unit of work and makes save/rollback boundaries explicit.\r\n *\r\n * Explicit EditTxn instances must be active before mutating operations are performed, regardless of enforcement level.\r\n * In other words, explicit transaction behavior is independent of `implicitWriteEnforcement`.\r\n *\r\n * @see [EditTxn transaction model and migration guidance]($docs/learning/backend/EditTxn.md)\r\n *\r\n * *During indirect changes (commit processing):* Use callback args (`indirectEditTxn`) in callbacks like\r\n * [[Relationship.onRootChangedArg]] and [[Relationship.onDeletedDependencyArg]] that fire during indirect processing.\r\n *\r\n * @beta\r\n */\r\nexport class EditTxn {\r\n /** Controls how writes through the implicit transaction are handled.\r\n *\r\n * This does not relax activation requirements for explicit transactions: explicit EditTxn writes\r\n * must always come from the active EditTxn.\r\n *\r\n * - `allow`: allow implicit writes for backwards compatibility, even while an explicit EditTxn is active.\r\n * - `log`: allow implicit writes but log `implicit-txn-write-disallowed` errors.\r\n * - `throw`: reject implicit writes with `implicit-txn-write-disallowed`.\r\n *\r\n * This is initialized from [[IModelHostOptions.implicitWriteEnforcement]] during [[IModelHost.startup]].\r\n *\r\n * Defaults to `allow` for backwards compatibility.\r\n * @beta\r\n */\r\n public static implicitWriteEnforcement: ImplicitWriteEnforcement = \"allow\";\r\n\r\n /** The iModel this EditTxn may modify. */\r\n public readonly iModel: IModelDb;\r\n\r\n /** Default description passed to [[saveChanges]] when saving this transaction. */\r\n public description: string;\r\n\r\n /** True if this transaction currently owns the iModel write surface. */\r\n public get isActive(): boolean {\r\n return this.iModel[_activeTxn] === this;\r\n }\r\n\r\n public constructor(iModel: IModelDb, description: string) {\r\n this.iModel = iModel;\r\n this.description = description;\r\n }\r\n\r\n public verifyWriteable(): void {\r\n this.iModel[_verifyTxnWrite]();\r\n // Explicit transactions must always be active before writing.\r\n if (!this.isActive)\r\n EditTxnError.throwError(\"not-active\", \"EditTxn is not active\", this.iModel.key);\r\n }\r\n\r\n /** Start this EditTxn, making it the active transaction for the iModel.\r\n * @throws EditTxnError if this EditTxn is already active, another EditTxn is already active, or if unsaved changes are present.\r\n * @throws IModelError if the geographic coordinate system is being restored.\r\n */\r\n public start(): void {\r\n this.iModel[_verifyTxnWrite]();\r\n if (this.isActive)\r\n EditTxnError.throwError(\"already-active\", \"This EditTxn is already active\", this.iModel.key);\r\n\r\n const activeTxn = this.iModel[_activeTxn];\r\n if (undefined !== activeTxn)\r\n EditTxnError.throwError(\"already-active\", \"Cannot start EditTxn while another EditTxn is active\", this.iModel.key, activeTxn.description);\r\n\r\n if (this.iModel[_nativeDb].hasUnsavedChanges())\r\n EditTxnError.throwError(\"unsaved-changes\", \"Cannot start a new EditTxn with unsaved changes\", this.iModel.key);\r\n\r\n this.iModel[_activeTxn] = this;\r\n }\r\n\r\n /** End this EditTxn, either by saving or abandoning the changes.\r\n * @param mode Whether to \"save\" or \"abandon\" the changes. Defaults to \"save\".\r\n * @param args Save changes arguments when saving.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if saving changes fails.\r\n * @throws Re-throws any error propagated by a geographic coordinate system restoration listener after completing abandonment.\r\n */\r\n public end(): void;\r\n public end(mode: \"save\" | \"abandon\", args?: string | SaveChangesArgs): void;\r\n public end(mode: \"save\" | \"abandon\" = \"save\", args?: string | SaveChangesArgs): void {\r\n if (!this.isActive)\r\n EditTxnError.throwError(\"not-active\", \"EditTxn is not active\", this.iModel.key);\r\n\r\n if (mode === \"save\") {\r\n this.saveChanges(args);\r\n } else {\r\n this.abandonDatabaseChanges();\r\n }\r\n this.iModel[_activeTxn] = undefined;\r\n if (mode === \"abandon\")\r\n this.iModel[_refreshGeographicCoordinateSystem]();\r\n }\r\n\r\n /** Invoked when the owning iModel is closing.\r\n * The base implementation commits unsaved changes. Subclasses may override to customize how\r\n * their changes are handled before the iModel closes.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if saving on close fails.\r\n */\r\n public onClose(): void {\r\n if (!this.iModel.isReadonly && this.iModel[_nativeDb].hasUnsavedChanges())\r\n this.saveChanges();\r\n }\r\n\r\n /** Abandon database changes while keeping this EditTxn active.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public abandonChanges(): void {\r\n this.abandonDatabaseChanges();\r\n this.iModel[_refreshGeographicCoordinateSystem]();\r\n }\r\n\r\n private abandonDatabaseChanges(): void {\r\n this.verifyWriteable();\r\n this.iModel.clearCaches({ instanceCachesOnly: true });\r\n this.iModel[_nativeDb].abandonChanges();\r\n }\r\n\r\n /** Save changes with additional arguments.\r\n * @param args Save changes arguments.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the iModel is readonly, if indirect changes are active, or if the native save fails.\r\n */\r\n public saveChanges(args?: string | SaveChangesArgs): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n if (iModel.openMode === OpenMode.Readonly)\r\n throw new IModelError(IModelStatus.ReadOnly, \"IModelDb was opened read-only\");\r\n\r\n if (iModel.isBriefcaseDb() && iModel.txns.isIndirectChanges)\r\n throw new IModelError(IModelStatus.BadRequest, \"Cannot save changes while in an indirect change scope\");\r\n\r\n args ??= this.description;\r\n const saveArgs = typeof args === \"string\" ? { description: args } : args;\r\n const stat = iModel[_nativeDb].saveChanges(JSON.stringify(saveArgs));\r\n if (DbResult.BE_SQLITE_ERROR_PropagateChangesFailed === stat)\r\n throw new IModelError(stat, \"Could not save changes due to propagation failure.\");\r\n\r\n if (DbResult.BE_SQLITE_OK !== stat)\r\n throw new IModelError(stat, `Could not save changes (${saveArgs.description})`);\r\n }\r\n\r\n /** Insert a new element into the iModel.\r\n * @param elProps The properties of the new element.\r\n * @returns The newly inserted element's Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if insertion fails.\r\n */\r\n public insertElement(elProps: ElementProps, options?: InsertElementOptions): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n options ??= {};\r\n this.iModel.elements[_cache].delete({\r\n id: elProps.id,\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n return elProps.id = this.iModel[_nativeDb].insertElement(elProps, options);\r\n } catch (err: any) {\r\n err.message = `Error inserting element [${err.message}]`;\r\n err.metadata = { elProps };\r\n throw err;\r\n }\r\n }\r\n\r\n /** Update an existing element in the iModel.\r\n * @param elProps The properties to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if update fails.\r\n */\r\n public updateElement<T extends ElementProps>(elProps: Partial<T>): void {\r\n this.verifyWriteable();\r\n try {\r\n if (elProps.id) {\r\n this.iModel.elements[_instanceKeyCache].deleteById(elProps.id);\r\n } else {\r\n this.iModel.elements[_instanceKeyCache].delete({\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n }\r\n this.iModel.elements[_cache].delete({\r\n id: elProps.id,\r\n federationGuid: elProps.federationGuid,\r\n code: elProps.code,\r\n });\r\n this.iModel[_nativeDb].updateElement(elProps);\r\n } catch (err: any) {\r\n err.message = `Error updating element [${err.message}], id: ${elProps.id}`;\r\n err.metadata = { elProps };\r\n throw err;\r\n }\r\n }\r\n\r\n /** Delete elements from the iModel.\r\n * @param ids The Ids of the elements to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if deletion fails.\r\n */\r\n public deleteElement(ids: Id64Arg): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n Id64.toIdSet(ids).forEach((id) => {\r\n try {\r\n this.iModel.elements[_cache].delete({ id });\r\n this.iModel.elements[_instanceKeyCache].deleteById(id);\r\n iModel[_nativeDb].deleteElement(id);\r\n } catch (err: any) {\r\n err.message = `Error deleting element [${err.message}], id: ${id}`;\r\n err.metadata = { elementId: id };\r\n throw err;\r\n }\r\n });\r\n }\r\n\r\n /** Change the parent of an element within its model.\r\n *\r\n * The new parent must be in the same model as the element. Cross-model reparenting is not allowed;\r\n * use [[changeElementModel]] only to move root elements between models.\r\n * Only the target element is reparented — its children and their model membership are unaffected.\r\n *\r\n * **Blocked cases** (will throw):\r\n * - The new parent is in a different model than the element.\r\n * - Element has a `ParentElement`-scoped code (code uniqueness is tied to the parent; use delete+insert instead).\r\n *\r\n * **Allowed cases**:\r\n * - Element has a `Repository`-scoped code (unique across entire iModel — unaffected by the parent change).\r\n * - Element has a `RelatedElement`-scoped code (scope element is independent of the parent).\r\n * - Element has a `Model`-scoped code (the model does not change, so the code remains valid).\r\n * - Element has no meaningful code (empty code).\r\n *\r\n * Channel verification is performed on the element's model.\r\n * Lock enforcement: requires an exclusive lock on the element, and a shared lock on the new parent.\r\n * @param props The reparent parameters: element id and new parent id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if the operation fails.\r\n * @beta\r\n */\r\n public changeElementParent(props: ChangeElementParentProps): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n\r\n // Lock enforcement: exclusive lock on the element being reparented, shared lock on the new parent.\r\n iModel.locks.checkExclusiveLock(props.id, \"element\", \"changeParent\");\r\n iModel.locks.checkSharedLock(props.parentId, \"parent\", \"changeParent\");\r\n\r\n // The new parent must be in the same model as the element. Cross-model reparenting is not\r\n // allowed here; changeElementModel only moves root elements between models. Check this up\r\n // front so consumers get a clear error instead of the addon's lower-level \"wrong model\" status.\r\n const sourceModelId = iModel.elements.getElementProps({ id: props.id }).model;\r\n const parentModelId = iModel.elements.getElementProps({ id: props.parentId }).model;\r\n if (sourceModelId !== parentModelId)\r\n ElementError.throwError(\"invalid-arguments\", `cannot reparent element '${props.id}' to a parent in a different model ('${parentModelId}' != '${sourceModelId}'); changeElementModel only moves root elements between models`);\r\n\r\n // Channel verification on the element's model.\r\n iModel.channels[_verifyChannel](sourceModelId);\r\n\r\n // Invalidate caches for the element being reparented.\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n\r\n try {\r\n iModel[_nativeDb].changeElementParent({ id: props.id, parentId: props.parentId });\r\n } catch (err: any) {\r\n err.message = `Error changing element parent [${err.message}], id: ${props.id}, parentId: ${props.parentId}`;\r\n err.metadata = { props };\r\n throw err;\r\n }\r\n\r\n // The model is unchanged and descendants are not moved, so only the reparented element's cache is stale.\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n }\r\n\r\n /** Change the model of a root element, making it a root element in the new model.\r\n *\r\n * The element must not have a parent.\r\n * The element's entire subtree moves with it: BIS requires a parent and all of its children to reside\r\n * in the same model, so every descendant of the element is relocated into the target model as well.\r\n * The parent-child hierarchy is preserved. The whole subtree is validated before anything is moved, so\r\n * a rejected change leaves the iModel untouched.\r\n *\r\n * **Blocked cases** (will throw):\r\n * - Element has a parent (only root elements can be moved between models).\r\n * - Any element in the subtree has a `Model`-scoped code (code uniqueness is tied to the source model; use delete+insert instead).\r\n * - The moved (root) element has a `ParentElement`-scoped code (use delete+insert instead). A descendant's `ParentElement`-scoped code is allowed, because its parent moves with it.\r\n *\r\n * **Allowed cases** (for any element in the subtree):\r\n * - A `Repository`-scoped code (unique across entire iModel — unaffected by the model change).\r\n * - A `RelatedElement`-scoped code (scope element is independent of the model).\r\n * - No meaningful code (empty code).\r\n *\r\n * The source and target models must be of the same class (classFullName must match exactly).\r\n * Channel verification is performed on both the source and target models.\r\n * Lock enforcement: requires an exclusive lock on every element in the moved subtree, and a shared lock on the target model.\r\n * @param props The model change parameters: element id and target model id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws [[ITwinError]] if the operation fails.\r\n * @beta\r\n */\r\n public changeElementModel(props: ChangeElementModelProps): void {\r\n this.verifyWriteable();\r\n const iModel = this.iModel;\r\n\r\n // Resolve the source model\r\n const sourceModelId = iModel.elements.getElementProps({ id: props.id }).model;\r\n\r\n // Channel verification on the source model\r\n iModel.channels[_verifyChannel](sourceModelId);\r\n\r\n // Model type check: source and target models must be the same class\r\n const sourceModel = iModel.models.getModel(sourceModelId);\r\n const targetModel = iModel.models.getModel(props.modelId);\r\n if (sourceModel.classFullName !== targetModel.classFullName)\r\n ElementError.throwError(\"model-type-mismatch\", `cannot move element from model of type '${sourceModel.classFullName}' to model of type '${targetModel.classFullName}'`);\r\n\r\n // Shared lock on target model\r\n iModel.locks.checkSharedLock(props.modelId, \"model\", \"changeModel\");\r\n\r\n // Lock enforcement: every element in the subtree is updated by the native bulk move.\r\n const subtreeIds = this.collectSubtreeIds(props.id);\r\n for (const id of subtreeIds)\r\n iModel.locks.checkExclusiveLock(id, \"element\", \"changeModel\");\r\n\r\n // Channel verification on the target model\r\n iModel.channels[_verifyChannel](props.modelId);\r\n\r\n // Invalidate caches\r\n iModel.elements[_cache].delete({ id: props.id });\r\n iModel.elements[_instanceKeyCache].deleteById(props.id);\r\n\r\n try {\r\n iModel[_nativeDb].changeElementModel({ id: props.id, modelId: props.modelId });\r\n } catch (err: any) {\r\n err.message = `Error changing element model [${err.message}], id: ${props.id}, modelId: ${props.modelId}`;\r\n err.metadata = { props };\r\n throw err;\r\n }\r\n\r\n // The move relocates the element's entire subtree into the target model (BIS requires a parent and\r\n // its children to reside in the same model). Every descendant's cached props therefore hold a stale\r\n // `model`, so invalidate the whole subtree rather than just the target element.\r\n for (const id of subtreeIds) {\r\n iModel.elements[_cache].delete({ id });\r\n iModel.elements[_instanceKeyCache].deleteById(id);\r\n }\r\n\r\n // Moving the subtree changes the membership - and therefore the geometry-derived state such as\r\n // GeometricModel.geometryGuid - of both the source and target models. Element insert/update/delete\r\n // invalidate models[_cache] via Element.onInserted/onUpdated/onDeleted for the same reason, but the\r\n // native changeElementModel does not fire those element callbacks, so invalidate both affected models\r\n // here to keep the model cache contract local to this wrapper.\r\n iModel.models[_cache].delete(sourceModelId);\r\n iModel.models[_cache].delete(props.modelId);\r\n }\r\n\r\n /** Collect an element together with all of its descendants by walking the `ElementOwnsChildElements`\r\n * hierarchy depth-first. Used to invalidate the cached props of every element affected by a subtree move.\r\n */\r\n private collectSubtreeIds(rootId: Id64String): Id64String[] {\r\n const ids: Id64String[] = [];\r\n const stack: Id64String[] = [rootId];\r\n for (let id = stack.pop(); undefined !== id; id = stack.pop()) {\r\n ids.push(id);\r\n for (const childId of this.iModel.elements.queryChildren(id))\r\n stack.push(childId);\r\n }\r\n return ids;\r\n }\r\n\r\n /**\r\n * Delete multiple elements from the iModel in a single bulk operation.\r\n *\r\n * Child elements and sub-model contents of the requested elements are deleted along with them.\r\n *\r\n * The operation is all-or-nothing:\r\n * - On `Success`, all elements (and their children / sub-model contents) were deleted.\r\n * - On `ConstraintViolation`, nothing was deleted and [[BulkDeleteElementsResult.failures]] lists every element in the\r\n * expanded delete set that is still referenced from outside the set, and why. Fix or include those referencing elements and retry.\r\n * - On `DeletionFailed` (an unexpected SQLite error) the iModel may be partially modified and the caller must abandon the current txn.\r\n *\r\n * @param ids The ids of the elements to delete. All ids must be well-formed and valid [[Id64String]]s.\r\n * @param _deleteOptions Deprecated and ignored; kept for backward compatibility of the signature.\r\n * @returns A result object describing the outcome of the operation and the elements that block it (if any).\r\n * @throws [[ITwinError]] if any of the supplied ids are not well-formed/valid [[Id64String]]s.\r\n * @beta\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-deprecated\r\n public deleteElements(ids: Id64Array, _deleteOptions?: BulkDeleteElementsArgs): BulkDeleteElementsResult {\r\n this.verifyWriteable();\r\n const invalidIds: Id64Set = new Set<Id64String>();\r\n for (const id of ids) {\r\n if (!Id64.isValidId64(id))\r\n invalidIds.add(id);\r\n }\r\n\r\n if (invalidIds.size > 0)\r\n ITwinError.throwError({ message: `Invalid element ids: ${Array.from(invalidIds).join(\", \")}`, iTwinErrorId: { scope: \"imodel\", key: \"invalid-arguments\" } });\r\n\r\n const nativeResult = this.iModel[_nativeDb].deleteElements(ids);\r\n\r\n // When deletion fails with `DeletionFailed`, all requested ids are returned to maintain backward compatibilty.\r\n // Once `failedIds` is deprecated, we will change this to throw instead as this is a SQLite failure.\r\n const failedIds = nativeResult.status === BulkDeleteElementsStatus.DeletionFailed\r\n ? new Set<Id64String>(ids)\r\n : new Set<Id64String>(nativeResult.failures.map((failure: BulkDeleteFailure) => failure.elementId));\r\n\r\n const result: BulkDeleteElementsResult = {\r\n status: nativeResult.status,\r\n sqlDeleteStatus: nativeResult.sqlDeleteStatus,\r\n failures: nativeResult.failures,\r\n // `failedIds` is deprecated. `failures` provides a more comprehensive error report.\r\n // We still need to return the deprecated `failedIds` to maintain backward compatibility.\r\n failedIds,\r\n };\r\n\r\n // Nothing was deleted on ConstraintViolation; on DeletionFailed the caller must abandon the txn, which restores the cached state.\r\n if (result.status !== BulkDeleteElementsStatus.Success)\r\n return result;\r\n\r\n // Native deletion also nulls logical navigation properties on surviving elements that referenced the deleted ones,\r\n // so evicting only the requested ids would leave stale cached referrers. Clear all instance caches.\r\n this.iModel.clearCaches({ instanceCachesOnly: true });\r\n\r\n return result;\r\n }\r\n\r\n /** Insert a new aspect into the iModel.\r\n * @param aspectProps The properties of the new aspect.\r\n * @returns The newly inserted aspect Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if insertion fails.\r\n */\r\n public insertAspect(aspectProps: ElementAspectProps): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n return this.iModel[_nativeDb].insertElementAspect(aspectProps);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error inserting ElementAspect [${err.message}], class: ${aspectProps.classFullName}`, aspectProps);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update an existing aspect in the iModel.\r\n * @param aspectProps The properties of the aspect to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if update fails.\r\n */\r\n public updateAspect(aspectProps: ElementAspectProps): void {\r\n this.verifyWriteable();\r\n try {\r\n this.iModel[_nativeDb].updateElementAspect(aspectProps);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error updating ElementAspect [${err.message}], id: ${aspectProps.id}`, aspectProps);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Delete one or more aspects from the iModel.\r\n * @param aspectInstanceIds The Ids of the aspects to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if deletion fails.\r\n */\r\n public deleteAspect(aspectInstanceIds: Id64Arg): void {\r\n this.verifyWriteable();\r\n Id64.toIdSet(aspectInstanceIds).forEach((aspectInstanceId) => {\r\n try {\r\n this.iModel[_nativeDb].deleteElementAspect(aspectInstanceId);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error deleting ElementAspect [${err.message}], id: ${aspectInstanceId}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n });\r\n }\r\n\r\n /** Delete definition elements from the iModel when they are not referenced.\r\n * @param definitionElementIds The Ids of the definition elements to attempt to delete.\r\n * @returns The set of definition elements that were still in use and therefore not deleted.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if usage queries fail.\r\n */\r\n public deleteDefinitionElements(definitionElementIds: Id64Array): Id64Set {\r\n this.verifyWriteable();\r\n const usageInfo = this.iModel[_nativeDb].queryDefinitionElementUsage(definitionElementIds);\r\n if (!usageInfo)\r\n throw new IModelError(IModelStatus.BadRequest, \"Error querying for DefinitionElement usage\");\r\n\r\n const usedIdSet = usageInfo.usedIds ? Id64.toIdSet(usageInfo.usedIds) : new Set<Id64String>();\r\n const deleteIfUnused = (ids: Id64Array | undefined, used: Id64Set): void => {\r\n ids?.forEach((id) => {\r\n if (!used.has(id))\r\n this.deleteElement(id);\r\n });\r\n };\r\n\r\n try {\r\n this.iModel[_nativeDb].beginPurgeOperation();\r\n deleteIfUnused(usageInfo.spatialCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.drawingCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.viewDefinitionIds, usedIdSet);\r\n deleteIfUnused(usageInfo.geometryPartIds, usedIdSet);\r\n deleteIfUnused(usageInfo.lineStyleIds, usedIdSet);\r\n deleteIfUnused(usageInfo.renderMaterialIds, usedIdSet);\r\n deleteIfUnused(usageInfo.subCategoryIds, usedIdSet);\r\n deleteIfUnused(usageInfo.textureIds, usedIdSet);\r\n deleteIfUnused(usageInfo.displayStyleIds, usedIdSet);\r\n deleteIfUnused(usageInfo.categorySelectorIds, usedIdSet);\r\n deleteIfUnused(usageInfo.modelSelectorIds, usedIdSet);\r\n if (usageInfo.otherDefinitionElementIds)\r\n this.deleteElement(usageInfo.otherDefinitionElementIds);\r\n } finally {\r\n this.iModel[_nativeDb].endPurgeOperation();\r\n }\r\n\r\n if (usageInfo.viewDefinitionIds) {\r\n // Recheck view-related definitions after deleting view definitions that may have been their last reference.\r\n let viewRelatedIds: Id64Array = [];\r\n if (usageInfo.displayStyleIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.displayStyleIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (usageInfo.categorySelectorIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.categorySelectorIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (usageInfo.modelSelectorIds)\r\n viewRelatedIds = viewRelatedIds.concat(usageInfo.modelSelectorIds.filter((id) => usedIdSet.has(id)));\r\n\r\n if (viewRelatedIds.length > 0) {\r\n const viewRelatedUsageInfo = this.iModel[_nativeDb].queryDefinitionElementUsage(viewRelatedIds);\r\n if (viewRelatedUsageInfo) {\r\n const usedViewRelatedIdSet: Id64Set = viewRelatedUsageInfo.usedIds ? Id64.toIdSet(viewRelatedUsageInfo.usedIds) : new Set<Id64String>();\r\n try {\r\n this.iModel[_nativeDb].beginPurgeOperation();\r\n deleteIfUnused(viewRelatedUsageInfo.displayStyleIds, usedViewRelatedIdSet);\r\n deleteIfUnused(viewRelatedUsageInfo.categorySelectorIds, usedViewRelatedIdSet);\r\n deleteIfUnused(viewRelatedUsageInfo.modelSelectorIds, usedViewRelatedIdSet);\r\n } finally {\r\n this.iModel[_nativeDb].endPurgeOperation();\r\n }\r\n\r\n viewRelatedIds.forEach((id) => {\r\n if (!usedViewRelatedIdSet.has(id))\r\n usedIdSet.delete(id);\r\n });\r\n }\r\n }\r\n }\r\n\r\n return usedIdSet;\r\n }\r\n\r\n /** Insert a new model into the iModel.\r\n * @param props The data for the new model.\r\n * @returns The newly inserted model's Id.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if insertion fails.\r\n */\r\n public insertModel(props: ModelProps): Id64String {\r\n this.verifyWriteable();\r\n try {\r\n return props.id = this.iModel[_nativeDb].insertModel(props);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error inserting model [${err.message}], class=${props.classFullName}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update an existing model in the iModel.\r\n * @param props the properties of the model to change\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if update fails.\r\n */\r\n public updateModel(props: UpdateModelOptions): void {\r\n this.verifyWriteable();\r\n try {\r\n if (props.id)\r\n this.iModel.models[_cache].delete(props.id);\r\n\r\n this.iModel[_nativeDb].updateModel(props);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error updating model [${err.message}], id: ${props.id}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n }\r\n\r\n /** Update the geometry guid of a model.\r\n * @param modelId The Id of the model to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the update fails.\r\n */\r\n public updateGeometryGuid(modelId: Id64String): void {\r\n this.verifyWriteable();\r\n this.iModel.models[_cache].delete(modelId);\r\n const error = this.iModel[_nativeDb].updateModelGeometryGuid(modelId);\r\n if (error !== IModelStatus.Success)\r\n throw new IModelError(error, `Error updating geometry guid for model ${modelId}`);\r\n }\r\n\r\n /** Delete models from the iModel.\r\n * @param ids The Ids of the models to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if deletion fails.\r\n */\r\n public deleteModel(ids: Id64Arg): void {\r\n this.verifyWriteable();\r\n Id64.toIdSet(ids).forEach((id) => {\r\n try {\r\n this.iModel.models[_cache].delete(id);\r\n this.iModel.models[_instanceKeyCache].deleteById(id);\r\n this.iModel[_nativeDb].deleteModel(id);\r\n } catch (err: any) {\r\n const error = new IModelError(err.errorNumber, `Error deleting model [${err.message}], id: ${id}`);\r\n error.cause = err;\r\n throw error;\r\n }\r\n });\r\n }\r\n\r\n /** Insert a new relationship into the iModel.\r\n * @param props The properties of the new relationship.\r\n * @returns The Id of the newly inserted relationship.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if the class is invalid for link-table insertion.\r\n */\r\n public insertRelationship(props: RelationshipProps): Id64String {\r\n this.verifyWriteable();\r\n if (!this.iModel[_nativeDb].isLinkTableRelationship(props.classFullName.replace(\".\", \":\")))\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Class '${props.classFullName}' must be a relationship class and it should be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.`);\r\n\r\n return props.id = this.iModel[_nativeDb].insertLinkTableRelationship(props);\r\n }\r\n\r\n /** Update an existing relationship in the iModel.\r\n * @param props the properties of the relationship to update.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateRelationship(props: RelationshipProps): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].updateLinkTableRelationship(props);\r\n }\r\n\r\n /** Delete a relationship from the iModel.\r\n * @param props The properties of the relationship to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteRelationship(props: RelationshipProps): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].deleteLinkTableRelationship(props);\r\n }\r\n\r\n /** Delete multiple relationships from the iModel.\r\n * @param props The properties of the relationships to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteRelationships(props: ReadonlyArray<RelationshipProps>): void {\r\n this.verifyWriteable();\r\n this.iModel[_nativeDb].deleteLinkTableRelationships(props);\r\n }\r\n\r\n\r\n /** Save a file property to the iModel.\r\n * @param prop The file property to save.\r\n * @param strValue String value.\r\n * @param blobVal Blob value.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public saveFileProperty(prop: FilePropertyProps, strValue: string | undefined, blobVal?: Uint8Array): void {\r\n this.verifyWriteable();\r\n const imodel = this.iModel;\r\n if (imodel.isBriefcaseDb()) {\r\n if (imodel.txns.isIndirectChanges) {\r\n throw new IModelError(IModelStatus.BadRequest, \"Cannot save file property while in an indirect change scope\");\r\n }\r\n }\r\n imodel[_nativeDb].saveFileProperty(prop, strValue, blobVal);\r\n }\r\n\r\n /** Delete a file property from the iModel.\r\n * @param prop The file property to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public deleteFileProperty(prop: FilePropertyProps): void {\r\n this.saveFileProperty(prop, undefined, undefined);\r\n }\r\n\r\n /** Update the project extents of the iModel.\r\n * @param newExtents The new project extents.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @throws IModelError if extents are invalid.\r\n */\r\n public updateProjectExtents(newExtents: Range3dProps): void {\r\n this.verifyWriteable();\r\n const extents = Range3d.fromJSON(newExtents);\r\n if (extents.isNull)\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, \"Invalid project extents\");\r\n\r\n this.iModel.projectExtents = extents;\r\n this.updateIModelProps();\r\n }\r\n\r\n /** Update the ECEF location of the iModel.\r\n * @param ecef The new ECEF location.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateEcefLocation(ecef: EcefLocationProps): void {\r\n this.verifyWriteable();\r\n this.iModel.setEcefLocation(new EcefLocation(ecef));\r\n this.updateIModelProps();\r\n }\r\n\r\n /** Update the iModel props in the database from the current in-memory state.\r\n * An unchanged geographic coordinate system is not replaced or re-resolved from its dictionary identifiers.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n */\r\n public updateIModelProps(): void {\r\n this.verifyWriteable();\r\n this.iModel[_updateIModelProps]();\r\n }\r\n\r\n private static readonly _settingPropNamespace = \"settings\";\r\n private static readonly _viewStoreProperty: FilePropertyProps = { namespace: \"itwinjs\", name: \"DefaultViewStore\" };\r\n\r\n /** Save a `SettingDictionary` in this iModel.\r\n * @param name The name for the SettingDictionary. If a dictionary by that name already exists, its value is replaced.\r\n * @param dict The SettingDictionary object to stringify and save.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public saveSettingDictionary(name: string, dict: SettingsContainer): void {\r\n this.verifyWriteable();\r\n this.iModel.withSqliteStatement(\"REPLACE INTO be_Prop(id,SubId,TxnMode,Namespace,Name,strData) VALUES(0,0,0,?,?,?)\", (stmt) => {\r\n stmt.bindString(1, EditTxn._settingPropNamespace);\r\n stmt.bindString(2, name);\r\n stmt.bindString(3, JSON.stringify(dict));\r\n stmt.stepForWrite();\r\n });\r\n this.saveChanges(\"add settings\");\r\n }\r\n\r\n /** Delete a SettingDictionary from this iModel.\r\n * @param name The name of the dictionary to delete.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public deleteSettingDictionary(name: string): void {\r\n this.verifyWriteable();\r\n this.iModel.withSqliteStatement(\"DELETE FROM be_Prop WHERE Namespace=? AND Name=?\", (stmt) => {\r\n stmt.bindString(1, EditTxn._settingPropNamespace);\r\n stmt.bindString(2, name);\r\n stmt.stepForWrite();\r\n });\r\n this.saveChanges(\"delete settings\");\r\n }\r\n\r\n /** Save a default ViewStore container reference in this iModel.\r\n * @param arg The cloud container properties for the ViewStore.\r\n * @throws EditTxnError if this EditTxn is not active.\r\n * @beta\r\n */\r\n public saveDefaultViewStore(arg: CloudSqlite.ContainerProps): void {\r\n this.verifyWriteable();\r\n const props = { baseUri: arg.baseUri, containerId: arg.containerId, storageType: arg.storageType }; // sanitize to only known properties\r\n this.saveFileProperty(EditTxn._viewStoreProperty, JSON.stringify(props));\r\n this.saveChanges(\"update default ViewStore\");\r\n }\r\n}\r\n\r\n/** Execute a callback within an explicit editing transaction. A new [[EditTxn]] is created, started,\r\n * and passed to `fn`. If `fn` returns normally (or its returned Promise resolves), the transaction\r\n * is committed. If `fn` throws (or its returned Promise rejects), the transaction is abandoned —\r\n * none of the changes made during the callback are saved — and the error is re-thrown.\r\n * If abandonment also throws, logging that secondary error is attempted without allowing a logging failure to replace the callback error.\r\n *\r\n * This is the recommended way to perform a scoped unit of work on an iModel. It ensures that\r\n * edits are committed atomically on success and rolled back on failure, without the caller needing\r\n * to manage `start` / `end` manually.\r\n *\r\n * @param iModel The iModel to edit.\r\n * @param fn A callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns The value returned by `fn`.\r\n * @throws EditTxnError if the transaction cannot be started (e.g. unsaved changes or another EditTxn is active).\r\n * @throws Re-throws any error thrown by `fn` after abandoning the transaction.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, fn: (txn: EditTxn) => T): T;\r\n/** Execute a callback within an explicit editing transaction, supplying commit arguments.\r\n * @param iModel The iModel to edit.\r\n * @param saveArgs Description or structured arguments passed to [[EditTxn.saveChanges]] on save.\r\n * @param fn A callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns The value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgs: string | SaveChangesArgs, fn: (txn: EditTxn) => T): T;\r\n/** Execute an async callback within an explicit editing transaction.\r\n * @param iModel The iModel to edit.\r\n * @param fn An async callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns A Promise that resolves to the value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, fn: (txn: EditTxn) => Promise<T>): Promise<T>;\r\n/** Execute an async callback within an explicit editing transaction, supplying commit arguments.\r\n * @param iModel The iModel to edit.\r\n * @param saveArgs Description or structured arguments passed to [[EditTxn.saveChanges]] on save.\r\n * @param fn An async callback that receives the active [[EditTxn]] and performs edits.\r\n * @returns A Promise that resolves to the value returned by `fn`.\r\n * @beta\r\n */\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgs: string | SaveChangesArgs, fn: (txn: EditTxn) => Promise<T>): Promise<T>;\r\nexport function withEditTxn<T>(iModel: IModelDb, saveArgsOrFn: string | SaveChangesArgs | ((txn: EditTxn) => T | Promise<T>), maybeFn?: (txn: EditTxn) => T | Promise<T>): T | Promise<T> {\r\n const saveArgs = \"function\" === typeof saveArgsOrFn ? undefined : saveArgsOrFn;\r\n const fn = \"function\" === typeof saveArgsOrFn ? saveArgsOrFn : maybeFn;\r\n\r\n if (undefined === fn)\r\n throw new Error(\"withEditTxn requires a callback\");\r\n\r\n const txn = new EditTxn(iModel, \"\");\r\n txn.start();\r\n\r\n const abandonOnError = (error: unknown): never => {\r\n try {\r\n if (txn.isActive)\r\n txn.end(\"abandon\");\r\n } catch (abandonError) {\r\n try {\r\n Logger.logError(BackendLoggerCategory.IModelDb, abandonError);\r\n } catch {\r\n throw error;\r\n }\r\n }\r\n throw error;\r\n };\r\n\r\n try {\r\n const result = fn(txn);\r\n if (result instanceof Promise) {\r\n return result.then((value) => {\r\n txn.end(\"save\", saveArgs);\r\n return value;\r\n }, abandonOnError);\r\n }\r\n\r\n txn.end(\"save\", saveArgs);\r\n return result;\r\n } catch (err) {\r\n return abandonOnError(err);\r\n }\r\n}\r\n"]}