Spanish Total.js
English
Documentation For AI agents
Contents

QueryBuilder

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

.md GitHub
On this page

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

API

method

NEWDB([name], [fn])

Registers or removes the adapter of an SQL connection.
ParameterTypeDescription
name? String The connection name. Default: 'default'
fn? Function 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.

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

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

// Remove
NEWDB('analytics');
delegate

function(filter, callback)

The function that runs a query against the database.
ParameterTypeDescription
filter Object The description of the query.
callback Function 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.

Skeleton of an adapter
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));
});
type

filter {Object}

The description of a query that the adapter receives.

Returns Object

FieldTypeMeaning
execStringfind, list, read, check, count, scalar, insert, update, remove, query, command, truncate or drop
tableStringThe table name, without the connection prefix (empty for query)
filterArrayThe conditions in their order (see below)
fieldsArrayThe column names from fields(), or empty for all
sortArrayItems in the form name_asc or name_desc
take, skipNumberLimit and offset. list starts with take: 100, skip: 0
firstBooleantrue for read, check and first(): one row is expected
payloadObjectThe data of insert and update
upsertBooleantrue for an update with upsert
returningArrayThe columns from returning()
query, paramsString, Array/ObjectThe SQL and the arguments of query()
scalarObject{ type, key, key2 } from scalar()
commandStringThe name from command()
languageStringThe value from language()
primarykeyStringThe value from builder.primarykey(name)
schemaStringThe value from builder.schema(name)
checksumStringA hash of the shape of the filters (without the values), useful as a cache key of prepared statements
debugBooleantrue 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).

method

DB()

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.

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

DATA

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.

A single query
var user = await DATA.read('tbl_user').id(id).promise();
method

db.find(table)

Finds rows.
ParameterTypeDescription
table String 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.

Find
DATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);
method

db.list(table)

Finds one page of rows with counts.
ParameterTypeDescription
table String 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).

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

db.read(table)

Reads one row.
ParameterTypeDescription
table String 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').

Read
DATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);
method

db.check(table)

Checks whether a row exists.
ParameterTypeDescription
table String 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.

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

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

Runs an aggregation.
ParameterTypeDescription
table String The table name. A prefix name/ chooses the connection, for example logs/tbl_request.
type String The kind of aggregation.
key? String The column. Default: '*'
key2? String 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.

Sum
DATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);
Count
DATA.count('tbl_order').where('status', 'new').callback(console.log);
method

db.insert(table, data)

Inserts a row.
ParameterTypeDescription
table String The table name. A prefix name/ chooses the connection, for example logs/tbl_request.
data Object 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.

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

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

Updates rows.
ParameterTypeDescription
table String The table name. A prefix name/ chooses the connection, for example logs/tbl_request.
data Object The changed columns.
upsert? Boolean Insert the data when nothing was updated. Default: false

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.

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

db.remove(table)

Removes rows.
ParameterTypeDescription
table String 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()).

Remove
DATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());
method

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

Runs your own SQL.
ParameterTypeDescription
conn? String The connection name. Default: 'default'
sql String The SQL.
params? Array|Object 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.

Raw SQL
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);
Command
DATA.command('tbl_product', 'reindex').callback(console.log);
method

db.truncate(table)

Removes all rows of a table.
ParameterTypeDescription
table String 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.

Truncate
DATA.truncate('tbl_log').callback(console.log);
method

db.load([conn], options)

Creates a query from a prepared object.
ParameterTypeDescription
conn? String The connection name. Default: 'default'
options Object 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.

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

db.callback(fn)

Sets the final callback of a DB() controller.
ParameterTypeDescription
fn Function|Object 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).

Callback
var db = DB();
db.read('tbl_user').id(id).set('user');
db.find('tbl_role').where('userid', id).set('roles');
db.callback($);
Await
var db = DB();
db.remove('tbl_user_role').where('userid', $.id);
db.remove('tbl_user').id($.id);
await db.promise($);
$.success();
method

db.done($, [fn])

Calls fn on success, $.invalid() on an error.
ParameterTypeDescription
$ Object The options of a schema or an operation.
fn? Function function(response).

Returns QueryBuilderDB

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

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

db.debug()

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.

Debug
var db = DB().debug();
db.find('tbl_user').take(1);
Debug
DATA.find('tbl_user').where('email', email).debug().callback(console.log);
method

db.language(prefix, skip)

Sets the default prefix and skip value of builder.language().
ParameterTypeDescription
prefix String Text put before the language.
skip String 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: '_'.

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

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

Adds a condition.
ParameterTypeDescription
name String The column.
comparer? String =, <>, >, <, >= or <=. Default: '='
value Object 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().

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

builder.id(id)

Filters by the id column.
ParameterTypeDescription
id Object|Array 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.

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

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

The column is one of the values.
ParameterTypeDescription
name String The column.
value Array|Object The values.
key? String 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.

In
DATA.find('tbl_product').in('id', items, 'productid').callback(console.log);
Not in
DATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);
method

builder.between(name, a, b)

