@itwin/core-backend 5.12.0-dev.11 → 5.12.0-dev.12

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.
@@ -101,6 +101,40 @@ export declare class SQLiteDb {
101
101
  saveChanges(): void;
102
102
  /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the default transaction. */
103
103
  abandonChanges(): void;
104
+ /**
105
+ * Apply a changeset file - in the same on-disk format used for iModel changesets - to this SQLiteDb.
106
+ * Unlike `BriefcaseDb.pullChanges`, this does *not* validate the changeset header (e.g. parentId/changesetId)
107
+ * against the current state of the database - it simply applies the changes it contains. If applying the
108
+ * changeset encounters any conflict, or otherwise fails, this method throws (conflicts are never resolved
109
+ * automatically).
110
+ * @note this method only throws on failure - it does *not* commit or abandon any changes itself. If it
111
+ * throws, some (but not necessarily all) of the changeset's changes may have already been applied to the
112
+ * current transaction. It is the caller's responsibility to call [[saveChanges]] or [[abandonChanges]]
113
+ * as appropriate after catching an error from this method.
114
+ * @param changesetFile the local file name of the changeset to apply.
115
+ * @internal
116
+ */
117
+ applyChangeset(changesetFile: LocalFileName): void;
118
+ /**
119
+ * Begin capturing DDL and data changes made to this SQLiteDb, so they may later be saved via [[createChangeset]].
120
+ * Intended only to produce changeset files for testing [[applyChangeset]] - not for any other purpose.
121
+ * @internal
122
+ */
123
+ startChangeTracking(): void;
124
+ /**
125
+ * Execute a DDL statement (e.g. `CREATE TABLE`) so that, if change tracking is active (see [[startChangeTracking]]),
126
+ * the DDL is captured for inclusion in the changeset produced by [[createChangeset]]. DDL executed via [[executeSQL]]
127
+ * is *not* captured for change tracking purposes.
128
+ * @internal
129
+ */
130
+ executeDdl(ddl: string): void;
131
+ /**
132
+ * Write out the changes captured since [[startChangeTracking]] was called to a changeset file, in the same
133
+ * on-disk format used for iModel changesets.
134
+ * @param changesetFile the local file name to write the changeset to.
135
+ * @internal
136
+ */
137
+ createChangeset(changesetFile: LocalFileName): void;
104
138
  /**
105
139
  * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist
106
140
  * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteDb.d.ts","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":"AAIA;;GAEG;AAKH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAe,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5C,OAAO,EAAE,eAAe,EAAkB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAI/C;;;GAGG;AACH,qBAAa,QAAQ;IACnB,gBAAgB;IAChB,SAAgB,CAAC,SAAS,CAAC,0BAAwC;IACnE,OAAO,CAAC,qBAAqB,CAAyC;IAEtE,gBAAgB;WACF,YAAY,IAAI,QAAQ,CAAC,MAAM;IAI7C;;OAEG;IACI,OAAO,IAAI,IAAI;IAItB;;OAEG;IACI,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IACrC,YAAY;IACL,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,WAAW,CAAC,cAAc,EAAE,MAAM,CAAC,EAAE,QAAQ,CAAC,YAAY,GAAG,IAAI;IAK7G;;OAEG;IACI,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC,UAAU,GAAG,IAAI;IAC7E;;;OAGG;IACI,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC,UAAU,EAAE,SAAS,CAAC,EAAE,WAAW,CAAC,cAAc,GAAG,IAAI;IAKrH;;OAEG;IACI,OA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C;QACpB,sEAAsE;QACtE,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,oFAAoF;QACpF,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB;;QAEA;QACA,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC3B,2FAA2F;QAC3F,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB;IAED,kDAAkD;IAClD,UAAiB,UAAW,SAAQ,kBAAkB;QACpD,gEAAgE;QAChE,QAAQ,EAAE,QAAQ,CAAC;KACpB;IAED,uCAAuC;IACvC,UAAiB,QAAQ;QACvB,8DAA8D;QAC9D,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB;IAED,6CAA6C;IAC7C,KAAY,YAAY,GAAG,kBAAkB,GAAG,QAAQ,CAAC;IAEzD,0CAA0C;IAC1C,UAAiB,cAAc;QAC7B,uCAAuC;QACvC,MAAM,EAAE,MAAM,CAAC;QACf,wEAAwE;QACxE,QAAQ,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC,UAAU,CAAC;QAC1C,gBAAgB;QAChB,SAAS,CAAC,EAAE,WAAW,CAAC,cAAc,CAAC;KACxC;IAED,sCAAsC;IACtC,UAAiB,YAAa,SAAQ,QAAQ;QAC5C,6FAA6F;QAC7F,IAAI,CAAC,EAAE,aAAa,CAAC;KACtB;CACF"}
@@ -190,6 +190,48 @@ export class SQLiteDb {
190
190
  abandonChanges() {
191
191
  this[_nativeDb].abandonChanges();
192
192
  }
193
+ /**
194
+ * Apply a changeset file - in the same on-disk format used for iModel changesets - to this SQLiteDb.
195
+ * Unlike `BriefcaseDb.pullChanges`, this does *not* validate the changeset header (e.g. parentId/changesetId)
196
+ * against the current state of the database - it simply applies the changes it contains. If applying the
197
+ * changeset encounters any conflict, or otherwise fails, this method throws (conflicts are never resolved
198
+ * automatically).
199
+ * @note this method only throws on failure - it does *not* commit or abandon any changes itself. If it
200
+ * throws, some (but not necessarily all) of the changeset's changes may have already been applied to the
201
+ * current transaction. It is the caller's responsibility to call [[saveChanges]] or [[abandonChanges]]
202
+ * as appropriate after catching an error from this method.
203
+ * @param changesetFile the local file name of the changeset to apply.
204
+ * @internal
205
+ */
206
+ applyChangeset(changesetFile) {
207
+ this[_nativeDb].applyChangeset(changesetFile);
208
+ }
209
+ /**
210
+ * Begin capturing DDL and data changes made to this SQLiteDb, so they may later be saved via [[createChangeset]].
211
+ * Intended only to produce changeset files for testing [[applyChangeset]] - not for any other purpose.
212
+ * @internal
213
+ */
214
+ startChangeTracking() {
215
+ this[_nativeDb].startChangeTracking();
216
+ }
217
+ /**
218
+ * Execute a DDL statement (e.g. `CREATE TABLE`) so that, if change tracking is active (see [[startChangeTracking]]),
219
+ * the DDL is captured for inclusion in the changeset produced by [[createChangeset]]. DDL executed via [[executeSQL]]
220
+ * is *not* captured for change tracking purposes.
221
+ * @internal
222
+ */
223
+ executeDdl(ddl) {
224
+ this[_nativeDb].executeDdl(ddl);
225
+ }
226
+ /**
227
+ * Write out the changes captured since [[startChangeTracking]] was called to a changeset file, in the same
228
+ * on-disk format used for iModel changesets.
229
+ * @param changesetFile the local file name to write the changeset to.
230
+ * @internal
231
+ */
232
+ createChangeset(changesetFile) {
233
+ this[_nativeDb].createChangeset(changesetFile);
234
+ }
193
235
  /**
194
236
  * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist
195
237
  * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteDb.js","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,OAAO,E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uH;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,QAAQ,CAAC,SAAS,EAAE,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC;IAC9E,CAAC;;AAGH,cAAc;AACd,WAAiB,QAAQ;IAqEvB;;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,EAjIgB,QAAQ,KAAR,QAAQ,QAiIxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module SQLiteDb\n */\n\nimport * as fs from \"fs\";\nimport { dirname } from \"path\";\nimport * as semver from \"semver\";\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\nimport { DbResult, OpenMode } from \"@itwin/core-bentley\";\nimport { LocalFileName, SqliteError } from \"@itwin/core-common\";\nimport { CloudSqlite } from \"./CloudSqlite\";\nimport { IModelNative } from \"./internal/NativePlatform\";\nimport { IModelJsFs } from \"./IModelJsFs\";\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\nimport { _nativeDb } from \"./internal/Symbols\";\n\n// cspell:ignore savepoint julianday rowid\n\n/**\n * A \"generic\" SQLiteDb. This class may be used to access local files or databases in a cloud container.\n * @public\n */\nexport class SQLiteDb {\n /** @internal */\n public readonly [_nativeDb] = new IModelNative.platform.SQLiteDb();\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\n\n /** @internal */\n public static createBlobIO(): SQLiteDb.BlobIO {\n return new IModelNative.platform.BlobIO();\n }\n\n /** alias for closeDb.\n * @deprecated in 4.0 - might be removed in next major version. Use [[closeDb]]\n */\n public dispose(): void {\n this.closeDb();\n }\n\n /** Create a SQLiteDb\n * @param dbName The path to the SQLiteDb file to create.\n */\n public createDb(dbName: string): void;\n /** @beta */\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\n this[_nativeDb].createDb(dbName, container, params);\n }\n\n /** Open a SQLiteDb.\n * @param dbName The path to the SQLiteDb file to open\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\n /**\n * @param container optional CloudContainer holding database\n * @beta\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\n this[_nativeDb].openDb(dbName, openMode, container);\n }\n\n /** Close SQLiteDb.\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\n */\n public closeDb(saveChanges?: boolean): void {\n if (saveChanges && this.isOpen)\n this.saveChanges();\n this._sqliteStatementCache.clear();\n this[_nativeDb].closeDb();\n }\n\n /** Returns true if this SQLiteDb is open */\n public get isOpen(): boolean { return this[_nativeDb].isOpen(); }\n\n /** Returns true if this SQLiteDb is open readonly */\n public get isReadonly(): boolean { return this[_nativeDb].isReadonly(); }\n\n /** Create a new table in this database. */\n protected createTable(args: {\n /** The name of the table to create. */\n tableName: string;\n /** all of the columns in the table. */\n columns: string;\n /** any unique or foreign key constraints */\n constraints?: string;\n /** if true, add a \"lastMod\" timestamp column and triggers to automatically update it. */\n addTimestamp?: boolean;\n }) {\n const timestampCol = args.addTimestamp ? \",lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))\" : \"\";\n const constraints = args.constraints ? `,${args.constraints}` : \"\";\n this.executeSQL(`CREATE TABLE ${args.tableName}(${args.columns}${timestampCol}${constraints})`);\n if (args.addTimestamp)\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`);\n }\n\n /**\n * Get the last modified date for a row in a table of this database.\n * @note the table must have been created with `addTimestamp: true`\n */\n public readLastModTime(tableName: string, rowId: number): Date {\n return this.withSqliteStatement(`SELECT lastMod from ${tableName} WHERE rowid=?`, (stmt) => {\n stmt.bindInteger(1, rowId);\n return stmt.getValueDate(0);\n });\n }\n\n /**\n * Open a database, perform an operation, then close the database.\n *\n * Details:\n * - if database is open, throw an error\n * - open a database\n * - call a function with the database opened. If it is async, await its return.\n * - if function throws, abandon all changes, close database, and rethrow\n * - save all changes\n * - close the database\n * @return value from operation\n */\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\n if (this.isOpen)\n SqliteError.throwError(\"already-open\", \"database is already open\", args.dbName);\n\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\n try {\n const result = operation();\n result instanceof Promise ? result.then(save, abandon) : save();\n return result;\n } catch (e) {\n abandon();\n throw e;\n }\n }\n\n /** The cloud container backing this SQLite database, if any.\n * @beta\n */\n public get cloudContainer(): CloudSqlite.CloudContainer | undefined {\n return this[_nativeDb].cloudContainer;\n }\n\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). */\n public getLastInsertRowId(): number {\n return this[_nativeDb].getLastInsertRowId();\n }\n\n /**\n * Perform an operation on a database in a CloudContainer with the write lock held.\n *\n * Details:\n * - acquire the write lock on a CloudContainer\n * - call `withOpenDb` with openMode `ReadWrite`\n * - upload changes\n * - release the write lock\n * @param args arguments to lock the container and open the database\n * @param operation an operation performed on the database with the write lock held.\n * @return value from operation\n * @internal\n */\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => Promise<T>) {\n return CloudSqlite.withWriteLock(args, async () => this.withOpenDb({ ...args, openMode: args.openMode ?? OpenMode.ReadWrite }, operation));\n }\n\n /** vacuum this database\n * @see https://www.sqlite.org/lang_vacuum.html\n */\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\n this[_nativeDb].vacuum(args);\n }\n\n /** Commit the outermost transaction, writing changes to the file. Then, restart the default transaction. */\n public saveChanges(): void {\n this[_nativeDb].saveChanges();\n }\n\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the default transaction. */\n public abandonChanges(): void {\n this[_nativeDb].abandonChanges();\n }\n\n /**\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Prepare and execute a callback on a SQL statement. After the callback completes the statement is disposed.\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this.prepareSqliteStatement(sql);\n const release = () => stmt[Symbol.dispose]();\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\n */\n public withSavePoint(savePointName: string, operation: () => void) {\n if (this.isReadonly)\n SqliteError.throwError(\"readonly\", \"database is readonly\", this[_nativeDb].getFilePath());\n\n this.executeSQL(`SAVEPOINT ${savePointName}`);\n try {\n operation();\n this.executeSQL(`RELEASE ${savePointName}`);\n } catch (e) {\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\n throw e;\n }\n }\n\n /** Prepare an SQL statement.\n * @param sql The SQLite SQL statement to prepare\n * @param logErrors Determine if errors are logged or not\n * @internal\n */\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\n const stmt = new SqliteStatement(sql);\n stmt.prepare(this[_nativeDb], logErrors);\n return stmt;\n }\n\n /** execute an SQL statement */\n public executeSQL(sql: string): DbResult {\n using stmt = this.prepareSqliteStatement(sql);\n return stmt.step();\n }\n}\n\n/**\n * Abstract base class for a SQLite database that has [[SQLiteDb.RequiredVersionRanges]] stored in it.\n * This class provides version checking when the database is opened, to guarantee that a valid version of software is\n * always used for access.\n *\n * Notes:\n * - This class may be used either to access a local file, or one stored in a cloud container.\n * - Subclasses must provide a `myVersion` member indicating the version of its software, and implement the `createDDL` member to create its\n * tables.\n * @beta\n */\nexport abstract class VersionedSqliteDb extends SQLiteDb {\n protected static _versionProps = { namespace: \"SQLiteDb\", name: \"versions\" } as const;\n\n /** The current semver \"persistence version\" of this class.\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.\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\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\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\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\n * supported by it, the user will be informed that they need to upgrade their software.\n * @note this identifier is independent of versions in `package.json` files.\n */\n public abstract myVersion: string;\n\n /**\n * Change the \"versions required to open this database\" property stored in this database. After this call,\n * versions of software that don't meet the supplied ranges will fail.\n * @param versions the new versions required for reading and writing this database.\n * @note the database must be opened for write access.\n */\n public setRequiredVersions(versions: SQLiteDb.RequiredVersionRanges) {\n // NOTE: It might look tempting to just stringify the supplied `versions` object, but we only include required members - there may be others.\n this[_nativeDb].saveFileProperty(VersionedSqliteDb._versionProps, JSON.stringify({ readVersion: versions.readVersion, writeVersion: versions.writeVersion }));\n }\n\n /** Get the required version ranges necessary to open this VersionedSqliteDb. */\n public getRequiredVersions() {\n const checkIsString = (value: any) => {\n if (typeof value !== \"string\")\n SqliteError.throwError(\"invalid-versions-property\", `CloudDb has invalid \"versions\" property`, this[_nativeDb].getFilePath());\n return value;\n };\n const versionJson = checkIsString(this[_nativeDb].queryFileProperty(VersionedSqliteDb._versionProps, true));\n const versionRanges = JSON.parse(versionJson) as SQLiteDb.RequiredVersionRanges;\n checkIsString(versionRanges.readVersion);\n checkIsString(versionRanges.writeVersion);\n return versionRanges;\n }\n\n /**\n * Implement this method to create all tables for this subclass of `VersionedSqliteDb` when a new database file is created. Called from [[createNewDb]].\n */\n protected abstract createDDL(args: any): void;\n\n /**\n * Create a new database file for the subclass of VersionedSqliteDb.\n * @note The required versions are saved as [[myVersion]] or newer for both read and write.\n */\n public static createNewDb(fileName: LocalFileName, setupArgs?: any) {\n const db = new (this as any)() as VersionedSqliteDb; // \"as any\" necessary because VersionedSqliteDb is abstract\n IModelJsFs.recursiveMkDirSync(dirname(fileName));\n if (fs.existsSync(fileName))\n fs.unlinkSync(fileName);\n\n db.createDb(fileName);\n db.createDDL(setupArgs);\n const minVer = `^${db.myVersion}`;\n db.setRequiredVersions({ readVersion: minVer, writeVersion: minVer });\n db.closeDb(true);\n }\n\n /**\n * Verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\n * Throws otherwise.\n */\n protected verifyVersions() {\n const versions = this.getRequiredVersions();\n const isReadonly = this.isReadonly; // so we can tell read/write after the file is closed.\n const range = isReadonly ? versions.readVersion : versions.writeVersion;\n if (semver.satisfies(this.myVersion, range))\n return;\n\n this.closeDb();\n const tooNew = semver.gtr(this.myVersion, range);\n SqliteError.throwError(\"incompatible-version\", `requires ${tooNew ? \"older\" : \"newer\"} version of ${this.constructor.name} for ${isReadonly ? \"read\" : \"write\"}`, this[_nativeDb].getFilePath());\n\n }\n\n /**\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.\n * Throws otherwise.\n * @see [[SqliteDb.openDb]] for argument types\n */\n public override openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer) {\n super.openDb(dbName, openMode, container);\n this.verifyVersions();\n }\n\n public async upgradeSchema(arg: { dbName: string, lockContainer?: { container: CloudSqlite.CloudContainer, user: string }, upgradeFn: () => void }) {\n // can't use \"this\" because it checks for version, which we don't want here\n return (arg.lockContainer) ?\n super.withLockedContainer({ dbName: arg.dbName, ...arg.lockContainer }, async () => arg.upgradeFn) :\n super.withOpenDb({ ...arg, openMode: OpenMode.ReadWrite }, arg.upgradeFn);\n }\n}\n\n/** @public */\nexport namespace SQLiteDb {\n /** A semver version range.\n * @see https://docs.npmjs.com/cli/v6/using-npm/semver\n */\n export type VersionRange = string;\n\n /**\n * A pair of semver [[SQLiteDb.VersionRange]]s, one for read and one for write, required to access a [[VersionedSqliteDb]].\n * If the version of the software attempting to read or write the database does not satisfy the range, access is denied.\n */\n export interface RequiredVersionRanges {\n /** a range of acceptable persistence versions for reading from a VersionedSqliteDb. */\n readonly readVersion: VersionRange;\n /** a range of acceptable persistence versions for writing to a VersionedSqliteDb. */\n readonly writeVersion: VersionRange;\n }\n\n /** interface for reading and writing to a blob in a SQLiteDb\n * @internal\n */\n export interface BlobIO {\n /** Close this BlobIO if it is opened.\n * @note this BlobIO *may* be reused after this call by calling `open` again.\n */\n close(): void;\n /** get the total number of bytes in the blob */\n getNumBytes(): number;\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\n isValid(): boolean;\n /** Open this BlobIO against a table/row/column in a Db */\n open(\n /** The database for the blob */\n db: IModelJsNative.AnyDb,\n args: {\n /** the name of the table for the blob*/\n tableName: string;\n /** the name of the column for the blob */\n columnName: string;\n /** The rowId of the blob */\n row: number;\n /** If true, open this BlobIO for write access */\n writeable?: boolean;\n }): void;\n /** Read from a blob\n * @returns the contents of the requested byte range\n */\n read(args: {\n /** The number of bytes to read */\n numBytes: number;\n /** starting offset within the blob to read */\n offset: number;\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\n blob?: ArrayBuffer;\n }): Uint8Array;\n /** Reposition this BlobIO to a new rowId\n * @note this BlobIO must be valid when this methods is called.\n */\n changeRow(row: number): void;\n /** Write to a blob */\n write(args: {\n /** The number of bytes to write */\n numBytes: number;\n /** starting offset within the blob to write */\n offset: number;\n /** the value to write */\n blob: ArrayBuffer;\n }): void;\n }\n\n /** Default transaction mode for SQLiteDbs.\n * @see https://www.sqlite.org/lang_transaction.html\n */\n export enum DefaultTxnMode {\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\n None = 0,\n /** A deferred transaction is started when the file is first opened. This is the default. */\n Deferred = 1,\n /** An immediate transaction is started when the file is first opened. */\n Immediate = 2,\n /** An exclusive transaction is started when the file is first opened. */\n Exclusive = 3\n }\n\n /** parameters common to opening or creating a new SQLiteDb */\n export interface OpenOrCreateParams {\n /** If true, do not require that the `be_Prop` table exist */\n rawSQLite?: boolean;\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\n immutable?: boolean;\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\n skipFileCheck?: boolean;\n /** the default transaction mode\n * @see [[SQLiteDb.DefaultTxnMode]]\n */\n defaultTxn?: 0 | 1 | 2 | 3;\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\n queryParam?: string;\n }\n\n /** Parameters for opening an existing SQLiteDb */\n export interface OpenParams extends OpenOrCreateParams {\n /** use OpenMode.ReadWrite to open the file with write access */\n openMode: OpenMode;\n }\n\n /** Size of a SQLiteDb page in bytes */\n export interface PageSize {\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\n pageSize?: number;\n }\n\n /** Parameters for creating a new SQLiteDb */\n export type CreateParams = OpenOrCreateParams & PageSize;\n\n /** Arguments for `SqliteDb.withOpenDb` */\n export interface WithOpenDbArgs {\n /** The name of the database to open */\n dbName: string;\n /** either an object with the open parameters or just OpenMode value. */\n openMode?: OpenMode | SQLiteDb.OpenParams;\n /** @internal */\n container?: CloudSqlite.CloudContainer;\n }\n\n /** Arguments for `SQLiteDb.vacuum` */\n export interface VacuumDbArgs extends PageSize {\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\n into?: LocalFileName;\n }\n}\n"]}
