Skip to content

Connection Syntax

Vitaly Tomilov edited this page Jul 31, 2021 · 101 revisions

Connection details syntax to be used when creating a Database object.

Most of the connection parameters are optional. See their default values. Please note that overriding defaults via pg.defaults does not work for all parameters (see #699), and should be avoided. Instead, you should pass those parameters with configuration object, as below.

Configuration Object

  • string host - server name or IP address
  • number port - server port number
  • string database - database name
  • string user - user name
  • string password - user password, or a function that returns one
  • boolean ssl - use SSL (it also can be an ISSLConfig-like object)
  • boolean binary - binary result mode
  • string client_encoding
  • string application_name
  • string fallback_application_name
  • number idleTimeoutMillis - lifespan for unused connections
  • number max - maximum size of the connection pool
  • number query_timeout - query execution timeout
  • boolean keepAlive - keep TCP alive
  • boolean allowExitOnIdle - let process exit when pool is idle

etc, there are more advanced parameters - reapIntervalMillis, returnToHead, poolLog, parseInputDatesAsUTC, rows and statement_timeout. You can check the driver for their usage.

Example:

const cn = {
    host: 'localhost',
    port: 5432,
    database: 'my-database-name',
    user: 'user-name',
    password: 'user-password',
    max: 30 // use up to 30 connections

    // "types" - in case you want to set custom type parsers on the pool level
};

const db = pgp(cn);

Connection String

General syntax for connection strings is as follows:

postgres://username:password@host:port/database?ssl=false&application_name=name
&fallback_application_name=name&client_encoding=encoding

It can be passed in either directly:

const db = pgp('postgres://john:pass123@localhost:5432/products');

or as a parameter within configuration object (which then combines the values):

const cn = {
    connectionString: 'postgres://...',
    max: 30
};

const db = pgp(cn);

The default connection strings are limited by what pg-connection-string can support, which is used by the driver internally.

But you can use the generic connection-string library instead, to let it parse any parameters you want, and then generate your configuration object from those, as shown in the examples.