QueryBuilder
DATA, DB(), NEWDB() and the methods of the QueryBuilder.
On this page
The global DATA, the DB() chain and the adapters registered with NEWDB(), together with every method of the QueryBuilder that they return. An introduction with examples is in the guide QueryBuilder.
API
property
DATA
The global database object that starts each query immediately.
DATAReturns Database
A shared instance of the database controller. Every operation on it (find(), insert()…) creates a QueryBuilder and executes it on the next tick, independently of other queries. Use DB() when you need several queries in a sequence with one result.
DATA.find('users').where('isremoved', false).callback(function(err, response) {
console.log(response);
});
method
DB()
Creates a database object that runs queries in sequence.
DB()Returns Database A new database controller.
Each operation you call on the returned object is queued and executed in order after the current tick. The final response is the result of the last query, or an object filled by set(name) of each query. The first error stops the chain and is passed to callback(). If you add a query after the chain finished, the chain starts again.
var db = DB();
db.read('users').id('u1').set('user');
db.find('orders').where('userid', 'u1').set('orders');
db.callback(function(err, response) {
// response.user, response.orders
});
method
NEWDB([name], [fn])
Registers or removes a database adapter.
NEWDB([name], [fn])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The connection name. Default: 'default' |
fn? |
Function |
function(filter, callback) that executes the query. Omit it to remove the adapter. |
The adapter executes the queries of the connection name. It is called with this as the internal query object, filter as the options of the query (exec, table, filter, fields, sort, take, skip, payload, upsert, returning, first, language, query, params, scalar, command, primarykey, schema, checksum, debug) and a callback (err, response). The checksum is a short hash of the structure of the filter, useful as a cache key for prepared queries. The adapter * is used for connections without their own adapter. Without fn the adapter name is removed; name is required then. The framework registers the adapter nosql for the embedded NoSQL files, and DATA.init() registers adapters for PostgreSQL (see PostgreSQL).
NEWDB('default', function(filter, callback) {
console.log(filter.exec, filter.table, filter.filter);
callback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);
});
method
db.find(table)
Finds all rows that match the filter.
db.find(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation find. The response is the array that the adapter returns. Alias: db.all().
DATA.find('products').where('price', '>', 10).sort('name').callback(console.log);
method
db.read(table)
Reads one row.
db.read(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation read, take 1 and the first option. When the adapter returns an array, the response is its first item or null. Alias: db.one().
DATA.read('users').id('u1').error('@(User not found)').callback(console.log);
method
db.list(table)
Reads one page of rows with paging metadata.
db.list(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation list, skip 0 and take 100. The adapter returns an object with the rows and the total count; the nosql adapter returns { items, count }, where count is the number of all matching documents. The QueryBuilder adds page, limit and pages to that object.
DATA.list('products').page(2, 20).callback(function(err, response) {
console.log(response.items, response.count, response.pages);
});
method
db.check(table)
Checks whether a row exists.
db.check(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation check, take 1 and the first option. The adapter answers whether a row matches (the nosql adapter returns true or false).
DATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);
method
db.count(table)
Counts the rows that match the filter.
db.count(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation count. The adapter decides the form of the response.
DATA.count('orders').where('status', 'paid').callback(console.log);
method
db.scalar(table, type, [key], [key2])
Computes an aggregate value.
db.scalar(table, type, [key], [key2])| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
type |
String |
The aggregate, for example sum, avg, min, max, count. |
key? |
String |
The column. Default: '*' |
key2? |
String |
A second column to group by key. |
Returns QueryBuilder
Returns a QueryBuilder with the operation scalar and the option scalar = { type, key, key2 }. key defaults to *. With key2 the adapter groups the values of key2 by key. The types are interpreted by the adapter; the nosql adapter supports min, max, sum, avg and count (without key2; with the default * each document counts as 1), and group (key2 sums the values of key2 per key).
DATA.scalar('orders', 'sum', 'price').where('status', 'paid').callback(console.log);
method
db.insert(table, data)
Inserts a row.
db.insert(table, data)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
data |
Object |
The row to insert. |
Returns QueryBuilder
Returns a QueryBuilder with the operation insert and data as the payload. Alias: db.ins().
DATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);
method
db.update(table, data, [upsert])
Updates the rows that match the filter.
db.update(table, data, [upsert])| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
data |
Object |
The columns to change. |
upsert? |
Boolean |
Insert the payload when nothing was updated. Default: false |
Returns QueryBuilder
Returns a QueryBuilder with the operation update and data as the payload. With upsert set to true, an update that returns no result (or an empty returning result) is executed again as an insert of the same payload with no conditions; builder.insert(fn) can change the payload before that. Aliases: db.modify(), db.mod(), db.upd().
DATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);
method
db.remove(table)
Removes the rows that match the filter.
db.remove(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation remove. Alias: db.rem().
DATA.remove('users').id('u1').callback(console.log);
method
db.query([connection], query, [params])
Runs a raw query.
db.query([connection], query, [params])| Parameter | Type | Description |
|---|---|---|
connection? |
String |
The connection name. Default: 'default' |
query |
String |
The raw query. |
params? |
Object|Array |
Parameters for the adapter. |
Returns QueryBuilder
Returns a QueryBuilder with the operation query and the options query and params. With one argument (or when the second argument is an object) the query runs on the connection default; otherwise the first argument is the connection name. The adapter decides the syntax of the query and of the parameters.
DATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').callback(console.log);
method
db.truncate(table)
Removes all rows of a table.
db.truncate(table)| Parameter | Type | Description |
|---|---|---|
table |
String |
The table name. connection/table selects a connection; without a slash the connection is default. |
Returns QueryBuilder
Returns a QueryBuilder with the operation truncate. Alias: db.clear(). db.drop(table) works the same with the operation drop, and db.command(table, name) with the operation command and the option command = name, for custom commands of the adapter.
DATA.truncate('logs/requests').callback(console.log);
method
db.exec(filter, callback)
Runs a query described by a plain object.
db.exec(filter, callback)| Parameter | Type | Description |
|---|---|---|
filter |
Object |
The options, for example { exec: 'find', table: 'users', take: 10 }. |
callback |
Function |
function(err, response). |
filter.exec selects the operation (find, list, read, count, truncate, drop, remove, insert, update, scalar, command or query) and filter.table the table; every other key is copied into the options of the query. For query the raw query is in filter.query.
DATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);
method
db.load([connection], options)
Creates a query from prepared options.
db.load([connection], options)| Parameter | Type | Description |
|---|---|---|
connection? |
String |
The connection name. Default: 'default' |
options |
Object |
The prepared options. |
Returns QueryBuilder
Creates a QueryBuilder from an object with table, exec, fields, skip, take, query, sort, payload, upsert, returning and filter (an array of filter items). The connection defaults to default.
DATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);
method
db.language(prefix, skip)
Sets the defaults for localized columns.
db.language(prefix, skip)| Parameter | Type | Description |
|---|---|---|
prefix |
String |
The prefix put before the language code. |
skip |
String |
A language that means "no language". |
Returns Database
Sets the global prefix and the language to skip that builder.language() uses when it gets no own values. The default skipped language is _.
DATA.language('_', 'en');
method
db.debug()
Sets the debug option on every query of a DB() chain.
db.debug()Returns Database
Each query created after this call gets the option debug = true, so an adapter that supports it can log the generated query.
var db = DB().debug();
db.find('users');
db.callback(console.log);
method
db.callback(fn)
Sets the callback of a DB() chain.
db.callback(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function|$ |
function(err, response) or the $ of an action. |
Returns Database
The callback gets the first error or the final response. Pass $ of an action instead of a function to answer the action. Alias: db.pipe().
var db = DB();
db.read('users').id('u1').set('user');
db.callback($);
method
db.promise([$])
Returns a promise of a DB() chain.
db.promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
Object |
The $ of an action. |
Returns Promise
The promise resolves with the final response. On error it is rejected, or, with $, the error goes to $.invalid().
var db = DB();
db.read('users').id('u1').set('user');
db.find('orders').where('userid', 'u1').set('orders');
var response = await db.promise($);
method
db.done($, fn)
Calls fn on success and $.invalid() on error.
db.done($, fn)| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action. |
fn? |
Function |
function(response). |
Returns Database
Ends a DB() chain inside an action: an error is passed to $.invalid(), a response to fn(response).
var db = DB();
db.read('users').id($.params.id).set('user');
db.done($, function(response) {
$.callback(response.user);
});
method
builder.where(name, [comparer], value)
Adds a comparison.
builder.where(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
comparer? |
String |
=, <>, >, <, >=, <=. Default: '=' |
value |
Object |
The value. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Without comparer the comparison is =. == becomes = and != becomes <>. With only name, the argument is a raw condition, the same as query().
DATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);
method
builder.id(value)
Filters by the column id.
builder.id(value)| Parameter | Type | Description |
|---|---|---|
value |
String|Array |
An id or a list of ids. |
Returns QueryBuilder The same QueryBuilder, for chaining.
where('id', value), or in('id', value) when the value is an array.
DATA.read('users').id('u1').callback(console.log);
method
builder.userid(value)
Filters by the column userid.
builder.userid(value)| Parameter | Type | Description |
|---|---|---|
value |
String|Array|Object |
An id, a list, a user or $. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Accepts an id, an array of ids (in), a user object (its id) or an object with user such as $ of an action (its user.id).
DATA.find('orders').userid($).callback($);
method
builder.equal(obj)
Adds one equality per key.
builder.equal(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
Column names and values. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Calls where(key, value) for every key of the object.
DATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);
method
builder.in(name, value, [key])
The column is one of the values.
builder.in(name, value, [key])| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
value |
Array |
The values. |
key? |
String |
A property to read from each object of value. |
Returns QueryBuilder The same QueryBuilder, for chaining.
A single value is wrapped in an array. With key, value is an array of objects and the values are taken from their property key.
DATA.find('users').in('id', orders, 'userid').callback(console.log);
method
builder.notin(name, value, [key])
The column is none of the values.
builder.notin(name, value, [key])| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
value |
Array |
The values. |
key? |
String |
A property to read from each object of value. |
Returns QueryBuilder The same QueryBuilder, for chaining.
The opposite of in(), with the same arguments.
DATA.find('users').notin('role', ['guest']).callback(console.log);
method
builder.between(name, a, b)
The column is between two values.
builder.between(name, a, b)| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
a |
Object |
The lower value. |
b |
Object |
The upper value. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Adds a between item with a and b.
DATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);
method
builder.search(name, value, [where])
Searches text in a column.
builder.search(name, value, [where])| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
value |
String |
The text. |
where? |
String |
beg or end. |
Returns QueryBuilder The same QueryBuilder, for chaining.
The column contains value. With where set to beg the text must be at the beginning, with end at the end.
DATA.find('products').search('name', 'phone').callback(console.log);
method
builder.or(fn)
Joins a group of conditions with OR.
builder.or(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(builder). |
Returns QueryBuilder The same QueryBuilder, for chaining.
The filters added inside fn form one group. fn is called with the builder as this and as the argument. An empty group is ignored.
DATA.find('users').or(function(builder) {
builder.where('role', 'admin');
builder.where('role', 'editor');
}).callback(console.log);
method
builder.contains(name)
The column has a value.
builder.contains(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Adds a contains item: the column is not empty (for arrays: it has items). empty(name) is the opposite: the column has no value.
DATA.find('users').contains('phone').callback(console.log);
method
builder.array(name, [comparer], value)
A condition on an array column.
builder.array(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
comparer? |
String |
The comparer. Default: '&&' |
value |
Array|String |
The values. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Adds an array item. The default comparer is && (the arrays overlap); the adapter interprets it.
DATA.find('products').array('tags', ['sale', 'new']).callback(console.log);
method
builder.year(name, [comparer], value)
Compares a part of a date.
builder.year(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
name |
String |
The date column. |
comparer? |
String |
The comparer. Default: '=' |
value |
Number |
The value of the part. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Compares the year of a date column. month(), day(), hour() and minute() have the same arguments and compare that part. The default comparer is =.
DATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);
method
builder.query(value)
Adds a raw condition.
builder.query(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
The raw condition. |
Returns QueryBuilder The same QueryBuilder, for chaining.
The text is passed to the adapter as it is, so it must be in the syntax of the engine.
DATA.find('users').query('age > 18').callback(console.log);
method
builder.join(name, table, type, a, b)
Adds a join item for the adapter.
builder.join(name, table, type, a, b)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the join. |
table |
String |
The joined table. |
type |
String |
The join type. |
a |
String |
The column of the main table. |
b |
String |
The column of the joined table. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Adds { type: 'join', name, table, join: type, on: [a, b] } to the filter. Whether joins are supported is up to the adapter.
DATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);
method
builder.permit(name, type, value, [userid], [required])
Adds a permission condition for the adapter.
builder.permit(name, type, value, [userid], [required])| Parameter | Type | Description |
|---|---|---|
name |
String |
The column with permissions. |
type |
String |
The letters R, W, D. |
value |
Array |
Roles or groups. |
userid? |
String |
The id of the user. |
required? |
Boolean |
The permission is required. Default: true |
Returns QueryBuilder The same QueryBuilder, for chaining.
Each letter of type (R read, W write, D delete) is combined with each item of value, so permit('permissions', 'RW', ['admin']) gives ['Radmin', 'Wadmin']. The item also carries userid and required (default true).
DATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).callback($);
method
builder.fields(fields)
Selects the columns.
builder.fields(fields)| Parameter | Type | Description |
|---|---|---|
fields |
String |
For example id,name,email. |
Returns QueryBuilder The same QueryBuilder, for chaining.
A comma-separated list of columns.
DATA.find('users').fields('id,name,email').callback(console.log);
method
builder.gridfields(fields, [allowed])
Selects the columns from an untrusted list.
builder.gridfields(fields, [allowed])| Parameter | Type | Description |
|---|---|---|
fields? |
String |
The requested fields, for example id,name. Can be empty or undefined. |
allowed? |
String |
The fields that may be selected, for example id,name,price. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Takes a comma-separated list, usually $.query.fields, and selects the fields that are also in allowed. Quotes, backticks, | and spaces are removed first. Empty names are skipped. When the list is empty or missing, or none of the fields is allowed, the selection does not change (all columns). Without allowed every field of the list is selected.
DATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);
method
builder.sort(name, [desc])
Adds a sort column.
builder.sort(name, [desc])| Parameter | Type | Description |
|---|---|---|
name |
String |
The column. |
desc? |
Boolean|String |
true or desc for descending. Default: false |
Returns QueryBuilder The same QueryBuilder, for chaining.
desc can be true or 'desc'; anything else sorts ascending. Several calls add more columns.
DATA.find('products').sort('price', true).sort('name').callback(console.log);
method
builder.gridsort(sort, [map])
Adds sort columns from a string.
builder.gridsort(sort, [map])| Parameter | Type | Description |
|---|---|---|
sort |
String |
The sort string. |
map? |
Object |
Field names mapped to columns. |
Returns QueryBuilder The same QueryBuilder, for chaining.
The string has the form name_asc,dtcreated_desc; a name without a suffix is ascending. map can rename the fields to columns.
DATA.find('products').gridsort('price_desc,name').callback(console.log);
method
builder.take(count)
Sets the maximum number of rows.
builder.take(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
The number of rows. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Alias: limit(). first() sets take to 1 and returns only the first row. skip(count) sets the number of rows to skip.
DATA.find('products').take(10).callback(console.log);
method
builder.page(page, [limit])
Selects a page.
builder.page(page, [limit])| Parameter | Type | Description |
|---|---|---|
page |
Number |
The page, from 1. |
limit? |
Number |
Rows per page. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Sets skip to (page - 1) * take. With limit it also sets take first.
DATA.list('products').page(3, 20).callback(console.log);
method
builder.paginate(page, limit, [maxlimit])
Selects a page from untrusted values.
builder.paginate(page, limit, [maxlimit])| Parameter | Type | Description |
|---|---|---|
page |
Number|String |
The page. |
limit |
Number|String |
Rows per page. |
maxlimit? |
Number |
The highest allowed limit. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Converts page and limit to numbers (strings from a query string work), uses page 1 when the page is missing, zero or negative, keeps the limit under maxlimit and uses maxlimit when no limit is given.
DATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);
method
builder.autoquery(query, schema, [defsort], [maxlimit])
Builds fields, filters, sort and paging from a query string.
builder.autoquery(query, schema, [defsort], [maxlimit])| Parameter | Type | Description |
|---|---|---|
query |
Object |
The query string, usually $.query. |
schema |
String |
The allowed fields and types. |
defsort? |
String |
The default sort, for example dtcreated_desc. |
maxlimit? |
Number |
Enables paging with this highest limit. |
Returns QueryBuilder The same QueryBuilder, for chaining.
schema lists the allowed fields as name:type separated by commas (types: string, number, date, boolean, [string], json; the default is string), or @SchemaName to take them from a JSON schema. query.fields selects among the allowed fields (all of them when it is missing), each allowed field is filtered with gridfilter(), query.sort (name_asc, name_desc) sorts by allowed fields or defsort is used, and with maxlimit query.page and query.limit go to paginate(). Fields that are not in the schema are ignored. Columns selected with fields() before autoquery() stay selected, and the fields of the query string are added to them for this query only.
DATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);
method
builder.autoqueryjson($, column, schema, [defsort], [maxlimit])
Builds fields, filters, sort and paging for properties of a JSON column.
builder.autoqueryjson($, column, schema, [defsort], [maxlimit])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action, or the query string. |
column |
String |
The JSON column. |
schema |
String |
The allowed properties and types. |
defsort? |
String |
The default sort, for example weight_desc. |
maxlimit? |
Number |
Enables paging with this highest limit. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Works like autoquery(), but the fields are properties stored in the JSON column column. $ is the $ of an action (its query is used) or the query string itself. schema lists the properties as name:type separated by commas (types: string, number, boolean, date, [string]; the default is string). The QueryBuilder gives the adapter each property as the name json:column:property:type in the fields, the filter and the sort, and the adapter translates it into its own syntax; the PostgreSQL adapter reads the property with ->> and converts it to its type. column may contain only letters, digits and _, otherwise the method throws an error; properties with other characters are ignored. It can follow autoquery() on the same query.
DATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);
method
builder.gridfilter(name, query, [type], [column])
Adds a filter from a query string value.
builder.gridfilter(name, query, [type], [column])| Parameter | Type | Description |
|---|---|---|
name |
String |
The key in query. |
query |
Object |
The query string. |
type? |
String |
The type of the value. Default: 'string' |
column? |
String |
The column, when it differs from name. |
Returns QueryBuilder The same QueryBuilder, for chaining.
Reads query[name] and adds a condition by its form: a - b is between, a,b is an OR of searches for text and in for other types, =a,b is in with exact texts, =a an exact match, a plain text a search, >v and <v comparisons. For dates today, yesterday and a date select the whole day, a 4-digit number the year and a small number the month. type is string, number, date, boolean, [string] (array filter) or json (search). Empty values add nothing.
DATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);
method
builder.language(value, [prefix], [skip])
Sets the language for localized columns.
builder.language(value, [prefix], [skip])| Parameter | Type | Description |
|---|---|---|
value |
String|Object |
The language or an object with language. |
prefix? |
String |
The prefix. |
skip? |
String |
A language that means "no language". |
Returns QueryBuilder The same QueryBuilder, for chaining.
Sets the option language to prefix + value. value can be an object with language (such as $). When value equals skip the language is empty. Without prefix and skip the defaults of db.language() apply. The nosql adapter replaces a trailing § in column names with the language.
DATA.find('products').fields('id,name§').language($).callback($);
method
builder.returning(fields)
Asks the adapter to return columns of the changed rows.
builder.returning(fields)| Parameter | Type | Description |
|---|---|---|
fields |
String |
For example id,name. |
Returns QueryBuilder The same QueryBuilder, for chaining.
A comma-separated list stored in the option returning. With an upsert, an empty returned result means "nothing was updated".
DATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);
method
builder.insert(fn, [param])
Prepares the payload of an upsert insert.
builder.insert(fn, [param])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(payload, param). |
param? |
Object |
A value passed to fn. |
Returns QueryBuilder The same QueryBuilder, for chaining.
With update(table, data, true), fn(payload, param) is called before the payload is inserted, so you can add values that only a new row needs.
DATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {
doc.id = 'home';
doc.dtcreated = NOW;
}).callback(console.log);
method
builder.error(message, [reverse])
Turns an empty result into an error.
builder.error(message, [reverse])| Parameter | Type | Description |
|---|---|---|
message |
String |
The error, for example @(User not found). |
reverse? |
Boolean |
Fail when there is a result. Default: false |
Returns QueryBuilder The same QueryBuilder, for chaining.
When the response is empty (no value, or an empty array for queries that do not take one row), the query fails with message. With reverse set to true, a non-empty response fails. Alias: err().
DATA.read('users').id($.params.id).error('@(User not found)').callback($);
method
builder.callback(fn)
Sets the callback of the query.
builder.callback(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function|$ |
function(err, response) or $. |
Returns QueryBuilder The same QueryBuilder, for chaining.
fn(err, response) is called when the query finishes. Pass $ of an action to answer the action with the result. Alias: pipe(). data(fn) sets a callback only for success (fn(response)) and fail(fn) one only for errors (fn(err)).
DATA.find('users').callback(function(err, response) {
console.log(err, response);
});
method
builder.promise([$])
Returns a promise of the query.
builder.promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
Object |
The $ of an action. |
Returns Promise
Resolves with the response. On error the promise is rejected with the error (an error object of the adapter gets the name QueryBuilder(table --> operation)), or, with $, the error goes to $.invalid().
var user = await DATA.read('users').id('u1').promise($);
method
builder.done($, fn, [param])
Calls fn on success and $.invalid() on error.
builder.done($, fn, [param])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action. |
fn |
Function |
function(response, param). |
param? |
Object |
A value passed to fn. |
Returns QueryBuilder The same QueryBuilder, for chaining.
On success fn(response, param) is called; an error goes to $.invalid().
DATA.read('users').id($.params.id).done($, function(user) {
$.callback({ id: user.id, name: user.name });
});
method
builder.audit($, [message], [type])
Writes an audit record after success.
builder.audit($, [message], [type])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action. |
message? |
String |
The message. |
type? |
String |
The type of the record. |
Returns QueryBuilder The same QueryBuilder, for chaining.
After a successful query, calls $.audit(message, type). Placeholders such as {data.name} in the message are filled from the payload, {user.name} from the user.
DATA.insert('products', model).audit($, 'Created product {data.name}').callback($);
method
builder.set(name)
Stores the result under a key of the DB() response.
builder.set(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The key. |
Returns QueryBuilder The same QueryBuilder, for chaining.
In a DB() chain the response becomes an object and this result is saved as response[name]. nobind() keeps the result out of the response completely.
var db = DB();
db.read('users').id('u1').set('user');
db.count('orders').where('userid', 'u1').set('orders');
db.callback($);
method
builder.debug()
Sets the debug option of the query.
builder.debug()Returns QueryBuilder The same QueryBuilder, for chaining.
Sets debug = true in the options, so an adapter that supports it can log the query. primarykey(name) and schema(name) set the options primarykey and schema in the same way, for adapters that use them.
DATA.find('users').debug().callback(console.log);