ForgeTotal.js 5
en

Total.js 5

Query builder: DB() and NEWDB() with your own database driver

Total.js 5 · total5@0.0.19 databasequerybuilder Executed against Total.js 5

DB() builds a query without knowing which database will run it, and NEWDB() registers the driver that runs it. total5 itself has no SQL driver: the query builder collects what you ask for into an options object and calls your driver with it, and the driver (yours, or one that comes in a module) translates options into SQL, a NoSQL call or anything else.

  • NEWDB(driver) registers the default driver and NEWDB('name', driver) a named one. The driver is function(options, callback): answer with callback(error, response). A table written as name/table (DB().find('audit/log')) uses the driver name and the table log; without a prefix the driver is default.
  • The operations start the query: find(table) (an array), read(table) (one object, or null when there is none), list(table) (a page of an array: response.page, limit and pages are added to what the driver returns, so the driver should set count) and insert(table, data). The builder also has count, update, remove and query; they work the same way (the driver gets options.exec with that name).
  • Refine the query with: where(name, [comparer], value) (= when there is no comparer), fields('a,b'), sort(name, [true]) (true for descending), take(n) and page(page, limit). Other modifiers include id, in, skip, between and search.
  • Finish with .callback($): the result goes to the response of the action $, or to a function (err, response) that you pass instead.

For the complete native operation catalogue, upsert/error behavior and filter shapes, see query-builder-contract. For SQL CRUD, commit and rollback, see query-builder-sqlite. The options the driver receives are plain data. The example driver stores records in memory and exposes the last options object received.

definitions/db.js
const users = [
	{ id: 1, name: 'Ann', age: 31 },
	{ id: 2, name: 'Bob', age: 17 },
	{ id: 3, name: 'Cy', age: 45 }
];

F.seen = [];

// The default driver: it understands only "age >= value" and "id = value", which is all this example asks
NEWDB(function(options, callback) {

	F.seen.push(JSON.parse(JSON.stringify(options)));

	let rows = users.slice();

	for (let f of options.filter) {
		if (f.type === 'where' && f.name === 'age' && f.comparer === '>=')
			rows = rows.filter(n => n.age >= f.value);
		else if (f.type === 'where' && f.name === 'id')
			rows = rows.filter(n => n.id === f.value);
	}

	switch (options.exec) {
		case 'find':
		case 'read':
			if (options.sort && options.sort[0] === 'name_desc')
				rows.sort((a, b) => a.name < b.name ? 1 : -1);
			if (options.take)
				rows = rows.slice(0, options.take);
			return callback(null, rows);
		case 'list':
			rows.count = rows.length;
			return callback(null, rows);
		case 'insert':
			users.push(Object.assign({ id: users.length + 1 }, options.payload));
			return callback(null, users[users.length - 1]);
		default:
			return callback('The driver does not know ' + options.exec);
	}
});

// A second driver, used by the tables that start with "audit/"
NEWDB('audit', function(options, callback) {
	F.seen.push({ driver: 'audit', table: options.table });
	callback(null, [{ event: 'login' }]);
});
controllers/users.js
exports.install = function() {
	ROUTE('GET /adults/', adults);
	ROUTE('GET /user/{id}/', user);
	ROUTE('POST /users/', create);
	ROUTE('GET /page/', page);
	ROUTE('GET /audit/', audit);
	ROUTE('GET /seen/', seen);
};

function adults($) {
	DB().find('users').where('age', '>=', 18).fields('id,name').sort('name', true).take(5).callback($);
}

function user($) {
	DB().read('users').where('id', +$.params.id).callback($);
}

function create($) {
	DB().insert('users', { name: $.body.name, age: $.body.age }).callback($);
}

function page($) {
	DB().list('users').page(1, 2).callback(function(err, response) {
		$.json({ err: err, count: response.count, page: response.page, limit: response.limit, pages: response.pages });
	});
}

function audit($) {
	DB().find('audit/log').callback($);
}

function seen($) {
	$.json(F.seen);
}