1
+ {"version":3,"file":"SQLiteDb.js","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,OAAO,EA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,QAAQ,QAiIxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module SQLiteDb\n */\n\nimport * as fs from \"fs\";\nimport { dirname } from \"path\";\nimport * as semver from \"semver\";\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\nimport { DbResult, OpenMode } from \"@itwin/core-bentley\";\nimport { LocalFileName, SqliteError } from \"@itwin/core-common\";\nimport { CloudSqlite } from \"./CloudSqlite\";\nimport { IModelNative } from \"./internal/NativePlatform\";\nimport { IModelJsFs } from \"./IModelJsFs\";\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\nimport { _nativeDb } from \"./internal/Symbols\";\n\n// cspell:ignore savepoint julianday rowid\n\n/**\n * A \"generic\" SQLiteDb. This class may be used to access local files or databases in a cloud container.\n * @public\n */\nexport class SQLiteDb {\n /** @internal */\n public readonly [_nativeDb] = new IModelNative.platform.SQLiteDb();\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\n\n /** @internal */\n public static createBlobIO(): SQLiteDb.BlobIO {\n return new IModelNative.platform.BlobIO();\n }\n\n /** alias for closeDb.\n * @deprecated in 4.0 - might be removed in next major version. Use [[closeDb]]\n */\n public dispose(): void {\n this.closeDb();\n }\n\n /** Create a SQLiteDb\n * @param dbName The path to the SQLiteDb file to create.\n */\n public createDb(dbName: string): void;\n /** @beta */\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\n this[_nativeDb].createDb(dbName, container, params);\n }\n\n /** Open a SQLiteDb.\n * @param dbName The path to the SQLiteDb file to open\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\n /**\n * @param container optional CloudContainer holding database\n * @beta\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\n this[_nativeDb].openDb(dbName, openMode, container);\n }\n\n /** Close SQLiteDb.\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\n */\n public closeDb(saveChanges?: boolean): void {\n if (saveChanges && this.isOpen)\n this.saveChanges();\n this._sqliteStatementCache.clear();\n this[_nativeDb].closeDb();\n }\n\n /** Returns true if this SQLiteDb is open */\n public get isOpen(): boolean { return this[_nativeDb].isOpen(); }\n\n /** Returns true if this SQLiteDb is open readonly */\n public get isReadonly(): boolean { return this[_nativeDb].isReadonly(); }\n\n /** Create a new table in this database. */\n protected createTable(args: {\n /** The name of the table to create. */\n tableName: string;\n /** all of the columns in the table. */\n columns: string;\n /** any unique or foreign key constraints */\n constraints?: string;\n /** if true, add a \"lastMod\" timestamp column and triggers to automatically update it. */\n addTimestamp?: boolean;\n }) {\n const timestampCol = args.addTimestamp ? \",lastMod TIMESTAMP NOT NULL DEFAULT(julianday('now'))\" : \"\";\n const constraints = args.constraints ? `,${args.constraints}` : \"\";\n this.executeSQL(`CREATE TABLE ${args.tableName}(${args.columns}${timestampCol}${constraints})`);\n if (args.addTimestamp)\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`);\n }\n\n /**\n * Get the last modified date for a row in a table of this database.\n * @note the table must have been created with `addTimestamp: true`\n */\n public readLastModTime(tableName: string, rowId: number): Date {\n return this.withSqliteStatement(`SELECT lastMod from ${tableName} WHERE rowid=?`, (stmt) => {\n stmt.bindInteger(1, rowId);\n return stmt.getValueDate(0);\n });\n }\n\n /**\n * Open a database, perform an operation, then close the database.\n *\n * Details:\n * - if database is open, throw an error\n * - open a database\n * - call a function with the database opened. If it is async, await its return.\n * - if function throws, abandon all changes, close database, and rethrow\n * - save all changes\n * - close the database\n * @return value from operation\n */\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\n if (this.isOpen)\n SqliteError.throwError(\"already-open\", \"database is already open\", args.dbName);\n\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\n try {\n const result = operation();\n result instanceof Promise ? result.then(save, abandon) : save();\n return result;\n } catch (e) {\n abandon();\n throw e;\n }\n }\n\n /** The cloud container backing this SQLite database, if any.\n * @beta\n */\n public get cloudContainer(): CloudSqlite.CloudContainer | undefined {\n return this[_nativeDb].cloudContainer;\n }\n\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). */\n public getLastInsertRowId(): number {\n return this[_nativeDb].getLastInsertRowId();\n }\n\n /**\n * Perform an operation on a database in a CloudContainer with the write lock held.\n *\n * Details:\n * - acquire the write lock on a CloudContainer\n * - call `withOpenDb` with openMode `ReadWrite`\n * - upload changes\n * - release the write lock\n * @param args arguments to lock the container and open the database\n * @param operation an operation performed on the database with the write lock held.\n * @return value from operation\n * @internal\n */\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => Promise<T>) {\n return CloudSqlite.withWriteLock(args, async () => this.withOpenDb({ ...args, openMode: args.openMode ?? OpenMode.ReadWrite }, operation));\n }\n\n /** vacuum this database\n * @see https://www.sqlite.org/lang_vacuum.html\n */\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\n this[_nativeDb].vacuum(args);\n }\n\n /** Commit the outermost transaction, writing changes to the file. Then, restart the default transaction. */\n public saveChanges(): void {\n this[_nativeDb].saveChanges();\n }\n\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the default transaction. */\n public abandonChanges(): void {\n this[_nativeDb].abandonChanges();\n }\n\n /**\n * Apply a changeset file - in the same on-disk format used for iModel changesets - to this SQLiteDb.\n * Unlike `BriefcaseDb.pullChanges`, this does *not* validate the changeset header (e.g. parentId/changesetId)\n * against the current state of the database - it simply applies the changes it contains. If applying the\n * changeset encounters any conflict, or otherwise fails, this method throws (conflicts are never resolved\n * automatically).\n * @note this method only throws on failure - it does *not* commit or abandon any changes itself. If it\n * throws, some (but not necessarily all) of the changeset's changes may have already been applied to the\n * current transaction. It is the caller's responsibility to call [[saveChanges]] or [[abandonChanges]]\n * as appropriate after catching an error from this method.\n * @param changesetFile the local file name of the changeset to apply.\n * @internal\n */\n public applyChangeset(changesetFile: LocalFileName): void {\n this[_nativeDb].applyChangeset(changesetFile);\n }\n\n /**\n * Begin capturing DDL and data changes made to this SQLiteDb, so they may later be saved via [[createChangeset]].\n * Intended only to produce changeset files for testing [[applyChangeset]] - not for any other purpose.\n * @internal\n */\n public startChangeTracking(): void {\n this[_nativeDb].startChangeTracking();\n }\n\n /**\n * Execute a DDL statement (e.g. `CREATE TABLE`) so that, if change tracking is active (see [[startChangeTracking]]),\n * the DDL is captured for inclusion in the changeset produced by [[createChangeset]]. DDL executed via [[executeSQL]]\n * is *not* captured for change tracking purposes.\n * @internal\n */\n public executeDdl(ddl: string): void {\n this[_nativeDb].executeDdl(ddl);\n }\n\n /**\n * Write out the changes captured since [[startChangeTracking]] was called to a changeset file, in the same\n * on-disk format used for iModel changesets.\n * @param changesetFile the local file name to write the changeset to.\n * @internal\n */\n public createChangeset(changesetFile: LocalFileName): void {\n this[_nativeDb].createChangeset(changesetFile);\n }\n\n /**\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Prepare and execute a callback on a SQL statement. After the callback completes the statement is disposed.\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this.prepareSqliteStatement(sql);\n const release = () => stmt[Symbol.dispose]();\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\n */\n public withSavePoint(savePointName: string, operation: () => void) {\n if (this.isReadonly)\n SqliteError.throwError(\"readonly\", \"database is readonly\", this[_nativeDb].getFilePath());\n\n this.executeSQL(`SAVEPOINT ${savePointName}`);\n try {\n operation();\n this.executeSQL(`RELEASE ${savePointName}`);\n } catch (e) {\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\n throw e;\n }\n }\n\n /** Prepare an SQL statement.\n * @param sql The SQLite SQL statement to prepare\n * @param logErrors Determine if errors are logged or not\n * @internal\n */\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\n const stmt = new SqliteStatement(sql);\n stmt.prepare(this[_nativeDb], logErrors);\n return stmt;\n }\n\n /** execute an SQL statement */\n public executeSQL(sql: string): DbResult {\n using stmt = this.prepareSqliteStatement(sql);\n return stmt.step();\n }\n}\n\n/**\n * Abstract base class for a SQLite database that has [[SQLiteDb.RequiredVersionRanges]] stored in it.\n * This class provides version checking when the database is opened, to guarantee that a valid version of software is\n * always used for access.\n *\n * Notes:\n * - This class may be used either to access a local file, or one stored in a cloud container.\n * - Subclasses must provide a `myVersion` member indicating the version of its software, and implement the `createDDL` member to create its\n * tables.\n * @beta\n */\nexport abstract class VersionedSqliteDb extends SQLiteDb {\n protected static _versionProps = { namespace: \"SQLiteDb\", name: \"versions\" } as const;\n\n /** The current semver \"persistence version\" of this class.\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.\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\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\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\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\n * supported by it, the user will be informed that they need to upgrade their software.\n * @note this identifier is independent of versions in `package.json` files.\n */\n public abstract myVersion: string;\n\n /**\n * Change the \"versions required to open this database\" property stored in this database. After this call,\n * versions of software that don't meet the supplied ranges will fail.\n * @param versions the new versions required for reading and writing this database.\n * @note the database must be opened for write access.\n */\n public setRequiredVersions(versions: SQLiteDb.RequiredVersionRanges) {\n // NOTE: It might look tempting to just stringify the supplied `versions` object, but we only include required members - there may be others.\n this[_nativeDb].saveFileProperty(VersionedSqliteDb._versionProps, JSON.stringify({ readVersion: versions.readVersion, writeVersion: versions.writeVersion }));\n }\n\n /** Get the required version ranges necessary to open this VersionedSqliteDb. */\n public getRequiredVersions() {\n const checkIsString = (value: any) => {\n if (typeof value !== \"string\")\n SqliteError.throwError(\"invalid-versions-property\", `CloudDb has invalid \"versions\" property`, this[_nativeDb].getFilePath());\n return value;\n };\n const versionJson = checkIsString(this[_nativeDb].queryFileProperty(VersionedSqliteDb._versionProps, true));\n const versionRanges = JSON.parse(versionJson) as SQLiteDb.RequiredVersionRanges;\n checkIsString(versionRanges.readVersion);\n checkIsString(versionRanges.writeVersion);\n return versionRanges;\n }\n\n /**\n * Implement this method to create all tables for this subclass of `VersionedSqliteDb` when a new database file is created. Called from [[createNewDb]].\n */\n protected abstract createDDL(args: any): void;\n\n /**\n * Create a new database file for the subclass of VersionedSqliteDb.\n * @note The required versions are saved as [[myVersion]] or newer for both read and write.\n */\n public static createNewDb(fileName: LocalFileName, setupArgs?: any) {\n const db = new (this as any)() as VersionedSqliteDb; // \"as any\" necessary because VersionedSqliteDb is abstract\n IModelJsFs.recursiveMkDirSync(dirname(fileName));\n if (fs.existsSync(fileName))\n fs.unlinkSync(fileName);\n\n db.createDb(fileName);\n db.createDDL(setupArgs);\n const minVer = `^${db.myVersion}`;\n db.setRequiredVersions({ readVersion: minVer, writeVersion: minVer });\n db.closeDb(true);\n }\n\n /**\n * Verify that this version of the software meets the required version range (as appropriate, read or write) stored in the database.\n * Throws otherwise.\n */\n protected verifyVersions() {\n const versions = this.getRequiredVersions();\n const isReadonly = this.isReadonly; // so we can tell read/write after the file is closed.\n const range = isReadonly ? versions.readVersion : versions.writeVersion;\n if (semver.satisfies(this.myVersion, range))\n return;\n\n this.closeDb();\n const tooNew = semver.gtr(this.myVersion, range);\n SqliteError.throwError(\"incompatible-version\", `requires ${tooNew ? \"older\" : \"newer\"} version of ${this.constructor.name} for ${isReadonly ? \"read\" : \"write\"}`, this[_nativeDb].getFilePath());\n\n }\n\n /**\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.\n * Throws otherwise.\n * @see [[SqliteDb.openDb]] for argument types\n */\n public override openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer) {\n super.openDb(dbName, openMode, container);\n this.verifyVersions();\n }\n\n public async upgradeSchema(arg: { dbName: string, lockContainer?: { container: CloudSqlite.CloudContainer, user: string }, upgradeFn: () => void }) {\n // can't use \"this\" because it checks for version, which we don't want here\n return (arg.lockContainer) ?\n super.withLockedContainer({ dbName: arg.dbName, ...arg.lockContainer }, async () => arg.upgradeFn) :\n super.withOpenDb({ ...arg, openMode: OpenMode.ReadWrite }, arg.upgradeFn);\n }\n}\n\n/** @public */\nexport namespace SQLiteDb {\n /** A semver version range.\n * @see https://docs.npmjs.com/cli/v6/using-npm/semver\n */\n export type VersionRange = string;\n\n /**\n * A pair of semver [[SQLiteDb.VersionRange]]s, one for read and one for write, required to access a [[VersionedSqliteDb]].\n * If the version of the software attempting to read or write the database does not satisfy the range, access is denied.\n */\n export interface RequiredVersionRanges {\n /** a range of acceptable persistence versions for reading from a VersionedSqliteDb. */\n readonly readVersion: VersionRange;\n /** a range of acceptable persistence versions for writing to a VersionedSqliteDb. */\n readonly writeVersion: VersionRange;\n }\n\n /** interface for reading and writing to a blob in a SQLiteDb\n * @internal\n */\n export interface BlobIO {\n /** Close this BlobIO if it is opened.\n * @note this BlobIO *may* be reused after this call by calling `open` again.\n */\n close(): void;\n /** get the total number of bytes in the blob */\n getNumBytes(): number;\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\n isValid(): boolean;\n /** Open this BlobIO against a table/row/column in a Db */\n open(\n /** The database for the blob */\n db: IModelJsNative.AnyDb,\n args: {\n /** the name of the table for the blob*/\n tableName: string;\n /** the name of the column for the blob */\n columnName: string;\n /** The rowId of the blob */\n row: number;\n /** If true, open this BlobIO for write access */\n writeable?: boolean;\n }): void;\n /** Read from a blob\n * @returns the contents of the requested byte range\n */\n read(args: {\n /** The number of bytes to read */\n numBytes: number;\n /** starting offset within the blob to read */\n offset: number;\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\n blob?: ArrayBuffer;\n }): Uint8Array;\n /** Reposition this BlobIO to a new rowId\n * @note this BlobIO must be valid when this methods is called.\n */\n changeRow(row: number): void;\n /** Write to a blob */\n write(args: {\n /** The number of bytes to write */\n numBytes: number;\n /** starting offset within the blob to write */\n offset: number;\n /** the value to write */\n blob: ArrayBuffer;\n }): void;\n }\n\n /** Default transaction mode for SQLiteDbs.\n * @see https://www.sqlite.org/lang_transaction.html\n */\n export enum DefaultTxnMode {\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\n None = 0,\n /** A deferred transaction is started when the file is first opened. This is the default. */\n Deferred = 1,\n /** An immediate transaction is started when the file is first opened. */\n Immediate = 2,\n /** An exclusive transaction is started when the file is first opened. */\n Exclusive = 3\n }\n\n /** parameters common to opening or creating a new SQLiteDb */\n export interface OpenOrCreateParams {\n /** If true, do not require that the `be_Prop` table exist */\n rawSQLite?: boolean;\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\n immutable?: boolean;\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\n skipFileCheck?: boolean;\n /** the default transaction mode\n * @see [[SQLiteDb.DefaultTxnMode]]\n */\n defaultTxn?: 0 | 1 | 2 | 3;\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\n queryParam?: string;\n }\n\n /** Parameters for opening an existing SQLiteDb */\n export interface OpenParams extends OpenOrCreateParams {\n /** use OpenMode.ReadWrite to open the file with write access */\n openMode: OpenMode;\n }\n\n /** Size of a SQLiteDb page in bytes */\n export interface PageSize {\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\n pageSize?: number;\n }\n\n /** Parameters for creating a new SQLiteDb */\n export type CreateParams = OpenOrCreateParams & PageSize;\n\n /** Arguments for `SqliteDb.withOpenDb` */\n export interface WithOpenDbArgs {\n /** The name of the database to open */\n dbName: string;\n /** either an object with the open parameters or just OpenMode value. */\n openMode?: OpenMode | SQLiteDb.OpenParams;\n /** @internal */\n container?: CloudSqlite.CloudContainer;\n }\n\n /** Arguments for `SQLiteDb.vacuum` */\n export interface VacuumDbArgs extends PageSize {\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\n into?: LocalFileName;\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- export {};
1
+ import "../TestUtils";
2
2
  //# sourceMappingURL=SQLiteDb.test.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteDb.test.d.ts","sourceRoot":"","sources":["../../../../src/test/standalone/SQLiteDb.test.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"SQLiteDb.test.d.ts","sourceRoot":"","sources":["../../../../src/test/standalone/SQLiteDb.test.ts"],"names":[],"mappings":"AAYA,OAAO,cAAc,CAAC"}
@@ -2,10 +2,65 @@
2
2
  * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
3
3
  * See LICENSE.md in the project root for license terms and full copyright notice.
4
4
  *--------------------------------------------------------------------------------------------*/
5
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
6
+ if (value !== null && value !== void 0) {
7
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
8
+ var dispose, inner;
9
+ if (async) {
10
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
11
+ dispose = value[Symbol.asyncDispose];
12
+ }
13
+ if (dispose === void 0) {
14
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
15
+ dispose = value[Symbol.dispose];
16
+ if (async) inner = dispose;
17
+ }
18
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
19
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
20
+ env.stack.push({ value: value, dispose: dispose, async: async });
21
+ }
22
+ else if (async) {
23
+ env.stack.push({ async: true });
24
+ }
25
+ return value;
26
+ };
27
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
28
+ return function (env) {
29
+ function fail(e) {
30
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
31
+ env.hasError = true;
32
+ }
33
+ var r, s = 0;
34
+ function next() {
35
+ while (r = env.stack.pop()) {
36
+ try {
37
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
38
+ if (r.dispose) {
39
+ var result = r.dispose.call(r.value);
40
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
41
+ }
42
+ else s |= 1;
43
+ }
44
+ catch (e) {
45
+ fail(e);
46
+ }
47
+ }
48
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
49
+ if (env.hasError) throw env.error;
50
+ }
51
+ return next();
52
+ };
53
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
54
+ var e = new Error(message);
55
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
56
+ });
5
57
  import { expect } from "chai";
