Spanish Total.js
English
Documentation For AI agents
Contents

QueryBuilder

Query any database with one QueryBuilder: DATA, DB(), adapters, filters, paging and autoquery.

.md GitHub
On this page

Total.js 5 has one QueryBuilder for every database. You describe a query with methods (find, where, sort, take…), the QueryBuilder turns the calls into a plain object of options, and an adapter for your database engine turns that object into a real query. Your code stays the same when you change the engine; only the adapter changes.

DATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {
    console.log(err, response);
});

The full list of methods is in the reference of QueryBuilder.

The parts

NameWhat it is
DATAA global, shared database object. Every call on it starts one query at once.
DB()Creates a new database object that runs several queries one after another and collects their results.
NEWDB(name, fn)Registers an adapter: the function that executes the queries for the connection name.
QueryBuilderThe object that find(), insert() and the other operations return. You chain filters on it.

Registering an adapter

The QueryBuilder does not talk to any database itself. An adapter is a function registered with NEWDB(). It receives the options of the query and a callback:

NEWDB('default', function(filter, callback) {
    // filter.exec     the operation: find, list, read, check, count, scalar,
    //                 insert, update, remove, query, drop, truncate, command
    // filter.table    the table name
    // filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]
    // filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...
    callback(null, []);
});

The adapter of the connection is chosen by the table name. 'users' uses the connection default, 'logs/requests' uses the connection logs and the table requests. When no adapter has that name, the adapter * is used if it exists; otherwise the query fails with the error Database is not initialized. Calling NEWDB(name) without a function removes the adapter.

The framework ships the adapter nosql, which runs the QueryBuilder against the embedded NoSQL files: DATA.find('nosql/users'). See NoSQL. For PostgreSQL, DATA.init('default', 'postgresql://…') registers an adapter that writes the SQL; see PostgreSQL.

Reading data

// all rows that match
DATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);

// one row (or null)
DATA.read('products').id('p123').callback(console.log);

// a page with metadata
DATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {
    // response.items, response.count (from the adapter)
    // response.page, response.limit, response.pages (added by the QueryBuilder)
});

// true or false
DATA.check('users').where('email', 'peter@example.com').callback(console.log);

// number of rows
DATA.count('orders').where('status', 'paid').callback(console.log);

list() starts with skip 0 and take 100. read() and check() take one row; when the adapter returns an array, read() gives its first item or null.

scalar(table, type, key, key2) computes a value such as 'sum', 'avg', 'min', 'max' or 'count' over a column; the adapter decides what each type returns.

Writing data

DATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);

DATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);

DATA.remove('users').where('id', 'u1').callback(console.log);

Pass true as the third argument of update() for an upsert: when the update changes nothing, the QueryBuilder clears the conditions and runs the same payload as an insert. With .insert(fn) you can change the payload just before that insert:

DATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {
    doc.id = 'home';
    doc.dtcreated = NOW;
}).callback(console.log);

returning('id,name') asks the adapter to return those columns of the changed rows.

Filters

All filters are joined with AND. Put a group in or() to join it with OR.

DATA.find('users')
    .where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)
    .in('role', ['admin', 'editor'])
    .notin('id', ['u1', 'u2'])
    .between('dtcreated', NOW.add('-7 days'), NOW)
    .search('name', 'pet')              // contains the text
    .or(function(builder) {
        builder.where('isblocked', false);
        builder.empty('dtblocked');
    })
    .fields('id,name,email')
    .callback(console.log);
MethodCondition
where(name, [comparer], value)Compare a column. With one argument it is a raw condition (query()).
id(value), userid(value)where('id', …), or in('id', …) for an array
equal(obj)One where() per key of the object
in(), notin()The value is (not) in a list
between(name, a, b)Between two values
search(name, value, [where])Text search; where can be 'beg' or 'end'
contains(name), empty(name)The column has a value, or is empty
array(name, [comparer], value)A condition on an array column (&& by default)
year(), month(), day(), hour(), minute()Compare a part of a date
query(sql)A raw condition passed to the adapter as it is

The adapter translates these items into its own syntax, so which comparers and raw conditions work depends on the engine.

Sorting and paging

DATA.find('products')
    .sort('price', 'desc')       // or true
    .sort('name')                // ascending
    .page(3, 20)                 // skip 40, take 20
    .callback(console.log);

take() (alias limit()), skip() and first() set the numbers directly. paginate(page, limit, maxlimit) accepts values straight from a query string and keeps the limit under maxlimit. gridsort('name_asc,dtcreated_desc') reads a sort string.

Filters from a query string

autoquery() builds the whole query from the query string of a request. You list the allowed fields and their types; everything else is ignored.

NEWACTION('Products/list', {
    name: 'List of products',
    action: function($) {
        DATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);
    }
});

With ?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50 this selects only id and name, searches name, keeps rows with price above 100, sorts by price and returns the second page of 50 rows (never more than 100). The second argument can also be '@SchemaName' to take the fields and types from a JSON schema.

autoqueryjson($, column, schema, [defsort], [maxlimit]) does the same for properties stored in one JSON column. The QueryBuilder gives the adapter each property as the name json:column:property:type (for example json:data:weight:number), and the adapter translates it into its own syntax. The PostgreSQL adapter does it; see PostgreSQL.

gridfields(fields, allowed) selects the columns from a comma-separated list, usually $.query.fields, and keeps only the allowed ones. When the list is empty or missing, or none of them is allowed, the query reads all columns:

DATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);

gridfilter(name, query, type, [column]) does the same for one field. The value of the query string decides the condition:

ValueCondition
phonesearch for text, = for other types
=phoneExact match
a,b,cText: any of the words (OR of search); other types: in
=a,bText: in with the exact values
10 - 20between
>10, <10Greater or less than (numbers and dates)
today, yesterday, 2024-05-01The whole day (dates)
2024, 5The year (a number above 1000) or the month (dates)

Inside actions

callback($) passes the result straight to the action. promise($) gives a promise; with $ an error goes to $.invalid().

NEWACTION('Users/read', {
    name: 'Read user',
    params: '*id:UID',
    action: async function($) {
        var user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);
        $.callback(user);
    }
});

error(message) turns an empty result (no row, an empty array) into an error with that message. With error(message, true) it is the other way: a result is an error, which is useful for "already exists" checks. done($, fn) calls fn(response) on success and $.invalid(err) on error. audit($, message) writes an audit record after a successful operation; {data.name} in the message is replaced from the payload. See Actions.

Several queries with DB()

DB() runs its queries one after another, in the order you add them. set(name) stores the result of a query under a key of the final response; without it the response is the result of the last query.

var db = DB();
db.read('users').id('u1').set('user').error('@(User not found)');
db.find('orders').where('userid', 'u1').set('orders');
db.callback(function(err, response) {
    // response.user, response.orders
});

The first error stops the chain. db.promise($) and db.done($, fn) work like the methods of the QueryBuilder. db.debug() sets the debug option on every query, so adapters that support it can print the generated queries.

Made in Europe