---
title: QueryBuilder
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/querybuilder/
updated: 2026-11-19T20:13:41.295Z
---

# QueryBuilder

> DATA, DB(), NEWDB() and every method of the SQL QueryBuilder.

The SQL QueryBuilder describes a query with chained methods and passes it to the adapter registered with `NEWDB()`. The guide [QueryBuilder](../../guides/querybuilder/) explains how to use it with examples; this page is the exact reference.

## API

### NEWDB([name], [fn])

Type: `method`

Registers or removes the adapter of an SQL connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | The connection name. |
| `fn` | `Function` | no |  | `function(filter, callback)`, see the adapter function. Leave it out to remove the adapter. |

Returns: `undefined`

Registers `fn` as the adapter for the connection `name` (default `default`). The name `*` is a fallback used for every connection without its own adapter. Calling `NEWDB(name)` without a function removes the adapter. When a query runs and no adapter exists, it fails with the error `Database is not initialized`.

The adapter is called with `this` set to the internal query object and receives the adapter options (see *Adapter options*) and a callback.

Example: A default and a named adapter
```js
NEWDB(function(filter, callback) {
	pgadapter(CONF.database, filter, callback);
});

NEWDB('analytics', function(filter, callback) {
	pgadapter(CONF.database_analytics, filter, callback);
});

// Remove
NEWDB('analytics');
```

### function(filter, callback)

Type: `delegate`

The function that runs a query against the database.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filter` | `Object` | yes |  | The description of the query. |
| `callback` | `Function` | yes |  | `function(err, response)`. |

Returns: `undefined`

You write the adapter and register it with `NEWDB()`. It reads `filter` (see *Adapter options*), builds and runs the SQL, and calls `callback(err, response)` exactly once.

What `response` must contain depends on `filter.exec`: an array for `find`, a row or an array for `read` and `check`, `{ items, count }` for `list`, a number for `count`, and what you consider useful for the rest. An `err` stops a `DB()` chain and goes to the callbacks of the query.

Example: Skeleton of an adapter
```js
NEWDB(function(filter, callback) {
	var sql;
	switch (filter.exec) {
		case 'query':
			client.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));
			return;
		case 'find':
		case 'read':
		case 'check':
			sql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);
			if (filter.sort)
				sql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');
			if (filter.take)
				sql += ' LIMIT ' + filter.take;
			if (filter.skip)
				sql += ' OFFSET ' + filter.skip;
			break;
		// ... count, list, insert, update, remove
	}
	client.query(sql, (err, res) => callback(err, res && res.rows));
});
```

### filter {Object}

Type: `type`

The description of a query that the adapter receives.

Returns: `Object`

| Field | Type | Meaning |
| --- | --- | --- |
| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` or `drop` |
| `table` | String | The table name, without the connection prefix (empty for `query`) |
| `filter` | Array | The conditions in their order (see below) |
| `fields` | Array | The column names from `fields()`, or empty for all |
| `sort` | Array | Items in the form `name_asc` or `name_desc` |
| `take`, `skip` | Number | Limit and offset. `list` starts with `take: 100, skip: 0` |
| `first` | Boolean | `true` for `read`, `check` and `first()`: one row is expected |
| `payload` | Object | The data of `insert` and `update` |
| `upsert` | Boolean | `true` for an update with upsert |
| `returning` | Array | The columns from `returning()` |
| `query`, `params` | String, Array/Object | The SQL and the arguments of `query()` |
| `scalar` | Object | `{ type, key, key2 }` from `scalar()` |
| `command` | String | The name from `command()` |
| `language` | String | The value from `language()` |
| `primarykey` | String | The value from `builder.primarykey(name)` |
| `schema` | String | The value from `builder.schema(name)` |
| `checksum` | String | A hash of the shape of the filters (without the values), useful as a cache key of prepared statements |
| `debug` | Boolean | `true` after `debug()` |

The items of `filter.filter` have a `type`: `where` (`name`, `comparer`, `value`), `in` and `notin` (`name`, `value` array), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` and `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: an array of items), `query` (`value`: raw SQL), `join` (`name`, `table`, `join`, `on`) and `permit` (`name`, `value`, `userid`, `required`).