6
58
  import { BeDuration, DbResult, OpenMode } from "@itwin/core-bentley";
7
- import { SQLiteDb } from "../../SQLiteDb";
59
+ import { IModelJsFs } from "../../IModelJsFs";
8
60
  import { IModelTestUtils } from "../IModelTestUtils";
61
+ import { SQLiteDb } from "../../SQLiteDb";
62
+ import { SqliteChangesetReader } from "../../SqliteChangesetReader";
63
+ import "../TestUtils"; // registers the global mocha before/after hooks that start/stop the backend
9
64
  describe("SQLiteDb", () => {
10
65
  it("should create new SQLiteDb", async () => {
11
66
  const fileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "db1.db");
@@ -59,5 +114,95 @@ describe("SQLiteDb", () => {
59
114
  });
60
115
  });
61
116
  });
117
+ describe("applyChangeset", () => {
118
+ const readRows = (db, tableName) => {
119
+ const rows = [];
120
+ db.withSqliteStatement(`SELECT id,val FROM ${tableName} ORDER BY id`, (stmt) => {
121
+ while (stmt.step() === DbResult.BE_SQLITE_ROW)
122
+ rows.push({ id: stmt.getValue(0).getInteger(), val: stmt.getValue(1).getString() });
123
+ });
124
+ return rows;
125
+ };
126
+ it("should apply a changeset containing DDL and data changes", () => {
127
+ const env_1 = { stack: [], error: void 0, hasError: false };
128
+ try {
129
+ const sourceFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-source.db");
130
+ const targetFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-target.db");
131
+ const changesetFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-1.changeset");
132
+ // create the source db, and capture a changeset that creates a table and inserts some rows
133
+ const source = new SQLiteDb();
134
+ source.createDb(sourceFileName, undefined, { rawSQLite: true });
135
+ source.startChangeTracking();
136
+ source.executeDdl("CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)");
137
+ source.executeSQL(`INSERT INTO test1(id,val) VALUES (1,'val1')`);
138
+ source.executeSQL(`INSERT INTO test1(id,val) VALUES (2,'val2')`);
139
+ source.saveChanges();
140
+ source.createChangeset(changesetFileName);
141
+ // verify the changeset's ddl/data via the existing SqliteChangesetReader
142
+ const reader = __addDisposableResource(env_1, SqliteChangesetReader.openFile({ fileName: changesetFileName, db: source, disableSchemaCheck: true }), false);
143
+ let dataChangeCount = 0;
144
+ while (reader.step())
145
+ ++dataChangeCount;
146
+ expect(dataChangeCount).equal(2);
147
+ // apply the changeset (from scratch - no header validation should be required) to a brand new, empty db
148
+ const target = new SQLiteDb();
149
+ target.createDb(targetFileName, undefined, { rawSQLite: true });
150
+ target.applyChangeset(changesetFileName);
151
+ target.saveChanges();
152
+ expect(readRows(target, "test1")).deep.equal([{ id: 1, val: "val1" }, { id: 2, val: "val2" }]);
153
+ source.closeDb();
154
+ target.closeDb();
155
+ }
156
+ catch (e_1) {
157
+ env_1.error = e_1;
158
+ env_1.hasError = true;
159
+ }
160
+ finally {
161
+ __disposeResources(env_1);
162
+ }
163
+ });
164
+ it("should fail if applying a changeset produces a conflict, leaving it to the caller to abandon the partially-applied changes", () => {
165
+ const baseFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-base.db");
166
+ const sourceFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-conflict-source.db");
167
+ const targetFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-conflict-target.db");
168
+ const changesetFileName = IModelTestUtils.prepareOutputFile("SQLiteDb", "applyChangeset-2.changeset");
169
+ // create a common base db with two rows, then clone it so source and target start out identical
170
+ const base = new SQLiteDb();
171
+ base.createDb(baseFileName, undefined, { rawSQLite: true });
172
+ base.executeSQL("CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)");
173
+ base.executeSQL(`INSERT INTO test1(id,val) VALUES (1,'base1')`);
174
+ base.executeSQL(`INSERT INTO test1(id,val) VALUES (2,'base2')`);
175
+ base.saveChanges();
176
+ base.closeDb();
177
+ IModelJsFs.copySync(baseFileName, sourceFileName);
178
+ IModelJsFs.copySync(baseFileName, targetFileName);
179
+ // diverge source: update both rows and capture that as a single changeset. Only the second row will
180
+ // conflict with target's divergence below - the first row's change would apply cleanly on its own.
181
+ const source = new SQLiteDb();
182
+ source.openDb(sourceFileName, { openMode: OpenMode.ReadWrite, rawSQLite: true });
183
+ source.startChangeTracking();
184
+ source.executeSQL(`UPDATE test1 SET val='fromSource1' WHERE id=1`);
185
+ source.executeSQL(`UPDATE test1 SET val='fromSource2' WHERE id=2`);
186
+ source.saveChanges();
187
+ source.createChangeset(changesetFileName);
188
+ source.closeDb();
189
+ // diverge target independently - only on the second row - so applying source's changeset conflicts partway through
190
+ const target = new SQLiteDb();
191
+ target.openDb(targetFileName, { openMode: OpenMode.ReadWrite, rawSQLite: true });
192
+ target.executeSQL(`UPDATE test1 SET val='fromTarget2' WHERE id=2`);
193
+ target.saveChanges();
194
+ // confirm the pre-apply baseline: id=1 was never touched by target, id=2 diverged from source
195
+ expect(readRows(target, "test1")).deep.equal([{ id: 1, val: "base1" }, { id: 2, val: "fromTarget2" }]);
196
+ // applyChangeset only throws on failure - it does not commit or abandon changes itself. Since the first
197
+ // row's change didn't conflict, it may already have been applied to the current transaction by the time
198
+ // the second row's conflict causes the throw.
199
+ expect(() => target.applyChangeset(changesetFileName)).throws();
200
+ expect(readRows(target, "test1")).deep.equal([{ id: 1, val: "fromSource1" }, { id: 2, val: "fromTarget2" }]);
201
+ // it is the caller's responsibility to abandon (or save) the partially-applied changes after catching the error
202
+ target.abandonChanges();
203
+ expect(readRows(target, "test1")).deep.equal([{ id: 1, val: "base1" }, { id: 2, val: "fromTarget2" }]);
204
+ target.closeDb();
205
+ });
206
+ });
62
207
  });
