PostgreSQL
Connect to PostgreSQL with DATA.init() and run the QueryBuilder, raw SQL and transactions on it.
On this page
Total.js 5 has its own PostgreSQL client, written for the framework and without other npm packages, and an adapter that runs the QueryBuilder on PostgreSQL. You register a connection once with DATA.init(). After that DATA, DB() and every method of the QueryBuilder work as described in QueryBuilder, and the adapter writes the SQL.
DATA.init('default', CONF.database + '?pooling=10');
DATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);
// SELECT * FROM tbl_product WHERE "price">100 ORDER BY "name" ASC LIMIT 20The full list of options and functions is in the reference of PostgreSQL.
Connecting
Keep the connection string in the config file:
database : postgresql://user:password@localhost:5432/eshopRegister the connection when the application starts, for example in definitions/db.js:
DATA.init('default', CONF.database + '?pooling=10');The first argument is the connection name. The connection default serves the tables without a prefix (DATA.find('tbl_product')). A connection with another name serves the tables with that prefix:
DATA.init('logs', CONF.database_logs);
DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);Calling DATA.init() again with the same name closes the old connections and replaces them. DATA.init(name) without a connection string removes the connection; its queries then fail with Database is not initialized.
The connection string
The connection string is a URL: postgresql://user:password@host:port/database. The port defaults to 5432. Without a database name the client uses the database named like the user. Encode special characters in the user name and the password with encodeURIComponent().
Options go in the query string, joined with &:
| Option | What it does |
|---|---|
pooling=10 | Keeps a pool of up to 10 connections. Without it every query opens a new connection and closes it at the end. |
schema=eshop | The schema of the tables: DATA.find('tbl_product') reads eshop.tbl_product. |
sslmode=require | Encrypts the connection (see below). ssl=true is the same. |
connect_timeout=5 | Seconds to wait for the connection. Then the query fails with Connection timeout. |
application_name=eshop | The name of the connections in pg_stat_activity. |
host, port, user, password, dbname | Replace the parts of the URL. A host that starts with / is the directory of a Unix socket. |
DATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');The values of sslmode:
| Value | Connection |
|---|---|
disable (default) | Not encrypted. |
prefer, allow | Encrypted when the server supports SSL, otherwise not encrypted. |
require, no-verify | Encrypted, the certificate is not checked. A server without SSL gives the error The server does not support SSL connections. |
verify-ca, verify-full | Encrypted, the certificate of the server must be valid. |
The client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks.
In a pool, an idle connection closes after 10 seconds. A connection that comes back to the pool inside an open transaction is closed and not used again.
Schemas
schema in the connection string sets the schema for every table of the connection. schema(name) on the QueryBuilder changes it for one query:
DATA.find('tbl_product').schema('archive').callback(console.log);
// SELECT * FROM archive.tbl_productRaw queries (DATA.query()) do not use the schema; write it in the SQL.
The SQL of the QueryBuilder
Column names are written in double quotes ("price"). A name with a space, a dot, a colon or a double quote is written as it is, so a field can be an expression:
DATA.find('tbl_product')
.where('isremoved', false)
.in('id', ['p1', 'p2'])
.search('name', 'pho')
.array('tags', ['sale'])
.fields('id, name, UPPER(name) AS code')
.callback(console.log);
// SELECT "id","name",UPPER(name) AS code FROM tbl_product
// WHERE "isremoved"=false AND "id" IN ('p1','p2') AND "name"::text ILIKE '%pho%' AND "tags" && ARRAY['sale']The values of conditions are escaped and written into the SQL. The payload of insert() and update() goes to the server as parameters ($1, $2…).
| Method | SQL |
|---|---|
where('age', '>', 20) | "age">20 |
where('dtremoved', null) | "dtremoved" IS NULL (IS NOT NULL with the comparer <>) |
in('id', ['a', 'b']), notin() | "id" IN ('a','b'), "id" NOT IN (…) |
between('age', 20, 30) | ("age" BETWEEN 20 AND 30) |
search('name', 'pet') | "name"::text ILIKE '%pet%' |
search('name', 'pet', 'beg') | "name"::text ILIKE 'pet%' (the text is at the beginning) |
search('name', 'pet', 'end') | "name"::text ILIKE '%pet' (the text is at the end) |
array('tags', ['a']) | "tags" && ARRAY['a']; another comparer, for example array('tags', '@>', ['a']), replaces && |
year('dtcreated', 2024) | EXTRACT(year from "dtcreated")=2024; month(), day(), hour() and minute() work in the same way |
contains('tags') | LENGTH("tags"::text)>0 |
empty('tags') | ("tags" IS NULL OR LENGTH("tags"::text)=0) |
query('age % 2 = 0') | (age % 2 = 0) |
or(fn) | (… OR …) |
permit('permissions', 'R', ['admin'], userid) | (userid='…' OR array_length("permissions",1) IS NULL OR "permissions"::_text && ARRAY['Radmin']); with required set to false the array_length() part is left out |
sort('name', true) | ORDER BY "name" DESC |
take(20), skip(40) | LIMIT 20 OFFSET 40 |
join() adds nothing to the SQL; write joins in a raw query. A column name that ends with § gets the language of the query: with language('sk', '_') the field name§ is read as "name_sk" AS "name".
Results
| Operation | Result |
|---|---|
find() | An array of rows. |
read() | One row or null. |
list() | { items, count, page, limit, pages }. The adapter runs two queries: the page and SELECT COUNT(1). |
check() | true or false. |
count() | A number. |
scalar(table, 'sum', 'price') | A number; also avg, min, max and count. |
scalar(table, 'group', 'kind', 'price') | Rows { kind, value }: the sum of price for each kind (without the fourth argument the number of rows). |
insert() | The number of inserted rows. With primarykey('id') the value of that column, with returning('id,dtcreated') the inserted row. |
update() | The number of changed rows. With returning() an array of the changed rows, with returning() and first() one row. |
remove() | The number of removed rows. With returning() an array of the removed rows. |
query() | An array of rows. |
truncate() | Runs TRUNCATE TABLE … RESTART IDENTITY. |
drop() | Runs DROP TABLE …. |
DATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);
// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }
DATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);
// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]Operators in the payload
The first character of a key in the payload of update() can change the value in the database instead of replacing it:
| Key | SQL |
|---|---|
'+stock': 5 | "stock"=COALESCE("stock",0)+$1; also -, * and / |
'>price': 10 | "price"=GREATEST("price",$1) |
'<price': 10 | "price"=LEAST("price",$1) |
'!isread': 1 | "isread"=NOT "isread" |
'=dtupdated': 'NOW()' | "dtupdated"=NOW(), the value is raw SQL |
'#dtupdated': 'NOW()' | The same as =, but insert() leaves the key out |
DATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);
// UPDATE tbl_product SET "stock"=COALESCE("stock",0)+$1,"reserved"=COALESCE("reserved",0)-$2,"dtupdated"=NOW() WHERE "id"='p1'In insert() the character is removed: the column gets the value (0 when the value is empty), ! inserts FALSE and = inserts the raw SQL. So the same payload works in an upsert. This counter adds a row for the day and then increases it:
var id = NOW.format('yyyy-MM-dd');
DATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);
// the first call: INSERT INTO tbl_visitor ("count","dtupdated","id") VALUES($1,NOW(),$2)
// the next calls: UPDATE tbl_visitor SET "count"=COALESCE("count",0)+$1,"dtupdated"=NOW() WHERE "id"='2026-11-16'Properties of a JSON column
autoqueryjson() works like autoquery(), but for properties stored in one JSON or JSONB column. It reads fields, filters, sort and paging from the query string, and the adapter reads each property with ->> and converts it to its type:
NEWACTION('Products/list', {
name: 'List of products',
action: function($) {
DATA.list('tbl_product')
.autoquery($.query, 'id,name,price:number', 'name_asc', 100)
.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')
.callback($);
}
});With ?fields=id,name,color,weight&color=red&weight=<100 the response has the columns id and name and the properties color and weight of the column data, for the red products lighter than 100:
{ items: [{ id: 'p3', name: "Kid's watch", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }A value of a wrong type never makes the query fail:
| Type | Result |
|---|---|
string (default) | The text. |
number | A number; 0 when the value is not a number. |
boolean | true for true, 1, on and yes, otherwise false. |
date | A Date; null when the value is not a valid date (2024-02-30). |
[string] | An array of strings; [] when the value is not an array. |
A missing property is null. The filters, the sort and the types of the values are the same as in autoquery().
Raw queries
DATA.query() sends the SQL as it is. Parameters are $1, $2… and their values go in an array:
DATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);Conditions added with the QueryBuilder replace the text {where}, or are added at the end of the SQL when it has no {where}:
DATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);
// SELECT id, name FROM eshop.tbl_product WHERE "isremoved"=false AND "name"::text ILIKE '%a%' ORDER BY idTransactions
Each query of DATA and DB() gets its own connection, so a BEGIN in one query and a COMMIT in the next one do not belong together. Write the whole transaction as one raw query without parameters. When a statement fails, PostgreSQL rolls back the whole transaction and the callback gets the error. A query with several statements returns no rows (undefined):
DATA.query(`BEGIN;
UPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';
INSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);
COMMIT`).callback(console.log);When the transaction needs parameters or JavaScript between the statements, use the client directly (see below).
Errors and debugging
An error of the server is an Error with the message of PostgreSQL and the fields of the server: code, detail, hint, position, schema, table, column, constraint, severity and others.
DATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {
if (err)
console.log(err.code, err.constraint, err.detail);
// 23505 tbl_order_pkey Key (id)=(o1) already exists.
});Every failed query is also logged with ERROR(), with the first 100 characters of the SQL. A function as the third argument of DATA.init() gets this text instead:
DATA.init('default', CONF.database + '?pooling=10', function(message) {
console.log('SQL error:', message);
// SQL error: Error: column "unknown" does not exist - SELECT * FROM tbl_product WHERE "unknown"=1
});debug() on a query (or on a DB() chain) prints the SQL and the parameters to the console:
-- PostgreSQL --> SELECT "id","name" FROM eshop.tbl_product ORDER BY "price" DESC LIMIT 2 undefinedTypes of values
| PostgreSQL | JavaScript |
|---|---|
boolean | Boolean |
smallint, integer, real, double precision, numeric | Number |
bigint | String (it does not always fit into a JavaScript number) |
json, jsonb | The parsed value; texts in the ISO date format become Date objects |
date, timestamp, timestamptz | Date |
bytea | Buffer |
| arrays | Array of the same types |
| other types | String |
COUNT(*) in raw SQL is a bigint, so it comes as a string. Cast it (COUNT(*)::int), or change the parser of the type with its OID:
const PG = require('total5/client-postgresql');
PG.types[20] = value => +value; // bigint as a numberIn parameters, a Date is sent with its time zone, an object as JSON, a Buffer as binary data, and an array as a PostgreSQL array, or as JSON when the parameter is a json or jsonb column.
The client without the QueryBuilder
The client is a module of the framework: require('total5/client-postgresql'). Use it when you need one connection for several queries, for example a transaction with parameters:
const PG = require('total5/client-postgresql');
const pool = PG.pool(CONF.database, 5);
pool.connect(async function(err, client, release) {
if (err) {
console.log(err);
return;
}
try {
await client.query('BEGIN');
await client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);
await client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
} finally {
release();
}
});client.query() and pool.query() return { command, rowCount, rows, fields }, through a callback or a promise.