### DB()

Type: `method`

Creates a controller that runs several queries one after another.

Returns: `QueryBuilderDB` The controller.

Returns a new controller (alias `DATABASE()`). Each method you call on it adds a query to a queue. The queue starts on the next tick and runs the queries in order. After the last one, the callback of the controller (`callback()`, `promise()` or `done()`) receives the error or the response. An error stops the queue.

By default each query replaces the response; use `builder.set(name)` to collect several responses, and `builder.nobind()` to keep a query out of the response. A query added from a callback of a previous query is run too.

Example: Two queries in a row
```js
var db = DB();
db.insert('tbl_user', model);
db.insert('tbl_user_role', { userid: model.id, role: 'user' });
db.callback(function(err) {
	$.success();
});
```

### DATA

Type: `property`

A global controller for single queries.

Returns: `QueryBuilderDB`

`DATA` has the same query methods as `DB()` (`find`, `read`, `insert`...), but each query runs on its own as soon as it is created, without a queue. It is faster than `DB()` because no controller is created.

Read the result with the methods of the builder: `callback()`, `promise()`, `done()`, `data()` or `fail()`. Do not use `set()` with `DATA`, and do not use the controller methods `DATA.callback()`, `DATA.promise()` and `DATA.done()`: `DATA` is shared by the whole app.

Example: A single query
```js
var user = await DATA.read('tbl_user').id(id).promise();
```

### db.find(table)

Type: `method`

Finds rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `find` query (alias `all()`). The response is an array of rows.

Example: Find
```js
DATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);
```

### db.list(table)

Type: `method`

Finds one page of rows with counts.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `list` query with `take: 100` and `skip: 0`. The adapter returns `{ items, count }`, where `count` is the number of all matching rows. The framework adds `page`, `limit` and `pages` (the number of pages).

Example: A page
```js
DATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {
	// response.items, response.count, response.page, response.pages, response.limit
});
```

### db.read(table)

Type: `method`

Reads one row.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `read` query (alias `one()`) with `take: 1`. When the adapter returns an array, the response is its first item or `null`. Combine it with `error('404')`.

Example: Read
```js
DATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);
```

### db.check(table)

Type: `method`

Checks whether a row exists.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `check` query with `take: 1`. The adapter usually selects only one column. Use it with `error()` to stop on a missing row, or `error(err, true)` to stop on an existing one.

Example: Unique e-mail
```js
DATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);
```

### db.scalar(table, type, [key], [key2])

Type: `method`

Runs an aggregation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |
| `type` | `String` | yes |  | The kind of aggregation. |
| `key` | `String` | no | `'*'` | The column. |
| `key2` | `String` | no |  | A second column, for example for grouping. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `scalar` query. The adapter receives `filter.scalar = { type, key, key2 }`. The meaning of `type` (for example `sum`, `min`, `max`, `avg`, `group`) depends on the adapter.

`db.count(table)` starts a `count` query; the response is the number the adapter returns.

Example: Sum
```js
DATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);
```

Example: Count
```js
DATA.count('tbl_order').where('status', 'new').callback(console.log);
```

### db.insert(table, data)

Type: `method`

Inserts a row.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |
| `data` | `Object` | yes |  | The row. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts an `insert` query (alias `ins()`). `data` goes to the adapter as `filter.payload`.

Example: Insert
```js
DATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());
```

### db.update(table, data, [upsert])

Type: `method`

Updates rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |
| `data` | `Object` | yes |  | The changed columns. |
| `upsert` | `Boolean` | no | `false` | Insert the data when nothing was updated. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts an `update` query (aliases `modify()`, `mod()`, `upd()`). `data` goes to the adapter as `filter.payload`. With `upsert`, when the adapter returns an empty response (or nothing from `returning`), the framework calls the function of `builder.insert()`, clears the filters and runs the data as an `insert`.

Example: Update
```js
DATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());
```

### db.remove(table)

Type: `method`

