diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md index cfd57f48922dfd..cd6d0574c6215b 100644 --- a/doc/api/sqlite.md +++ b/doc/api/sqlite.md @@ -526,6 +526,63 @@ exception. | `TEXT` | {string} | | `BLOB` | {TypedArray} or {DataView} | +## `sqlite.backup(sourceDb, destination[, options])` + + + +* `sourceDb` {DatabaseSync} The database to backup. The source database must be open. +* `destination` {string} The path where the backup will be created. If the file already exists, the contents will be + overwritten. +* `options` {Object} Optional configuration for the backup. The + following properties are supported: + * `source` {string} Name of the source database. This can be `'main'` (the default primary database) or any other + database that have been added with [`ATTACH DATABASE`][] **Default:** `'main'`. + * `target` {string} Name of the target database. This can be `'main'` (the default primary database) or any other + database that have been added with [`ATTACH DATABASE`][] **Default:** `'main'`. + * `rate` {number} Number of pages to be transmitted in each batch of the backup. **Default:** `100`. + * `progress` {Function} Callback function that will be called with the number of pages copied and the total number of + pages. +* Returns: {Promise} A promise that resolves when the backup is completed and rejects if an error occurs. + +This method makes a database backup. This method abstracts the [`sqlite3_backup_init()`][], [`sqlite3_backup_step()`][] +and [`sqlite3_backup_finish()`][] functions. + +The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same +{DatabaseSync} - object will be reflected in the backup right away. However, mutations from other connections will cause +the backup process to restart. + +```cjs +const { backup, DatabaseSync } = require('node:sqlite'); + +(async () => { + const sourceDb = new DatabaseSync('source.db'); + const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + rate: 1, // Copy one page at a time. + progress: ({ totalPages, remainingPages }) => { + console.log('Backup in progress', { totalPages, remainingPages }); + }, + }); + + console.log('Backup completed', totalPagesTransferred); +})(); +``` + +```mjs +import { backup, DatabaseSync } from 'node:sqlite'; + +const sourceDb = new DatabaseSync('source.db'); +const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + rate: 1, // Copy one page at a time. + progress: ({ totalPages, remainingPages }) => { + console.log('Backup in progress', { totalPages, remainingPages }); + }, +}); + +console.log('Backup completed', totalPagesTransferred); +``` + ## `sqlite.constants`