doc: add CJS code snippets in `sqlite.md` · nodejs/node@2127754

@@ -504,6 +504,33 @@ console.log(allUsers);

504504

// ]

505505

```

506506507+

```cjs

508+

const { DatabaseSync } = require('node:sqlite');

509+510+

const db = new DatabaseSync(':memory:');

511+

const sql = db.createTagStore();

512+513+

db.exec('CREATE TABLE users (id INT, name TEXT)');

514+515+

// Using the 'run' method to insert data.

516+

// The tagged literal is used to identify the prepared statement.

517+

sql.run`INSERT INTO users VALUES (1, 'Alice')`;

518+

sql.run`INSERT INTO users VALUES (2, 'Bob')`;

519+520+

// Using the 'get' method to retrieve a single row.

521+

const id = 1;

522+

const user = sql.get`SELECT * FROM users WHERE id = ${id}`;

523+

console.log(user); // { id: 1, name: 'Alice' }

524+525+

// Using the 'all' method to retrieve all rows.

526+

const allUsers = sql.all`SELECT * FROM users ORDER BY id`;

527+

console.log(allUsers);

528+

// [

529+

// { id: 1, name: 'Alice' },

530+

// { id: 2, name: 'Bob' }

531+

// ]

532+

```

533+507534

### `database.createSession([options])`

508535509536

<!-- YAML

@@ -557,7 +584,29 @@ added:

557584

An exception is thrown if the database is not

558585

open. This method is a wrapper around [`sqlite3changeset_apply()`][].

559586560-

```js

587+

```mjs

588+

import { DatabaseSync } from 'node:sqlite';

589+590+

const sourceDb = new DatabaseSync(':memory:');

591+

const targetDb = new DatabaseSync(':memory:');

592+593+

sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');

594+

targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');

595+596+

const session = sourceDb.createSession();

597+598+

const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');

599+

insert.run(1, 'hello');

600+

insert.run(2, 'world');

601+602+

const changeset = session.changeset();

603+

targetDb.applyChangeset(changeset);

604+

// Now that the changeset has been applied, targetDb contains the same data as sourceDb.

605+

```

606+607+

```cjs

608+

const { DatabaseSync } = require('node:sqlite');

609+561610

const sourceDb = new DatabaseSync(':memory:');

562611

const targetDb = new DatabaseSync(':memory:');

563612