Removes rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `remove` query (alias `rem()`).

Example: Remove
```js
DATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());
```

### db.query([conn], sql, [params])

Type: `method`

Runs your own SQL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `conn` | `String` | no | `'default'` | The connection name. |
| `sql` | `String` | yes |  | The SQL. |
| `params` | `Array|Object` | no |  | The arguments for the placeholders of your driver. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Sends `sql` as `filter.query` and `params` as `filter.params` to the adapter of `conn`. When the second argument is an array or an object, it is taken as `params` and the connection is `default`. Filters added to the builder (for example `where()`) are passed in `filter.filter` as well.

`db.command(table, name)` sends `exec: 'command'` with `filter.command = name`, for operations of your adapter that the other methods do not cover.

Example: Raw SQL
```js
DATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);
DATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);
```

Example: Command
```js
DATA.command('tbl_product', 'reindex').callback(console.log);
```

### db.truncate(table)

Type: `method`

Removes all rows of a table.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Starts a `truncate` query (alias `clear()`). `db.drop(table)` starts a `drop` query in the same way, to remove the table itself.

Example: Truncate
```js
DATA.truncate('tbl_log').callback(console.log);
```

### db.load([conn], options)

Type: `method`

Creates a query from a prepared object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `conn` | `String` | no | `'default'` | The connection name. |
| `options` | `Object` | yes |  | The prepared query. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Creates a builder from the fields of `options`: `table`, `exec`, `fields` (array), `sort` (array), `skip`, `take`, `query`, `payload`, `upsert`, `returning` and `filter` (an array of filter items). Unlike the other methods, `table` has no connection prefix; pass the connection as `conn`. Put all conditions into `options.filter`.

`db.exec(options, callback)` runs a prepared object at once: it starts the query named by `options.exec` on `options.table` (for `exec: 'query'`, `options.query` holds the SQL), copies the other fields to the adapter options and calls `callback(err, response)`. It returns nothing.

Example: Load
```js
DATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);
```

Example: Exec
```js
DATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);
```

### db.callback(fn)

Type: `method`

Sets the final callback of a DB() controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | yes |  | `function(err, response)` or `$`. |

Returns: `QueryBuilderDB`

Called after the last query, or after the first error, with `(err, response)`. Accepts `$` too, then it uses `$.callback`. Use it only on `DB()`.

Two other ways to end a `DB()` controller: `db.promise([$])` returns a promise of the final response (with `$`, an error goes to `$.invalid()` and the promise stays pending; without it, the promise is rejected), and `db.done($, [fn])` sends an error to `$.invalid(err)` and otherwise calls `fn(response)`.

Example: Callback
```js
var db = DB();
db.read('tbl_user').id(id).set('user');
db.find('tbl_role').where('userid', id).set('roles');
db.callback($);
```

Example: Await
```js
var db = DB();
db.remove('tbl_user_role').where('userid', $.id);
db.remove('tbl_user').id($.id);
await db.promise($);
$.success();
```

### db.done($, [fn])

Type: `method`

Calls fn on success, $.invalid() on an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The options of a schema or an operation. |
| `fn` | `Function` | no |  | `function(response)`. |

Returns: `QueryBuilderDB`

Sets the final callback of a `DB()` controller: an error goes to `$.invalid(err)`, otherwise `fn(response)` is called.

Example: Done
```js
var db = DB();
db.update('tbl_user', { isremoved: true }).id($.id);
db.done($, () => $.success());
```

### db.debug()

Type: `method`

Turns on debug mode for the next queries.

Returns: `QueryBuilderDB`

Sets `filter.debug = true` for queries created on this controller after the call, so the adapter can print the SQL. On one query, use `builder.debug()` instead.

`builder.debug()` sets the flag on one query only.

Example: Debug
```js
var db = DB().debug();
db.find('tbl_user').take(1);
```

Example: Debug
```js
DATA.find('tbl_user').where('email', email).debug().callback(console.log);
```

### db.language(prefix, skip)

Type: `method`

