PostgreSQL
DATA.init(), the connection string, the SQL results and errors, and the PostgreSQL client.
On this page
DATA.init() and its connection string, what the PostgreSQL adapter returns, the operators of the payload, the errors, PG_ESCAPE() and the client total5/client-postgresql. The methods of the QueryBuilder are in the reference of QueryBuilder. An introduction with examples is in the guide PostgreSQL.
API
method
DATA.init([name], [connection], [onerror])
Registers a PostgreSQL connection for the QueryBuilder.
DATA.init([name], [connection], [onerror])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The connection name. Default: 'default' |
connection? |
String |
The connection string: postgresql://user:password@host:port/database?options. See the connection string. |
onerror? |
Function |
function(message) called for every failed query. |
Registers an adapter (NEWDB()) with the name name that runs the queries of DATA and DB() on PostgreSQL. The connection default serves the tables without a prefix, any other connection the tables with its prefix (DATA.find('logs/tbl_request')). Calling it again with the same name closes the old pool and replaces the connection. Without connection the connection is removed. Every failed query is passed to onerror as a text with the error and the first 100 characters of the SQL; without onerror it is logged with ERROR(name). The callback of the query gets the error in both cases.
DATA.init('default', CONF.database + '?pooling=10');
DATA.init('logs', CONF.database_logs);
DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);
DATA.init('default', CONF.database + '?pooling=10', function(message) {
console.log('SQL error:', message);
});
type
postgresql://user:password@host:port/database?options
The URL of the database and its options.
postgresql://user:password@host:port/database?options| Parameter | Type | Description |
|---|---|---|
pooling? |
Number |
The maximum number of connections in a pool. Without it every query opens a new connection and closes it at the end. An idle connection of the pool closes after 10 seconds. |
schema? |
String |
The schema of the tables: DATA.find('tbl_product') reads schema.tbl_product. builder.schema(name) changes it for one query. Raw queries do not use it. |
sslmode? |
String |
disable, prefer, allow, require, no-verify, verify-ca or verify-full. Default: 'disable' |
ssl? |
Boolean |
true or 1 is the same as sslmode=require. |
connect_timeout? |
Number |
Seconds to wait for the connection. Then the query fails with Connection timeout. |
application_name? |
String |
The name of the connections in pg_stat_activity. |
host? |
String |
Replaces the host of the URL. A value that starts with / is the directory of a Unix socket. |
port, user, password, dbname? |
String |
Replace the parts of the URL. |
The port defaults to 5432. Without a database name the client uses the database named like the user. Special characters of the user name and the password must be encoded with encodeURIComponent(). The options go in the query string. Other options are ignored.
The values of sslmode: disable (default) is not encrypted; prefer and allow encrypt when the server supports SSL; require and no-verify encrypt without checking the certificate and fail with The server does not support SSL connections when the server has no SSL; verify-ca and verify-full encrypt and the certificate must be valid.
The client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks.
database : postgresql://user:password@localhost:5432/eshop
DATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');
type
{ '+stock': 5, '=dtupdated': 'NOW()' }
Keys of the update() payload that change the value in the database.
{ '+stock': 5, '=dtupdated': 'NOW()' }The first character of a key in the payload of update():
| Key | SQL |
|---|---|
+name, -name, *name, /name | "name"=COALESCE("name",0)+$1 (and -, *, /) |
>name | "name"=GREATEST("name",$1) |
<name | "name"=LEAST("name",$1) |
!name | "name"=NOT "name" |
=name | "name"=value, the value is raw SQL |
#name | The same as =, but insert() leaves the key out |
In insert() (also the insert of an upsert) the character is removed: the column gets the value (0 when it is empty), ! inserts FALSE and = inserts the raw SQL. Keys without an operator are sent as parameters.
DATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);
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);
type
callback(err, response)
What each operation of the QueryBuilder returns on PostgreSQL.
callback(err, response)| Operation | Response |
|---|---|
find() | An array of rows. |
read() | One row or null. |
list() | { items, count, page, limit, pages }; the adapter runs the page and SELECT COUNT(1). |
check() | true or false. |
count() | A number. |
scalar() | A number for sum, avg, min, max and count; rows { key, value } for group. |
insert() | The number of inserted rows, the value of the primarykey() column, or the inserted row with returning(). |
update() | The number of changed rows, an array of rows with returning(), one row with returning() and first(). |
remove() | The number of removed rows, or an array of rows with returning(). |
query() | An array of rows; undefined for SQL with several statements. |
truncate(), drop() | Run TRUNCATE TABLE … RESTART IDENTITY and DROP TABLE …. |
Values: boolean is a Boolean; smallint, integer, real, double precision and numeric are numbers; bigint is a String; json and jsonb are parsed (texts in the ISO date format become Date objects); date, timestamp and timestamptz are Date objects; bytea is a Buffer; arrays are arrays; other types are strings.
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 }
type
err
The error of a failed query.
errAn error of the server is an Error with the message of PostgreSQL and the fields the server sends: code (the SQLSTATE code), severity, detail, hint, position, where, schema, table, column, datatype, constraint and routine. Errors of the connection are Error objects of Node.js (ECONNREFUSED…) or Connection timeout, The server does not support SSL connections and Pool is closed.
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.
});
method
PG_ESCAPE(value)
Escapes a value for a PostgreSQL query.
PG_ESCAPE(value)| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
Returns String The SQL literal.
Returns the value as an SQL literal, the same way the adapter writes the values of conditions: a string in single quotes ('O''Brien', with the prefix E when it contains a backslash), a number and a boolean as they are, null and undefined as null, an array as ARRAY[…], a Date as 'yyyy-MM-dd HH:mm:ss' and an object as its JSON in quotes. A function is called and its result is escaped. The global exists after the first DATA.init().
DATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE("Kid's watch")).callback(console.log);
method
require('total5/client-postgresql')
The PostgreSQL client without the QueryBuilder.
require('total5/client-postgresql')Returns Object The module.
The module exports connect(), pool(), types and the classes Client and Pool. The adapter of DATA.init() uses the same module, so a change in types applies to both.
const PG = require('total5/client-postgresql');
method
PG.connect(options, callback)
Opens one connection.
PG.connect(options, callback)| Parameter | Type | Description |
|---|---|---|
options |
String|Object |
The connection string or the options. |
callback |
Function |
function(err, client). |
Returns Client
options is a connection string or an object with connectionString, host, port, user, password, database, ssl (true, an sslmode value or an object of options for tls.connect()), timeout (milliseconds) and name (the application name). Close the connection with client.end() or client.close().
const PG = require('total5/client-postgresql');
PG.connect(CONF.database, async function(err, client) {
var response = await client.query('SELECT $1::int + 1 AS value', [41]);
console.log(response.rows); // [ { value: 42 } ]
client.close();
});
method
PG.pool(options, [max])
Creates a pool of connections.
PG.pool(options, [max])| Parameter | Type | Description |
|---|---|---|
options |
String|Object |
The connection string or the options of PG.connect(). |
max? |
Number |
The maximum number of connections. Default: 10 |
Returns Pool
The pool opens up to max connections (default 10) and reuses them. When options is an object, max and idle (milliseconds an idle connection stays open, default 10000) can be in it too. A connection that comes back in an open transaction is closed.
const PG = require('total5/client-postgresql');
const pool = PG.pool(CONF.database, 5);
pool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {
console.log(response.rows);
});
method
pool.connect(callback)
Borrows a connection from the pool.
pool.connect(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(err, client, release). |
The callback gets the connection and a release function that returns it to the pool (client.release() does the same). Use it for several queries on one connection, for example a transaction.
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();
}
});
method
client.query(sql, [params], [callback])
Runs a query on the connection.
client.query(sql, [params], [callback])| Parameter | Type | Description |
|---|---|---|
sql |
String |
The SQL. |
params? |
Array |
The values of the parameters. |
callback? |
Function |
function(err, response). |
Returns Promise Without callback. The response is { command, rowCount, rows, fields }.
The parameters are $1, $2… in the SQL. Without parameters the SQL can have several statements; the response is then an array with one result for each statement. 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 for a json or jsonb parameter. Without callback it returns a promise. pool.query() takes the same arguments and runs the query on a free connection of the pool.
client.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {
console.log(response.command, response.rowCount, response.rows);
});
method
client.close([callback])
Returns the connection to its pool or closes it.
client.close([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when it is done. |
A connection of a pool goes back to the pool (alias client.release()). Other connections are closed after their pending queries, like client.end([callback]).
client.close();
method
pool.end([callback])
Closes all connections of the pool.
pool.end([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when all connections are closed. |
Idle connections close at once, busy ones when they are released. Waiting and later requests fail with Pool is closed.
pool.end(() => console.log('closed'));
property
PG.types
The parsers of values by the OID of the type.
PG.typesReturns Object
An object { oid: function(text) }. A type without a parser is returned as a string. bigint (OID 20) has no parser because its values do not always fit into a JavaScript number.
const PG = require('total5/client-postgresql');
PG.types[20] = value => +value;