The column is between two values.
ParameterTypeDescription
name String The column.
a Object The lower value.
b Object The upper value.

Returns QueryBuilder The builder of the query, for chaining.

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

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

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

A condition on an array column.
ParameterTypeDescription
name String The column.
comparer? String The operator for the adapter. Default: '&&'
value Array 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).

Tags
DATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);
method

builder.or(fn)

Groups conditions joined with OR.
ParameterTypeDescription
fn Function function(builder).

Returns QueryBuilder The builder of the query, for chaining.

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

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

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

A text search (LIKE).
ParameterTypeDescription
name String The column.
value String The text.
where? String 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.

Search
DATA.find('tbl_product').search('name', $.query.q).callback($.callback);
method

builder.contains(name)

The column has a value.
ParameterTypeDescription
name String 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 }.

Contains
DATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);
method

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

Compares a part of a date.
ParameterTypeDescription
name String The date column.
comparer? String The operator. Default: '='
value Number 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 =.

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

builder.query(sql)

Adds a raw SQL condition.
ParameterTypeDescription
sql String 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.

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

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

Adds a join.
ParameterTypeDescription
name String The name of the joined data.
table String The joined table.
jointype? String For example left or inner.
a String The column of the main table.
b String 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.

Join
DATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);
method

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

Filters by a permissions column.
ParameterTypeDescription
name String The column.
type String Letters such as R, W, D.
value Array Roles or ids.
userid? String A user id that the adapter may also accept.
required? Boolean Whether the permission is required. Default: true

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.

Permit
DATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);
method

builder.fields(fields)

Selects the columns.
ParameterTypeDescription
fields String 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.

Fields
DATA.find('tbl_user').fields('id,name,email').callback(console.log);
method

builder.sort(name, [desc])

Adds a sort.
ParameterTypeDescription
name String The column.
desc? Boolean|String Descending order. Default: false

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.

Sort
DATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);
Grid sort
DATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);
method

builder.take(count)

Limits the number of rows.
ParameterTypeDescription
count Number 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.

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

builder.page(page, [limit])

Sets the page.
ParameterTypeDescription
page Number The page, from 1.
limit? Number 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.

Page
DATA.list('tbl_product').page(2, 20).callback(console.log);
Skip
DATA.find('tbl_article').skip(20).take(10).callback(console.log);
method

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

Sets the page from user input.
ParameterTypeDescription
page String|Number The page, from 1.
limit String|Number Rows per page.
maxlimit? Number 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.

Paginate
DATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);
method

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

Adds a filter from a text value.
ParameterTypeDescription
name String The key in obj.
obj Object Usually the query string.
type? Function|String The type of the column. Default: String
key? String 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.
Grid filter
// ?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);
method

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

Builds fields, filters, sort and paging from the query string.
ParameterTypeDescription
query Object The query string, usually $.query.
fields String The allowed columns and types.
sort? String The default sort, for example 'dtcreated_desc'.
maxlimit? Number 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.

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

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

Builds a grid query from the schema of $.
ParameterTypeDescription
$ Object The options of a schema operation.
allowedfields? String Extra columns, with optional types.
skipfields? String Columns of the schema to leave out.
sort? String The default sort.
maxlimit? Number The maximum rows per page. Default: 50

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.

Autofill
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);
	});
});
method

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

Passes a language to the adapter.
ParameterTypeDescription
value String|Object The language, or an object with language.
prefix? String Text before the language.
skip? String 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.

Language
DATA.find('tbl_product').fields('id,name§').language($).callback($.callback);
method

builder.returning(fields)

Asks for columns of changed rows.
ParameterTypeDescription
fields String 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".

Returning
DATA.insert('tbl_user', model).returning('id').first().callback(console.log);
method

builder.insert(fn, [param])

Prepares the data of an upsert.
ParameterTypeDescription
fn Function function(data, param).
param? Object 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.

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

builder.error(err, [reverse])

Makes an empty result an error.
ParameterTypeDescription
err String The error.
reverse? Boolean Fail when a row exists. Default: false

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().

404
DATA.read('tbl_user').id($.id).error('404').callback($.callback);
method

builder.set(name)

Stores the response under a key of a DB() response.
ParameterTypeDescription
name String 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.

Set
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 }
method

builder.data(fn)

Calls fn with the response on success.
ParameterTypeDescription
fn Function 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.

Data
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);
Fail
DATA.insert('tbl_log', item).fail(err => console.error('log', err));
method

builder.callback(fn)

Calls fn with the result of this query.
ParameterTypeDescription
fn Function|Object 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).

Callback
DATA.find('tbl_user').take(10).callback(function(err, response) {
	console.log(err, response);
});
DATA.find('tbl_user').take(10).callback($);
Done
DATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());
method

builder.promise([$])

Returns a promise of this query.
ParameterTypeDescription
$? Object 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).

Await
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);
});
method

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

Writes an audit record after success.
ParameterTypeDescription
$ Object The options of a schema or an operation.
message? String The text.
type? String 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.

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

QueryBuilder

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.

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

DATA.find('tbl_user').active().callback(console.log);
Made in Europe