Sets the default prefix and skip value of builder.language().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prefix` | `String` | yes |  | Text put before the language. |
| `skip` | `String` | yes |  | A language that produces an empty value (the default language). |

Returns: `QueryBuilderDB`

The values are global: they apply to every later `builder.language()` call in the app, whether on `DB()` or `DATA`. The defaults are `prefix: ''` and `skip: '_'`.

Example: Defaults
```js
// definitions/db.js
DATA.language('_', 'en');
// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''
```

### builder.where(name, [comparer], value)

Type: `method`

Adds a condition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` or `<=`. |
| `value` | `Object` | yes |  | The value. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'where', name, comparer, value }`. Without a comparer it is `=`. `==` becomes `=` and `!=` becomes `<>`. Called with one argument, it adds a raw condition like `builder.query()`.

Example: Where
```js
DATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);
```

### builder.id(id)

Type: `method`

Filters by the id column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `Object|Array` | yes |  | One value or an array. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Shortcut for `where('id', id)`, or `in('id', id)` when `id` is an array. `builder.userid(id)` does the same for the `userid` column, and `builder.equal(obj)` adds `where(key, value)` for each key of an object.

Example: Id
```js
DATA.read('tbl_user').id($.id).callback($.callback);
DATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);
```

### builder.in(name, value, [key])

Type: `method`

The column is one of the values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `value` | `Array|Object` | yes |  | The values. |
| `key` | `String` | no |  | Take this property from each object of `value`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'in', name, value }`. A single value becomes an array. With `key`, `value` is an array of objects and their `key` property is used.

`builder.notin(name, value, [key])` is the opposite, with the same arguments.

Example: In
```js
DATA.find('tbl_product').in('id', items, 'productid').callback(console.log);
```

Example: Not in
```js
DATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);
```

### builder.between(name, a, b)

Type: `method`

The column is between two values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `a` | `Object` | yes |  | The lower value. |
| `b` | `Object` | yes |  | The upper value. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'between', name, a, b }`.

Example: Between
```js
DATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);
```

### builder.array(name, [comparer], value)

Type: `method`

A condition on an array column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `comparer` | `String` | no | `'&&'` | The operator for the adapter. |
| `value` | `Array` | yes |  | The values. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'array', name, comparer, value }` for columns that hold arrays (for example `text[]` in PostgreSQL). The default comparer is `&&` (overlap).

Example: Tags
```js
DATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);
```

### builder.or(fn)

Type: `method`

Groups conditions joined with OR.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Calls `fn(builder)`; conditions added inside go to one `{ type: 'or', value: [...] }` item.

Example: Or
```js
DATA.find('tbl_user').or(function(builder) {
	builder.where('email', login);
	builder.where('phone', login);
}).callback(console.log);
```

### builder.search(name, value, [where])

Type: `method`

A text search (LIKE).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `value` | `String` | yes |  | The text. |
| `where` | `String` | no |  | The position hint for the adapter. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'search', name, value, comparer: where }`. `where` is a hint for the adapter where the text may be (for example at the beginning or the end); without it, anywhere.

Example: Search
```js
DATA.find('tbl_product').search('name', $.query.q).callback($.callback);
```

### builder.contains(name)

Type: `method`

The column has a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'contains', name }`; the adapter writes a test for a non-empty value. `builder.empty(name)` adds the opposite test `{ type: 'empty', name }`.

Example: Contains
```js
DATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);
```

### builder.year(name, [comparer], value)

Type: `method`