63
208
  //# sourceMappingURL=SQLiteDb.test.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"SQLiteDb.test.js","sourceRoot":"","sources":["../../../../src/test/standalone/SQLiteDb.test.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD,QAAQ,CAAC,UAAU,EAAE,GAAG,EAAE;IAExB,EAAE,CAAC,4BAA4B,EAAE,KAAK,IAAI,EAAE;QAC1C,MAAM,QAAQ,GAAG,eAAe,CAAC,iBAAiB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QACzE,MAAM,EAAE,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC1B,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;QAC1E,EAAE,CAAC,UAAU,CAAC,qDAAqD,CAAC,CAAC;QACrE,EAAE,CAAC,UAAU,CAAC,6CAA6C,CAAC,CAAC;QAC7D,EAAE,CAAC,UAAU,CAAC,6CAA6C,CAAC,CAAC;QAC7D,EAAE,CAAC,WAAW,EAAE,CAAC;QAEjB,MAAM,MAAM,GAAG,GAAG,EAAE;YAClB,EAAE,CAAC,mBAAmB,CAAC,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,CAAC,CAAC;gBAClD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC;gBACrD,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;gBACjD,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;YACnD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AAEL,CAAC,CAAC,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n\nimport { expect } from \"chai\";\nimport { BeDuration, DbResult, OpenMode } from \"@itwin/core-bentley\";\nimport { SQLiteDb } from \"../../SQLiteDb\";\nimport { IModelTestUtils } from \"../IModelTestUtils\";\n\ndescribe(\"SQLiteDb\", () => {\n\n it(\"should create new SQLiteDb\", async () => {\n const fileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"db1.db\");\n const db = new SQLiteDb();\n db.createDb(fileName, undefined, { rawSQLite: true, pageSize: 8 * 1024 });\n db.executeSQL(\"CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)\");\n db.executeSQL(`INSERT INTO test1(id,val) VALUES (1,\"val1\")`);\n db.executeSQL(`INSERT INTO test1(id,val) VALUES (2,\"val2\")`);\n db.saveChanges();\n\n const testDb = () => {\n db.withSqliteStatement(\"SELECT id,val from test1\", (stmt) => {\n stmt.step();\n expect(stmt.getValue(0).getInteger()).equal(1);\n expect(stmt.getValue(1).getString()).equal(\"val1\");\n stmt.step();\n expect(stmt.getValue(0).getInteger()).equal(2);\n expect(stmt.getValue(1).getString()).equal(\"val2\");\n });\n db.closeDb();\n };\n testDb();\n\n // now test immutable flag\n db.openDb(fileName, { openMode: OpenMode.Readonly, skipFileCheck: true, immutable: true, defaultTxn: SQLiteDb.DefaultTxnMode.None, rawSQLite: true });\n testDb();\n\n expect(db.isOpen).false;\n expect(() => db.vacuum()).throws(\"not open\");\n\n let val = db.withOpenDb({ dbName: fileName, openMode: { openMode: OpenMode.ReadWrite, rawSQLite: true } }, () => {\n expect(db.isOpen);\n db.vacuum();\n return 22;\n });\n expect(val).equal(22);\n expect(db.isOpen).false;\n\n val = await db.withOpenDb({ dbName: fileName, openMode: { openMode: OpenMode.ReadWrite, rawSQLite: true } }, async () => {\n expect(db.isOpen);\n await BeDuration.fromMilliseconds(10).wait();\n return 100;\n });\n expect(val).equal(100);\n expect(db.isOpen).false;\n });\n\n it(\"should be able to open existing .bim file with SQLiteDb\", () => {\n const testFileName = IModelTestUtils.resolveAssetFile(\"test.bim\");\n const db = new SQLiteDb();\n db.withOpenDb({ dbName: testFileName }, () => {\n db.withSqliteStatement(`SELECT StrData FROM be_Prop WHERE Namespace=\"ec_Db\" AND Name=\"SchemaVersion\"`, (stmt) => {\n expect(stmt.step()).equal(DbResult.BE_SQLITE_ROW);\n const val = JSON.parse(stmt.getValue(0).getString());\n expect(val.major).equal(4, \"read major version\");\n expect(val.minor).equal(0, \"read minor version\");\n });\n });\n });\n\n});\n"]}
