-
-
Notifications
You must be signed in to change notification settings - Fork 2
client.query()
Oxford Harrison edited this page Nov 9, 2024
·
25 revisions
Run an arbitrary query.
client.query(sql: string | StatementInterface, options?: Options): Promise<Savepoint | Array<object>>
Param | Type | Description |
---|---|---|
query |
string | an SQL query. |
options? |
Options | extra parameters for the query. |
-
Savepoint
- when it's a DDL operation (CREATE
,ALTER
,DROP
,RENAME
) -
Array (the result set) - when it's a DQL operation (
SELECT
) or when it's a DML operation (INSERT
,UPDATE
,DELETE
) with aRETURNING
clause -
Number (indicating number of rows processed by the query) - when it's a DML operation without a
RETURNING
clause - Null - in all other cases
Run a DML operation (CREATE
, ALTER
, DROP
, RENAME
) and get back a reference to the savepoint associated with it (See ➞ Automatic-Schema-Versioning):
const savepoint = await client.query(
`ALTER TABLE users
RENAME TO accounts`
);
console.log(savepoint.versionTag()); // number
await savepoint.rollback(); // true
or a DQL operation (SELECT
), and get back a result set:
const rows = await client.query(
`SELECT * FROM users
WHERE id = 4`
);
console.log(rows.length); // 1
or a DML operation (INSERT
, UPDATE
, DELETE
) with a RETURNING
clause, and get back a result set:
const rows = await client.query(
`INSERT INTO users
SET name = 'John Doe'
RETURNING id`
);
console.log(rows.length); // 1
or same DML operation without a RETURNING
clause, and get back a number indicating the number of rows processed by the query:
const rowCount = await client.query(
`INSERT INTO users
SET name = 'John Doe'`
);
console.log(rowCount); // 1
Param | Type | Applicable to | Description |
---|---|---|---|
desc |
string | DDL operations (CREATE , ALTER , DROP , RENAME ) |
the commit description. |
noCreateSavepoint |
string | DDL operations (CREATE , ALTER , DROP , RENAME ) |
a disable savepoint creation. |
values |
Array | Non-DDL operations | values for parameters in the query |
inspect |
Boolean | All | Log details of the query to the console. |
// Parameterize a query
const rows = await client.query(
`SELECT * FROM users
WHERE id = $1`,
{ values: [4] }
);
// Log Parser-level details to the console
const rows = await client.query(
`ALTER TABLE users
MODIFY COLUMN id int`,
{ inspect: true }
);