TinyJoin logoTinyJoin

query

Essential

The query method executes exactly one parameterized SQL statement.

query<RowType>(
  sql: string,
  params?: JsonValue[],
  options?: QueryOptions,
): Promise<Results<RowType>>
TypeDescription
sqlstring

A statement in the documented TinyJoin SQL subset.

params?JsonValue[]

JSON-compatible values for $1, $2, and so on.

options?QueryOptions

Result-shape options.

returnsPromise<Results<RowType>>

A Promise resolving to the statement results.

Examples

import {create} from 'tinyjoin';

const db = await create();
await db.query(
  'CREATE TABLE tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL)',
);
const inserted = await db.query(
  'INSERT INTO tasks (id, title) VALUES ($1, $2)',
  ['a', 'Write docs'],
);
console.log(inserted.affectedRows);
// -> 1

const {rows} = await db.query<{id: string; title: string}>(
  'SELECT * FROM tasks WHERE id = $1',
  ['a'],
);
console.log(rows);
// -> [{id: 'a', title: 'Write docs'}]
await db.close();
import {create} from 'tinyjoin';

const db = await create();
await db.exec(`
  CREATE TABLE tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL);
  INSERT INTO tasks (id, title) VALUES ('a', 'Write docs');
`);
// Rows come back as arrays, in the order of the fields, on request.
const {fields, rows} = await db.query('SELECT id, title FROM tasks', [], {
  rowMode: 'array',
});
console.log(fields.map(({name}) => name));
// -> ['id', 'title']
console.log(rows);
// -> [['a', 'Write docs']]
await db.close();