1
+ {"version":3,"file":"SQLiteDb.test.js","sourceRoot":"","sources":["../../../../src/test/standalone/SQLiteDb.test.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE/F,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CA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AE,IAAI,EAAE,CAAC,CAAC;YACjF,MAAM,CAAC,UAAU,CAAC,+CAA+C,CAAC,CAAC;YACnE,MAAM,CAAC,WAAW,EAAE,CAAC;YAErB,8FAA8F;YAC9F,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC;YAEvG,wGAAwG;YACxG,wGAAwG;YACxG,8CAA8C;YAC9C,MAAM,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;YAChE,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,aAAa,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC;YAE7G,gHAAgH;YAChH,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC;YAEvG,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AAEL,CAAC,CAAC,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n\nimport { expect } from \"chai\";\nimport { BeDuration, DbResult, OpenMode } from \"@itwin/core-bentley\";\nimport type { IModelDb } from \"../../IModelDb\";\nimport { IModelJsFs } from \"../../IModelJsFs\";\nimport { IModelTestUtils } from \"../IModelTestUtils\";\nimport { SQLiteDb } from \"../../SQLiteDb\";\nimport { SqliteChangesetReader } from \"../../SqliteChangesetReader\";\nimport \"../TestUtils\"; // registers the global mocha before/after hooks that start/stop the backend\n\ndescribe(\"SQLiteDb\", () => {\n\n it(\"should create new SQLiteDb\", async () => {\n const fileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"db1.db\");\n const db = new SQLiteDb();\n db.createDb(fileName, undefined, { rawSQLite: true, pageSize: 8 * 1024 });\n db.executeSQL(\"CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)\");\n db.executeSQL(`INSERT INTO test1(id,val) VALUES (1,\"val1\")`);\n db.executeSQL(`INSERT INTO test1(id,val) VALUES (2,\"val2\")`);\n db.saveChanges();\n\n const testDb = () => {\n db.withSqliteStatement(\"SELECT id,val from test1\", (stmt) => {\n stmt.step();\n expect(stmt.getValue(0).getInteger()).equal(1);\n expect(stmt.getValue(1).getString()).equal(\"val1\");\n stmt.step();\n expect(stmt.getValue(0).getInteger()).equal(2);\n expect(stmt.getValue(1).getString()).equal(\"val2\");\n });\n db.closeDb();\n };\n testDb();\n\n // now test immutable flag\n db.openDb(fileName, { openMode: OpenMode.Readonly, skipFileCheck: true, immutable: true, defaultTxn: SQLiteDb.DefaultTxnMode.None, rawSQLite: true });\n testDb();\n\n expect(db.isOpen).false;\n expect(() => db.vacuum()).throws(\"not open\");\n\n let val = db.withOpenDb({ dbName: fileName, openMode: { openMode: OpenMode.ReadWrite, rawSQLite: true } }, () => {\n expect(db.isOpen);\n db.vacuum();\n return 22;\n });\n expect(val).equal(22);\n expect(db.isOpen).false;\n\n val = await db.withOpenDb({ dbName: fileName, openMode: { openMode: OpenMode.ReadWrite, rawSQLite: true } }, async () => {\n expect(db.isOpen);\n await BeDuration.fromMilliseconds(10).wait();\n return 100;\n });\n expect(val).equal(100);\n expect(db.isOpen).false;\n });\n\n it(\"should be able to open existing .bim file with SQLiteDb\", () => {\n const testFileName = IModelTestUtils.resolveAssetFile(\"test.bim\");\n const db = new SQLiteDb();\n db.withOpenDb({ dbName: testFileName }, () => {\n db.withSqliteStatement(`SELECT StrData FROM be_Prop WHERE Namespace=\"ec_Db\" AND Name=\"SchemaVersion\"`, (stmt) => {\n expect(stmt.step()).equal(DbResult.BE_SQLITE_ROW);\n const val = JSON.parse(stmt.getValue(0).getString());\n expect(val.major).equal(4, \"read major version\");\n expect(val.minor).equal(0, \"read minor version\");\n });\n });\n });\n\n describe(\"applyChangeset\", () => {\n const readRows = (db: SQLiteDb, tableName: string) => {\n const rows: Array<{ id: number, val: string }> = [];\n db.withSqliteStatement(`SELECT id,val FROM ${tableName} ORDER BY id`, (stmt) => {\n while (stmt.step() === DbResult.BE_SQLITE_ROW)\n rows.push({ id: stmt.getValue(0).getInteger(), val: stmt.getValue(1).getString() });\n });\n return rows;\n };\n\n it(\"should apply a changeset containing DDL and data changes\", () => {\n const sourceFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-source.db\");\n const targetFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-target.db\");\n const changesetFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-1.changeset\");\n\n // create the source db, and capture a changeset that creates a table and inserts some rows\n const source = new SQLiteDb();\n source.createDb(sourceFileName, undefined, { rawSQLite: true });\n source.startChangeTracking();\n source.executeDdl(\"CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)\");\n source.executeSQL(`INSERT INTO test1(id,val) VALUES (1,'val1')`);\n source.executeSQL(`INSERT INTO test1(id,val) VALUES (2,'val2')`);\n source.saveChanges();\n source.createChangeset(changesetFileName);\n\n // verify the changeset's ddl/data via the existing SqliteChangesetReader\n using reader = SqliteChangesetReader.openFile({ fileName: changesetFileName, db: source as unknown as IModelDb, disableSchemaCheck: true });\n let dataChangeCount = 0;\n while (reader.step())\n ++dataChangeCount;\n expect(dataChangeCount).equal(2);\n\n // apply the changeset (from scratch - no header validation should be required) to a brand new, empty db\n const target = new SQLiteDb();\n target.createDb(targetFileName, undefined, { rawSQLite: true });\n target.applyChangeset(changesetFileName);\n target.saveChanges();\n\n expect(readRows(target, \"test1\")).deep.equal([{ id: 1, val: \"val1\" }, { id: 2, val: \"val2\" }]);\n\n source.closeDb();\n target.closeDb();\n });\n\n it(\"should fail if applying a changeset produces a conflict, leaving it to the caller to abandon the partially-applied changes\", () => {\n const baseFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-base.db\");\n const sourceFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-conflict-source.db\");\n const targetFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-conflict-target.db\");\n const changesetFileName = IModelTestUtils.prepareOutputFile(\"SQLiteDb\", \"applyChangeset-2.changeset\");\n\n // create a common base db with two rows, then clone it so source and target start out identical\n const base = new SQLiteDb();\n base.createDb(baseFileName, undefined, { rawSQLite: true });\n base.executeSQL(\"CREATE TABLE test1(id INTEGER PRIMARY KEY,val TEXT)\");\n base.executeSQL(`INSERT INTO test1(id,val) VALUES (1,'base1')`);\n base.executeSQL(`INSERT INTO test1(id,val) VALUES (2,'base2')`);\n base.saveChanges();\n base.closeDb();\n\n IModelJsFs.copySync(baseFileName, sourceFileName);\n IModelJsFs.copySync(baseFileName, targetFileName);\n\n // diverge source: update both rows and capture that as a single changeset. Only the second row will\n // conflict with target's divergence below - the first row's change would apply cleanly on its own.\n const source = new SQLiteDb();\n source.openDb(sourceFileName, { openMode: OpenMode.ReadWrite, rawSQLite: true });\n source.startChangeTracking();\n source.executeSQL(`UPDATE test1 SET val='fromSource1' WHERE id=1`);\n source.executeSQL(`UPDATE test1 SET val='fromSource2' WHERE id=2`);\n source.saveChanges();\n source.createChangeset(changesetFileName);\n source.closeDb();\n\n // diverge target independently - only on the second row - so applying source's changeset conflicts partway through\n const target = new SQLiteDb();\n target.openDb(targetFileName, { openMode: OpenMode.ReadWrite, rawSQLite: true });\n target.executeSQL(`UPDATE test1 SET val='fromTarget2' WHERE id=2`);\n target.saveChanges();\n\n // confirm the pre-apply baseline: id=1 was never touched by target, id=2 diverged from source\n expect(readRows(target, \"test1\")).deep.equal([{ id: 1, val: \"base1\" }, { id: 2, val: \"fromTarget2\" }]);\n\n // applyChangeset only throws on failure - it does not commit or abandon changes itself. Since the first\n // row's change didn't conflict, it may already have been applied to the current transaction by the time\n // the second row's conflict causes the throw.\n expect(() => target.applyChangeset(changesetFileName)).throws();\n expect(readRows(target, \"test1\")).deep.equal([{ id: 1, val: \"fromSource1\" }, { id: 2, val: \"fromTarget2\" }]);\n\n // it is the caller's responsibility to abandon (or save) the partially-applied changes after catching the error\n target.abandonChanges();\n expect(readRows(target, \"test1\")).deep.equal([{ id: 1, val: \"base1\" }, { id: 2, val: \"fromTarget2\" }]);\n\n target.closeDb();\n });\n });\n\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@itwin/core-backend",
3
- "version": "5.12.0-dev.11",
3
+ "version": "5.12.0-dev.12",
4
4
  "description": "iTwin.js backend components",
5
5
  "main": "lib/cjs/core-backend.js",
6
6
  "module": "lib/esm/core-backend.js",
@@ -27,10 +27,10 @@
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@opentelemetry/api": "^1.0.4",
30
- "@itwin/core-bentley": "5.12.0-dev.11",
31
- "@itwin/ecschema-metadata": "5.12.0-dev.11",
32
- "@itwin/core-common": "5.12.0-dev.11",
33
- "@itwin/core-geometry": "5.12.0-dev.11"
30
+ "@itwin/core-bentley": "5.12.0-dev.12",
31
+ "@itwin/core-geometry": "5.12.0-dev.12",
32
+ "@itwin/ecschema-metadata": "5.12.0-dev.12",
33
+ "@itwin/core-common": "5.12.0-dev.12"
34
34
  },
35
35
  "peerDependenciesMeta": {
36
36
  "@opentelemetry/api": {
@@ -77,17 +77,17 @@
77
77
  "marked": "^14.1.3",
78
78
  "sql-formatter": "^15.4.6",
79
79
  "webpack": "^5.97.1",
80
- "@itwin/build-tools": "5.12.0-dev.11",
81
- "@itwin/core-common": "5.12.0-dev.11",
82
- "@itwin/core-bentley": "5.12.0-dev.11",
83
- "@itwin/ecsql-common": "5.12.0-dev.11",
84
- "@itwin/ecschema-metadata": "5.12.0-dev.11",
85
- "@itwin/core-geometry": "5.12.0-dev.11",
80
+ "@itwin/ecschema-locaters": "5.12.0-dev.12",
81
+ "@itwin/build-tools": "5.12.0-dev.12",
86
82
  "internal-tools": "3.0.0-dev.69",
87
- "@itwin/ecschema-locaters": "5.12.0-dev.11"
83
+ "@itwin/core-bentley": "5.12.0-dev.12",
84
+ "@itwin/ecsql-common": "5.12.0-dev.12",
85
+ "@itwin/core-common": "5.12.0-dev.12",
86
+ "@itwin/core-geometry": "5.12.0-dev.12",
87
+ "@itwin/ecschema-metadata": "5.12.0-dev.12"
88
88
  },
89
89
  "dependencies": {
90
- "@bentley/imodeljs-native": "5.12.15",
90
+ "@bentley/imodeljs-native": "5.12.17",
91
91
  "@itwin/object-storage-azure": "^3.0.4",
92
92
  "@azure/storage-blob": "^12.28.0",
93
93
  "form-data": "^4.0.6",