Compares a part of a date.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The date column. |
| `comparer` | `String` | no | `'='` | The operator. |
| `value` | `Number` | yes |  | The year (or month, day, hour, minute). |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` and `minute()` work the same way. The default comparer is `=`.

Example: Dates
```js
DATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);
```

### builder.query(sql)

Type: `method`

Adds a raw SQL condition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sql` | `String` | yes |  | The condition. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'query', value: sql }`. The adapter puts the text into the WHERE clause as it is, so never put input of users into it.

Example: Raw condition
```js
DATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \'1 day\'').callback(console.log);
```

### builder.join(name, table, [jointype], a, b)

Type: `method`

Adds a join.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the joined data. |
| `table` | `String` | yes |  | The joined table. |
| `jointype` | `String` | no |  | For example `left` or `inner`. |
| `a` | `String` | yes |  | The column of the main table. |
| `b` | `String` | yes |  | The column of the joined table. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `{ type: 'join', name, table, join: jointype, on: [a, b] }`. How the adapter builds the join and where it puts the joined data depends on the adapter.

Example: Join
```js
DATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);
```

### builder.permit(name, type, value, [userid], [required])

Type: `method`

Filters by a permissions column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `type` | `String` | yes |  | Letters such as `R`, `W`, `D`. |
| `value` | `Array` | yes |  | Roles or ids. |
| `userid` | `String` | no |  | A user id that the adapter may also accept. |
| `required` | `Boolean` | no | `true` | Whether the permission is required. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds a `permit` filter for a column that holds permissions as `<type><value>` strings. `type` is one or more letters (`R` read, `W` write, `D` delete); each letter is joined with each item of `value`, so `permit('permissions', 'RW', ['admin'])` gives `['Radmin', 'Wadmin']`. `userid` and `required` (default `true`) are passed to the adapter.

Example: Permit
```js
DATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);
```

### builder.fields(fields)

Type: `method`

Selects the columns.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | yes |  | For example `'id,name,email'`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

A comma-separated list of columns. It goes to the adapter as an array in `filter.fields`.

Example: Fields
```js
DATA.find('tbl_user').fields('id,name,email').callback(console.log);
```

### builder.sort(name, [desc])

Type: `method`

Adds a sort.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `desc` | `Boolean|String` | no | `false` | Descending order. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Adds `name_asc`, or `name_desc` when `desc` is `true` or `'desc'`. Call it more times for more columns.

`builder.gridsort(sort, [localized])` adds sorts from a string such as `'name_asc,price_desc'` (an item without `_asc`/`_desc` is ascending); `localized` maps a field name to another column name.

Example: Sort
```js
DATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);
```

Example: Grid sort
```js
DATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);
```

### builder.take(count)

Type: `method`

Limits the number of rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The maximum number of rows. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Sets `filter.take` (alias `limit()`). `builder.first()` sets `take: 1` and makes the response one row or `null` instead of an array.

Example: Take
```js
DATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);
DATA.find('tbl_article').where('slug', slug).first().callback(console.log);
```

### builder.page(page, [limit])

Type: `method`

Sets the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `Number` | yes |  | The page, from 1. |
| `limit` | `Number` | no |  | Rows per page. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Sets `skip` to `(page - 1) * take`. With `limit`, it sets `take` first. `page` starts at 1.

`builder.skip(count)` sets `filter.skip` (the offset) directly.

Example: Page
```js
DATA.list('tbl_product').page(2, 20).callback(console.log);
```

Example: Skip
```js
DATA.find('tbl_article').skip(20).take(10).callback(console.log);
```

### builder.paginate(page, limit, [maxlimit])

Type: `method`

Sets the page from user input.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `String|Number` | yes |  | The page, from 1. |
| `limit` | `String|Number` | yes |  | Rows per page. |
| `maxlimit` | `Number` | no |  | The largest and the default limit. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Like `page()`, but accepts strings from a query string, uses page 1 for missing or wrong values, caps `limit` at `maxlimit` and uses `maxlimit` when `limit` is missing.

Example: Paginate
```js
DATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);
```

### builder.gridfilter(name, obj, [type], [key])

Type: `method`

Adds a filter from a text value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The key in `obj`. |
| `obj` | `Object` | yes |  | Usually the query string. |
| `type` | `Function|String` | no | `String` | The type of the column. |
| `key` | `String` | no |  | The column, when it differs from `name`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Reads `obj[name]` and, when it is a non-empty string, adds a filter for the column `key` (default `name`). `type` is `String` (default), `Number`, `Date`, `Boolean` or a string: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (an `array()` filter) or `json` (a `search()`).

- `a - b` is `between()`.
- `a,b,c` is `in()`; for strings it is an `or()` of searches.
- For strings, `!text` is an exact match and other text is `search()`.
- For numbers and dates, a leading `>` or `<` compares.
- Dates accept `today`, `yesterday`, a full date, `MM-DD` of this year, a year (more than 1000) or a month number, and a relative value with a space such as `7 days` (that day in the past). A single day matches from 00:00:00 to 23:59:59.

Example: Grid filter
```js
// ?price=10 - 50&dtcreated=today&name=phone
DATA.list('tbl_product')
	.gridfilter('name', $.query)
	.gridfilter('price', $.query, Number)
	.gridfilter('dtcreated', $.query, Date)
	.paginate($.query.page, $.query.limit, 50)
	.callback($.callback);
