Members

(constant) queryResult :number

Query Result Mask.

Binary mask that represents the result expected from queries. It is used in the generic query method, as well as method func.

The mask is always the last optional parameter, which defaults to queryResult.any.

Any combination of flags is supported, except for one + many.

The type is available from the library's root: pgp.queryResult.

Type:
  • number
Properties:
Name Type Description
one number

Single row is expected.

many number

One or more rows expected.

none number

Expecting no rows.

any number

many|none - any result is expected.

Source:
See:

Type Definitions

EventContext

This common type is used for the following events: query, receive, error, task and transact.

Properties:
Name Type Description
cn string | object

Set only for event error, and only when the error is connection-related.

It is a safe copy of the connection string/object that was used when initializing db - the database instance.

If the original connection contains a password, the safe copy contains it masked with symbol #, so the connection can be logged safely, without exposing the password.

dc *

Database Context that was used when creating the database object (see Database). It is set for all events.

query string | object

Query string/object that was passed into the query method. This property is only set during events query, receive and error (only when the error is query-related).

client external:Client

pg.Client object that represents the connection. It is set for all events, except for event error when it is connection-related.

params *

Formatting parameters for the query.

It is set only for events query, receive and error, and only when it is needed for logging. This library takes an extra step in figuring out when formatting parameters are of any value to the event logging:

  • when an error occurs related to the query formatting, event error is sent with the property set.
  • when initialization parameter pgFormat is used, and all query formatting is done within the PG library, events query and receive will have this property set also, since this library no longer handles the query formatting.

When this parameter is not set, it means one of the two things:

  • there were no parameters passed into the query method;
  • property query of this object already contains all the formatting values in it, so logging only the query is sufficient.
ctx TaskContext

Task/Transaction Context object.

This property is always set for events task and transact, while for events query, receive and error it is only set when they occur inside a task or transaction.

Source:

TaskContext

Task/Transaction Context used via property ctx inside tasks (method Database.task) and transactions (method Database.tx).

Properties context, connected, parent, level, dc, isTX, tag, start and isFresh are set just before the operation has started, while properties finish, duration, success and result are set immediately after the operation has finished.

Properties:
Name Type Description
context *

If the operation was invoked with a calling context - task.call(context,...) or tx.call(context,...), this property is set with the context that was passed in. Otherwise, the property doesn't exist.

dc *

Database Context that was passed into the Database object during construction.

isTX boolean

Indicates whether this operation is a transaction (as opposed to a regular task).

duration number

Added in v6.2.0

Number of milliseconds consumed by the operation.

Set after the operation has finished, it is simply a shortcut for finish - start.

level number

Added in v6.2.0

Task nesting level, starting from 0, counting both regular tasks and transactions.

txLevel number

Added in v6.2.0

Transaction nesting level, starting from 0. Transactions on level 0 use BEGIN/COMMIT/ROLLBACK, while transactions on nested levels use the corresponding SAVEPOINT commands.

This property exists only within the context of a transaction (isTX = true).

parent TaskContext

Added in v6.2.1

Parent task/transaction context, or null when it is top-level.

connected boolean

Added in v6.2.1

Indicates when the task/transaction acquired the connection on its own (connected = true), and will release it once the operation has finished. When the value is false, the operation is reusing an existing connection.

tag *

Tag value as it was passed into the task. See methods task and tx.

start Date

Date/Time of when this operation started the execution.

isFresh boolean

Indicates when a fresh physical connection is being used.

finish Date

Once the operation has finished, this property is set to the Data/Time of when it happened.

success boolean

Once the operation has finished, this property indicates whether it was successful.

result *

Once the operation has finished, this property contains the result, depending on property success:

  • data resolved by the operation, if success = true
  • error / rejection reason, if success = false
Source:

Events

connect

Global notification of acquiring a new database connection from the connection pool, i.e. a virtual connection.

However, for direct calls to method Database.connect with parameter {direct: true}, this event represents a physical connection.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
client external:Client

pg.Client object that represents the connection.

dc *

Database Context that was used when creating the database object (see Database).

isFresh boolean

It indicates when it is a fresh physical connection:

  • true - the physical connection just has been allocated
  • false - the connection has been used previously

NOTE:

This parameter is always true for direct connections (created by calling Database.connect with parameter {direct: true}).

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    connect: (client, dc, isFresh) => {
        const cp = client.connectionParameters;
        console.log('Connected to database:', cp.database);
    }

};

disconnect

Global notification of releasing a database connection back to the connection pool, i.e. releasing the virtual connection.

However, when releasing a direct connection (created by calling Database.connect with parameter {direct: true}), this event represents a physical disconnection.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
client external:Client

pg.Client object that represents connection with the database.

dc *

Database Context that was used when creating the database object (see Database).

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    disconnect: (client, dc) => {
       const cp = client.connectionParameters;
       console.log('Disconnecting from database:', cp.database);
    }

};

error

Global notification of every error encountered by this library.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
err *

The error encountered, of the same value and type as it was reported.

