Fbackup
Bun

function

sqlite.backup

function backup(
sourceDb: DatabaseSync,
path: string | Buffer<ArrayBufferLike> | URL,
options?: BackupOptions
): Promise<void>;

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.

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);
@param sourceDb

The database to backup. The source database must be open.

@param path

The path where the backup will be created. If the file already exists, the contents will be overwritten.

@param options

Optional configuration for the backup. The following properties are supported:

@returns

A promise that resolves when the backup is completed and rejects if an error occurs.

Referenced types

class DatabaseSync

This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.

  • readonly isOpen: boolean

    Whether the database is currently open or not.

  • readonly isTransaction: boolean
  • Closes the database connection. If the database connection is already closed then this is a no-op.

  • name: string,
    ): void;

    Registers a new aggregate function with the SQLite database. This method is a wrapper around sqlite3_create_window_function().

    When used as a window function, the result function will be called multiple times.

    import { DatabaseSync } from 'node:sqlite';
    
    const db = new DatabaseSync(':memory:');
    db.exec(`
      CREATE TABLE t3(x, y);
      INSERT INTO t3 VALUES ('a', 4),
                            ('b', 5),
                            ('c', 3),
                            ('d', 8),
                            ('e', 1);
    `);
    
    db.aggregate('sumint', {
      start: 0,
      step: (acc, value) => acc + value,
    });
    
    db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
    
    @param name

    The name of the SQLite function to create.

    @param options

    Function configuration settings.

    name: string,
    options: AggregateOptions<T>
    ): void;

    Registers a new aggregate function with the SQLite database. This method is a wrapper around sqlite3_create_window_function().

    When used as a window function, the result function will be called multiple times.

    import { DatabaseSync } from 'node:sqlite';
    
    const db = new DatabaseSync(':memory:');
    db.exec(`
      CREATE TABLE t3(x, y);
      INSERT INTO t3 VALUES ('a', 4),
                            ('b', 5),
                            ('c', 3),
                            ('d', 8),
                            ('e', 1);
    `);
    
    db.aggregate('sumint', {
      start: 0,
      step: (acc, value) => acc + value,
    });
    
    db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
    
    @param name

    The name of the SQLite function to create.

    @param options

    Function configuration settings.

  • changeset: Uint8Array,
    ): boolean;

    An exception is thrown if the database is not open. This method is a wrapper around sqlite3changeset_apply().

    const sourceDb = new DatabaseSync(':memory:');
    const targetDb = new DatabaseSync(':memory:');
    
    sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
    targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
    
    const session = sourceDb.createSession();
    
    const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
    insert.run(1, 'hello');
    insert.run(2, 'world');
    
    const changeset = session.changeset();
    targetDb.applyChangeset(changeset);
    // Now that the changeset has been applied, targetDb contains the same data as sourceDb.
    
    @param changeset

    A binary changeset or patchset.

    @param options

    The configuration options for how the changes will be applied.

    @returns

    Whether the changeset was applied successfully without being aborted.

  • close(): void;

    Closes the database connection. An exception is thrown if the database is not open. This method is a wrapper around sqlite3_close_v2().

  • @param options

    The configuration options for the session.

    @returns

    A session handle.

  • allow: boolean
    ): void;

    Enables or disables the loadExtension SQL function, and the loadExtension() method. When allowExtension is false when constructing, you cannot enable loading extensions for security reasons.

    @param allow

    Whether to allow loading extensions.

  • sql: string
    ): void;

    This method allows one or more SQL statements to be executed without returning any results. This method is useful when executing SQL statements read from a file. This method is a wrapper around sqlite3_exec().

    @param sql

    A SQL string to execute.

  • name: string,
    options: FunctionOptions,
    func: (...args: SQLOutputValue[]) => SQLInputValue
    ): void;
    @param name

    The name of the SQLite function to create.

    @param options

    Optional configuration settings for the function.

    @param func

    The JavaScript function to call when the SQLite function is invoked. The return value of this function should be a valid SQLite data type: see Type conversion between JavaScript and SQLite. The result defaults to NULL if the return value is undefined.

    name: string,
    func: (...args: SQLOutputValue[]) => SQLInputValue
    ): void;
    @param name

    The name of the SQLite function to create.

    @param func

    The JavaScript function to call when the SQLite function is invoked. The return value of this function should be a valid SQLite data type: see Type conversion between JavaScript and SQLite. The result defaults to NULL if the return value is undefined.

  • path: string
    ): void;

    Loads a shared library into the database connection. This method is a wrapper around sqlite3_load_extension(). It is required to enable the allowExtension option when constructing the DatabaseSync instance.

    @param path

    The path to the shared library to load.

  • dbName?: string
    ): null | string;
    @param dbName

    Name of the database. This can be 'main' (the default primary database) or any other database that has been added with ATTACH DATABASE Default: 'main'.

    @returns

    The location of the database file. When using an in-memory database, this method returns null.

  • open(): void;

    Opens the database specified in the path argument of the DatabaseSyncconstructor. This method should only be used when the database is not opened via the constructor. An exception is thrown if the database is already open.

  • sql: string
    @param sql

    A SQL string to compile to a prepared statement.

    @returns

    The prepared statement.

class URL

The URL interface represents an object providing static methods used for creating object URLs.

MDN Reference

interface BackupOptions

  • progress?: (progressInfo: BackupProgressInfo) => void

    Callback function that will be called with the number of pages copied and the total number of pages.

  • rate?: number

    Number of pages to be transmitted in each batch of the backup.

  • 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

  • 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