```

### builder.autoquery(query, fields, [sort], [maxlimit])

Type: `method`

Builds fields, filters, sort and paging from the query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `query` | `Object` | yes |  | The query string, usually `$.query`. |
| `fields` | `String` | yes |  | The allowed columns and types. |
| `sort` | `String` | no |  | The default sort, for example `'dtcreated_desc'`. |
| `maxlimit` | `Number` | no |  | The maximum rows per page. |

Returns: `QueryBuilder` The builder of the query, for chaining.

`fields` lists the allowed columns with their types, `'id,name,price:number,dtcreated:date'` (the default type is `string`). Then:

- `query.fields` chooses columns from the allowed ones; otherwise all allowed columns are selected.
- Each allowed column present in `query` gets a `gridfilter()` with its type.
- `query.sort` (for example `price_desc`) is used for allowed columns; otherwise `sort` is the default.
- With `maxlimit`, `paginate(query.page, query.limit, maxlimit)` is called. Without it, no paging is set.

A column name with `§` is localized: `§` stays in the column name sent to the adapter and is removed in the name used in the query string.

Example: Autoquery
```js
schema.setQuery(function($) {
	DATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);
});
```

### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])

Type: `method`

Builds a grid query from the schema of $.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The options of a schema operation. |
| `allowedfields` | `String` | no |  | Extra columns, with optional types. |
| `skipfields` | `String` | no |  | Columns of the schema to leave out. |
| `sort` | `String` | no |  | The default sort. |
| `maxlimit` | `Number` | no | `50` | The maximum rows per page. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Works like `autoquery()`, but the columns and their types come from the schema of the current operation (`$.schema`). It reads `$.query` (or `$.options`). `allowedfields` adds columns that are not in the schema (`'name:type,...'`), `skipfields` hides columns of the schema. Paging is always set, with `maxlimit` 50 by default. When the fourth argument is a number, it is `maxlimit`.

Example: Autofill
```js
NEWSCHEMA('Products', function(schema) {
	schema.define('id', 'UID');
	schema.define('name', String);
	schema.define('price', Number);
	schema.setQuery(function($) {
		DATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);
	});
});
```

### builder.language(value, [prefix], [skip])

Type: `method`

Passes a language to the adapter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes |  | The language, or an object with `language`. |
| `prefix` | `String` | no |  | Text before the language. |
| `skip` | `String` | no |  | The language that gives an empty value. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Sets `filter.language` to `prefix + value`. `value` may be `$` or a controller; then its `language` is used. When `value` equals `skip` (by default `_`, see `db.language()`), the language is empty. The adapter uses it, for example, to replace `§` in column names.

Example: Language
```js
DATA.find('tbl_product').fields('id,name§').language($).callback($.callback);
```

### builder.returning(fields)

Type: `method`

Asks for columns of changed rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | yes |  | For example `'id,dtcreated'`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Sets `filter.returning` to an array from a comma-separated list. The adapter returns these columns after `insert`, `update` or `remove`. With upsert, an empty returned result means "not updated".

Example: Returning
```js
DATA.insert('tbl_user', model).returning('id').first().callback(console.log);
```

### builder.insert(fn, [param])

Type: `method`

Prepares the data of an upsert.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(data, param)`. |
| `param` | `Object` | no |  | A value passed to `fn`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

With `update(table, data, true)`, when nothing was updated, `fn(data, param)` is called before the data are inserted. Use it to add columns that only a new row has.