e EventContext

Event Context Object.

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    error: (err, e) => {

        if (e.cn) {
            // this is a connection-related error
            // cn = safe connection details passed into the library:
            //      if password is present, it is masked by #
        }

        if (e.query) {
            // query string is available
            if (e.params) {
                // query parameters are available
            }
        }

        if (e.ctx) {
            // occurred inside a task or transaction
        }
      }
};

extend

Extends Database protocol with custom methods and properties.

Override this event to extend the existing access layer with your own functions and properties best suited for your application.

The extension thus becomes available across all access layers:

  • Within the root/default database protocol;
  • Inside transactions, including nested ones;
  • Inside tasks, including nested ones.

All pre-defined methods and properties are read-only, so you will get an error, if you try overriding them.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
obj object

Protocol object to be extended.

dc *

Database Context that was used when creating the Database object.

Source:
See:
Examples
// In the example below we extend the protocol with function `addImage`
// that will insert one binary image and resolve with the new record id.

const initOptions = {

    // pg-promise initialization options...

    extend: (obj, dc) => {
        // dc = database context;
        obj.addImage = data => {
            // adds a new image and resolves with its record id:
            return obj.one('INSERT INTO images(data) VALUES($1) RETURNING id', data, a => a.id);
        }
    }
};
// It is best to extend the protocol by adding whole entity repositories to it as shown in the following example.
// For a comprehensive example see https://github.com/vitaly-t/pg-promise-demo

class UsersRepository {
    constructor(rep, pgp) {
        this.rep = rep;
        this.pgp = pgp;
    }

    add(name) {
        return this.rep.one('INSERT INTO users(name) VALUES($1) RETURNING id', name, a => a.id);
    }

    remove(id) {
        return this.rep.none('DELETE FROM users WHERE id = $1', id);
    }
}

// Overriding 'extend' event;
const initOptions = {

    // pg-promise initialization options...

    extend: (obj, dc) => {
        // dc = database context;
        obj.users = new UsersRepository(obj, pgp);
        // You can set different repositories based on `dc`
    }
};

// Usage example:
db.users.add('John', true)
    .then(id => {
        // user added successfully, id = new user's id
    })
    .catch(error => {
        // failed to add the user;
    });

query

Global notification of a query that's about to execute.

Notification happens just before the query execution. And if the handler throws an error, the query execution will be rejected with that error.

Parameters:
Name Type Description
e EventContext

Event Context Object.

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    query: e => {
        console.log('QUERY:', e.query);
    }
};

receive

Global notification of any data received from the database, coming from a regular query or from a stream.

The event is fired before the data reaches the client, and only when receiving 1 or more records.

This event notification serves two purposes:

  • Providing selective data logging for debugging;
  • Pre-processing data before it reaches the client.

NOTES:

  • If you alter the size of data directly or through the result object, it may affect QueryResultMask validation for regular queries, which is executed right after this notification.
  • When adding data pre-processing, you should consider possible performance penalty this may bring.
  • If the event handler throws an error, the original request will be rejected with that error.
Parameters:
Name Type Description
data array

A non-empty array of received data objects/rows.

If any of those objects are modified during notification, the client will receive the modified data.

result object
  • original Result object, if the data comes from a regular query, in which case data = result.rows.
  • undefined when the data comes from a stream.
e EventContext

Event Context Object.

Source:
Example
// Example below shows the fastest way to camelize all column names:

const initOptions = {

    // pg-promise initialization options...

    receive: (data, result, e) => {
        camelizeColumns(data);
    }
};

function camelizeColumns(data) {
    const tmp = data[0];
    for (let prop in tmp) {
        const camel = pgp.utils.camelize(prop);
        if (!(camel in tmp)) {
            for (let i = 0; i < data.length; i++) {
                const d = data[i];
                d[camel] = d[prop];
                delete d[prop];
            }
        }
    }
}

task

Global notification of a task start / finish events, as executed via Database.task.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
e EventContext

Event Context Object.

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    task: e => {
        if (e.ctx.finish) {
            // this is a task->finish event;
            console.log('Duration:', e.ctx.duration);
            if (e.ctx.success) {
                // e.ctx.result = resolved data;
            } else {
                // e.ctx.result = error/rejection reason;
            }
        } else {
            // this is a task->start event;
            console.log('Start Time:', e.ctx.start);
        }
    }
};

transact

Global notification of a transaction start / finish events, as executed via Database.tx.

The library will suppress any error thrown by the handler and write it into the console.

Parameters:
Name Type Description
e EventContext

Event Context Object.

Source:
Example
const initOptions = {

    // pg-promise initialization options...

    transact: e => {
        if (e.ctx.finish) {
            // this is a transaction->finish event;
            console.log('Duration:', e.ctx.duration);
            if (e.ctx.success) {
                // e.ctx.result = resolved data;
            } else {
                // e.ctx.result = error/rejection reason;
            }
        } else {
            // this is a transaction->start event;
            console.log('Start Time:', e.ctx.start);
        }
    }
};