diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md index a5c5fd6cec2b0d..d684bbe12ccbb7 100644 --- a/doc/api/sqlite.md +++ b/doc/api/sqlite.md @@ -1281,6 +1281,66 @@ const totalPagesTransferred = await backup(sourceDb, 'backup.db', { console.log('Backup completed', totalPagesTransferred); ``` +## Diagnostics channel + + + +The `node:sqlite` module publishes SQL trace events on the +[`diagnostics_channel`][] channel `sqlite.db.query`. This allows subscribers +to observe every SQL statement executed against any `DatabaseSync` instance +without modifying the database code itself. Tracing is zero-cost when there +are no subscribers. + +### Channel `sqlite.db.query` + +The message published to this channel is a {string} containing the expanded +SQL with bound parameter values substituted. If expansion fails, the source +SQL with unsubstituted placeholders is used instead. + +```cjs +const dc = require('node:diagnostics_channel'); +const { DatabaseSync } = require('node:sqlite'); + +function onQuery(sql) { + console.log(sql); +} + +dc.subscribe('sqlite.db.query', onQuery); + +const db = new DatabaseSync(':memory:'); +db.exec('CREATE TABLE t (x INTEGER)'); +// Logs: CREATE TABLE t (x INTEGER) + +const stmt = db.prepare('INSERT INTO t VALUES (?)'); +stmt.run(42); +// Logs: INSERT INTO t VALUES (42.0) + +dc.unsubscribe('sqlite.db.query', onQuery); +``` + +```mjs +import dc from 'node:diagnostics_channel'; +import { DatabaseSync } from 'node:sqlite'; + +function onQuery(sql) { + console.log(sql); +} + +dc.subscribe('sqlite.db.query', onQuery); + +const db = new DatabaseSync(':memory:'); +db.exec('CREATE TABLE t (x INTEGER)'); +// Logs: CREATE TABLE t (x INTEGER) + +const stmt = db.prepare('INSERT INTO t VALUES (?)'); +stmt.run(42); +// Logs: INSERT INTO t VALUES (42.0) + +dc.unsubscribe('sqlite.db.query', onQuery); +``` + ## `sqlite.constants`