doc: add CJS code snippets in sqlite.md

Refs: https://github.com/nodejs/node/issues/60394
PR-URL: https://github.com/nodejs/node/pull/60395
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
Allon Murienik
2025-11-08 17:01:50 +02:00
committed by GitHub
parent 887e3eca98
commit b8e51e4cef

View File

@@ -504,6 +504,33 @@ console.log(allUsers);
// ]
```
```cjs
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
const sql = db.createTagStore();
db.exec('CREATE TABLE users (id INT, name TEXT)');
// Using the 'run' method to insert data.
// The tagged literal is used to identify the prepared statement.
sql.run`INSERT INTO users VALUES (1, 'Alice')`;
sql.run`INSERT INTO users VALUES (2, 'Bob')`;
// Using the 'get' method to retrieve a single row.
const id = 1;
const user = sql.get`SELECT * FROM users WHERE id = ${id}`;
console.log(user); // { id: 1, name: 'Alice' }
// Using the 'all' method to retrieve all rows.
const allUsers = sql.all`SELECT * FROM users ORDER BY id`;
console.log(allUsers);
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' }
// ]
```
### `database.createSession([options])`
<!-- YAML
@@ -557,7 +584,29 @@ added:
An exception is thrown if the database is not
open. This method is a wrapper around [`sqlite3changeset_apply()`][].
```js
```mjs
import { DatabaseSync } from 'node:sqlite';
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.
```
```cjs
const { DatabaseSync } = require('node:sqlite');
const sourceDb = new DatabaseSync(':memory:');
const targetDb = new DatabaseSync(':memory:');