Query
Query is the abstract base class shared by every statement type —
Select, Insert (via ReturningQuery),
Update (via ReturningQuery), Delete, and Union.
It supplies .generate(), .values(), .comment(), and — because it also mixes in Node's
EventEmitter — per-query event hooks such as the 'serialize' hook used to intercept
serialization (see Generating SQL per dialect).
Query cannot be instantiated directly; calling Query() or new Query() throws a TypeError
("Query is abstract and cannot be instantiated"). You always work with one of its concrete
subclasses.
Properties
| Key | Type | Readonly | Description |
|---|---|---|---|
_comment | Query.Comment[] | No | Comment entries added via .comment(). |
_params | Record<string, any> | undefined | No | Bind-parameter values set via .values(), merged into generate()'s params option. |
Query also inherits every EventEmitter property/method (.on(), .once(), .emit(), ...).
Methods
generate()
generate(options?: GenerateOptions): GenerateResult
Serializes the query to SQL text. See
GenerateOptions and
GenerateResult, and the
Generating SQL per dialect guide
for the full option/result reference.
import '@sqb/postgres-dialect';
import { Select } from '@sqb/builder';
const { sql, params } = Select('id').from('customers').generate({ dialect: 'postgres' });
values()
values(obj: Record<string, any>): this
Merges obj into the query's bind-parameter values, equivalent to passing the same object as
generate({ params: obj }). Throws a TypeError ("Invalid argument") if obj is not a plain
object (e.g. an array).
import { Insert, Param } from '@sqb/builder';
Insert('customers', { id: Param('id'), name: Param('name') })
.values({ id: 1, name: 'Abc' })
.generate().sql;
// insert into customers (id, name) values (:id, :name)
comment()
comment(text: string, dialect?: string[]): this;
comment(args: Query.Comment): this;
Attaches an SQL comment block, rendered as /*...*/ above the generated statement. Multi-line
comments are re-indented automatically. When dialect is given, the comment is only emitted when
generate()'s dialect option matches one of the listed names.
import '@sqb/postgres-dialect';
import { Select } from '@sqb/builder';
Select().from('customers').comment('Only active rows').generate().sql;
// /*Only active rows*/
// select * from customers
Select().from('customers').comment('Postgres only', ['postgres']);