Example: Upsert
```js
DATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {
	data.id = key;
	data.dtcreated = NOW;
}).callback(console.log);
```

### builder.error(err, [reverse])

Type: `method`

Makes an empty result an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `String` | yes |  | The error. |
| `reverse` | `Boolean` | no | `false` | Fail when a row exists. |

Returns: `QueryBuilder` The builder of the query, for chaining.

When the response is empty (no row, `null`, `0` or an empty array), the query fails with `err` (as a string, for example an error key of a resource or `'404'`). With `reverse`, the query fails when the response is **not** empty. Alias `err()`.

Example: 404
```js
DATA.read('tbl_user').id($.id).error('404').callback($.callback);
```

### builder.set(name)

Type: `method`

Stores the response under a key of a DB() response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The key. |

Returns: `QueryBuilder` The builder of the query, for chaining.

On a `DB()` controller, the response of this query goes to `response[name]` instead of replacing the whole response. `builder.nobind()` keeps the response out of the controller response completely. Not for `DATA`.

Example: Set
```js
var db = DB();
db.read('tbl_user').id(id).set('user');
db.count('tbl_order').where('userid', id).set('orders');
db.find('tbl_log').where('userid', id).nobind().data(console.log);
db.callback(console.log); // { user: {...}, orders: 3 }
```

### builder.data(fn)

Type: `method`

Calls fn with the response on success.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(response)`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Called only when the query succeeds, before `callback()`. In a `DB()` chain you can add more queries from here.

`builder.fail(fn)` is the counterpart: `fn(err)` is called only when the query fails.

Example: Data
```js
var db = DB();
db.read('tbl_user').id(id).error('404').data(function(user) {
	db.find('tbl_order').where('userid', user.id).set('orders');
});
db.callback($.callback);
```

Example: Fail
```js
DATA.insert('tbl_log', item).fail(err => console.error('log', err));
```

### builder.callback(fn)

Type: `method`

Calls fn with the result of this query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | yes |  | `function(err, response)` or `$`. |

Returns: `QueryBuilder` The builder of the query, for chaining.

Called with `(err, response)`. Accepts `$` too, then it uses `$.callback`, so an error becomes the error of the operation.

`builder.done($, fn, [param])` sends an error to `$.invalid(err)` and otherwise calls `fn(response, param)`.

Example: Callback
```js
DATA.find('tbl_user').take(10).callback(function(err, response) {
	console.log(err, response);
});
DATA.find('tbl_user').take(10).callback($);
```

Example: Done
```js
DATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());
```

### builder.promise([$])

Type: `method`

Returns a promise of this query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | The options of a schema or an operation. |

Returns: `Promise`

Resolves with the response. With `$`, an error goes to `$.invalid()` and the promise stays pending, so the rest of the function does not run. Without `$`, the promise is rejected; the error gets the name `QueryBuilder(table --> exec)`.

Example: Await
```js
schema.setRead(async function($) {
	var user = await DATA.read('tbl_user').id($.id).error('404').promise($);
	user.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);
	$.callback(user);
});
```

### builder.audit($, [message], [type])

Type: `method`

Writes an audit record after success.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The options of a schema or an operation. |
| `message` | `String` | no |  | The text. |
| `type` | `String` | no |  | The type of the record. |

Returns: `QueryBuilder` The builder of the query, for chaining.

When the query succeeds, calls `$.audit(message, type)`. `message` may contain dynamic arguments (`{user.name}`, `{model.key}`, `{data.key}`...); `data` is the payload of the query.

Example: Audit
```js
DATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());
```

### QueryBuilder

Type: `class`

The global class of the SQL query builder.

Every method of `DB()` and `DATA` that starts a query returns an instance. Its prototype `QueryBuilder.prototype` is global, so you can add your own methods. The controller class is the global `QueryBuilderDB`.

Example: Own method
```js
QueryBuilder.prototype.active = function() {
	return this.where('isremoved', false).where('isdisabled', false);
};

DATA.find('tbl_user').active().callback(console.log);
```
