---
title: PostgreSQL
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/postgresql/
updated: 2026-11-19T20:13:56.297Z
---

# PostgreSQL

> DATA.init(), the connection string, the SQL results and errors, and the PostgreSQL client.

`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](../../reference/querybuilder/). An introduction with examples is in the guide [PostgreSQL](../../guides/postgresql/).

## API

### DATA.init([name], [connection], [onerror])

Type: `method`

Registers a PostgreSQL connection for the QueryBuilder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | The connection name. |
| `connection` | `String` | no |  | The connection string: `postgresql://user:password@host:port/database?options`. See the connection string. |
| `onerror` | `Function` | no |  | `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.

Example: In definitions/db.js
```js
DATA.init('default', CONF.database + '?pooling=10');
```

Example: A second connection
```js
DATA.init('logs', CONF.database_logs);
DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);
```

Example: Own error handling
```js
DATA.init('default', CONF.database + '?pooling=10', function(message) {
	console.log('SQL error:', message);
});
```

### postgresql://user:password@host:port/database?options

Type: `type`

The URL of the database and its options.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `pooling` | `Number` | no |  | 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` | no |  | 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` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` or `verify-full`. |
| `ssl` | `Boolean` | no |  | `true` or `1` is the same as `sslmode=require`. |
| `connect_timeout` | `Number` | no |  | Seconds to wait for the connection. Then the query fails with `Connection timeout`. |
| `application_name` | `String` | no |  | The name of the connections in `pg_stat_activity`. |
| `host` | `String` | no |  | Replaces the host of the URL. A value that starts with `/` is the directory of a Unix socket. |
| `port, user, password, dbname` | `String` | no |  | 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.

Example: In the config file
```text
database : postgresql://user:password@localhost:5432/eshop
```

Example: Options
```js
DATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');
```

### { '+stock': 5, '=dtupdated': 'NOW()' }

Type: `type`

Keys of the update() payload that change the value in the database.

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.

Example: Stock
```js
DATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);
```

Example: A daily counter (upsert)
```js
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);
```

### callback(err, response)

Type: `type`

What each operation of the QueryBuilder returns on PostgreSQL.

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

Example: Returning
```js
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 }
```

### err

Type: `type`

The error of a failed query.

An 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`.

Example: A duplicate key
```js
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.
});
```

### PG_ESCAPE(value)

Type: `method`

Escapes a value for a PostgreSQL query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | 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()`.

Example: Escaping
```js
DATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE("Kid's watch")).callback(console.log);
```

### require('total5/client-postgresql')

Type: `method`

The PostgreSQL client without the QueryBuilder.

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.

Example: Require
```js
const PG = require('total5/client-postgresql');
```

### PG.connect(options, callback)

Type: `method`

Opens one connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `String|Object` | yes |  | The connection string or the options. |
| `callback` | `Function` | yes |  | `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()`.

Example: One connection
```js
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();
});
```

### PG.pool(options, [max])

Type: `method`

Creates a pool of connections.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `String|Object` | yes |  | The connection string or the options of `PG.connect()`. |
| `max` | `Number` | no | `10` | The maximum number of connections. |

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.

Example: A pool
```js
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);
});
```

### pool.connect(callback)

Type: `method`

Borrows a connection from the pool.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `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.

Example: A transaction
```js
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(sql, [params], [callback])

Type: `method`

Runs a query on the connection.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sql` | `String` | yes |  | The SQL. |
| `params` | `Array` | no |  | The values of the parameters. |
| `callback` | `Function` | no |  | `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.

Example: Query
```js
client.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {
	console.log(response.command, response.rowCount, response.rows);
});
```

### client.close([callback])

Type: `method`

Returns the connection to its pool or closes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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])`.

Example: Close
```js
client.close();
```

### pool.end([callback])

Type: `method`

Closes all connections of the pool.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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`.

Example: End
```js
pool.end(() => console.log('closed'));
```

### PG.types

Type: `property`

The parsers of values by the OID of the type.

Returns: `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.

Example: bigint as a number
```js
const PG = require('total5/client-postgresql');
PG.types[20] = value => +value;
```
