diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md index 35bbebea16e158..22d1eae3653777 100644 --- a/doc/api/sqlite.md +++ b/doc/api/sqlite.md @@ -531,6 +531,64 @@ Opens the database specified in the `path` argument of the `DatabaseSync` constructor. 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. +### `database.serialize([dbName])` + + + +* `dbName` {string} Name of the database to serialize. This can be `'main'` + (the default primary database) or any other database that has been added with + [`ATTACH DATABASE`][]. **Default:** `'main'`. +* Returns: {Uint8Array} A binary representation of the database. + +Serializes the database into a binary representation, returned as a +`Uint8Array`. This is useful for saving, cloning, or transferring an in-memory +database. This method is a wrapper around [`sqlite3_serialize()`][]. + +```cjs +const { DatabaseSync } = require('node:sqlite'); + +const db = new DatabaseSync(':memory:'); +db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); +db.exec("INSERT INTO t VALUES (1, 'hello')"); +const buffer = db.serialize(); +console.log(buffer.length); // Prints the byte length of the database +``` + +### `database.deserialize(buffer[, options])` + + + +* `buffer` {Uint8Array} A binary representation of a database, such as the + output of [`database.serialize()`][]. +* `options` {Object} Optional configuration for the deserialization. + * `dbName` {string} Name of the database to deserialize into. + **Default:** `'main'`. + +Loads a serialized database into this connection, replacing the current +database. The deserialized database is writable. Existing prepared statements +are finalized before deserialization is attempted, even if the operation +subsequently fails. This method is a wrapper around +[`sqlite3_deserialize()`][]. + +```cjs +const { DatabaseSync } = require('node:sqlite'); + +const original = new DatabaseSync(':memory:'); +original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); +original.exec("INSERT INTO t VALUES (1, 'hello')"); +const buffer = original.serialize(); +original.close(); + +const clone = new DatabaseSync(':memory:'); +clone.deserialize(buffer); +console.log(clone.prepare('SELECT value FROM t').get()); +// Prints: { value: 'hello' } +``` + ### `database.prepare(sql[, options])`