Namespace for query-formatting generators, available as pgp.helpers, after initializing the library.
It unifies the approach to generating multi-row INSERT
/ UPDATE
queries with the single-row ones.
See also: Performance Boost.
Properties:
Name | Type | Description |
---|---|---|
TableName |
function | TableName class constructor. |
_TN |
function | _TN Table-Name conversion function. |
ColumnSet |
function | ColumnSet class constructor. |
Column |
function | Column class constructor. |
insert |
function | insert static method. |
update |
function | update static method. |
values |
function | values static method. |
sets |
function | sets static method. |
concat |
function | concat static method. |
- Source:
Classes
Methods
(static) _TN(path) → {Table}
Table-Name helper function, to convert any "schema.table"
string
into {schema, table}
object. It also works as a template-tag function.
Parameters:
Name | Type | Description |
---|---|---|
path |
string | TemplateStringsArray | Table-name path, as a simple string or a template string (with parameters). |
- Source:
- See:
Returns:
- Type
- Table
Example
const {ColumnSet, _TN} = pgp.helpers;
// Using as a regular function:
const cs1 = new ColumnSet(['id', 'name'], {table: _TN('schema.table')});
// Using as a template-tag function:
const schema = 'schema';
const cs2 = new ColumnSet(['id', 'name'], {table: _TN`${schema}.table`});
(static) concat(queries) → {string}
Formats and concatenates multiple queries into a single query string.
Before joining the queries, the method does the following:
- Formats each query, if
values
are provided; - Removes all leading and trailing spaces, tabs and semi-colons;
- Automatically skips all empty queries.
Parameters:
Name | Type | Description |
---|---|---|
queries |
array.<(string|helpers.QueryFormat|QueryFile)> | Array of mixed-type elements:
|
- Source:
Returns:
Concatenated string with all queries.
- Type
- string
Example
const pgp = require('pg-promise')();
const qf1 = new pgp.QueryFile('./query1.sql', {minify: true});
const qf2 = new pgp.QueryFile('./query2.sql', {minify: true});
const query = pgp.helpers.concat([
{query: 'INSERT INTO Users(name, age) VALUES($1, $2)', values: ['John', 23]}, // QueryFormat-like object
{query: qf1, values: [1, 'Name']}, // QueryFile with formatting parameters
'SELECT count(*) FROM Users', // a simple-string query,
qf2 // direct QueryFile object
]);
// query = concatenated string with all the queries
(static) insert(data, columnsopt, tableopt) → {string}
Generates an INSERT
query for either one object or an array of objects.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
data |
object | Array.<object> | An insert object with properties for insert values, or an array of such objects. When When When |
|
columns |
array | helpers.Column | helpers.ColumnSet |
<optional> |
Set of columns to be inserted. It is optional when When When the final ColumnSet is empty (no columns in it), the method will throw
Error = |
table |
helpers.TableName | Table | string |
<optional> |
Destination table. It is normally a required parameter. But when |
- Source:
- See:
Returns:
An INSERT
query string.
- Type
- string
Examples
const pgp = require('pg-promise')({
capSQL: true // if you want all generated SQL capitalized
});
const {insert} = pgp.helpers;
const dataSingle = {val: 123, msg: 'hello'};
const dataMulti = [{val: 123, msg: 'hello'}, {val: 456, msg: 'world!'}];
// Column details can be taken from the data object:
insert(dataSingle, null, 'my-table');
//=> INSERT INTO "my-table"("val","msg") VALUES(123,'hello')
// Column details are required for a multi-row `INSERT`:
const {insert} = pgp.helpers;
insert(dataMulti, ['val', 'msg'], 'my-table');
//=> INSERT INTO "my-table"("val","msg") VALUES(123,'hello'),(456,'world!')
// Column details from a reusable ColumnSet (recommended for performance):
const {ColumnSet, insert} = pgp.helpers;
const cs = new ColumnSet(['val', 'msg'], {table: 'my-table'});
insert(dataMulti, cs);
//=> INSERT INTO "my-table"("val","msg") VALUES(123,'hello'),(456,'world!')
(static) sets(data, columnsopt) → {string}
Generates a string of comma-separated value-set statements from a single object: col1=val1, col2=val2, ...
,
to be used as part of a query.
Since it is to be used as part of UPDATE
queries, Column properties cnd
and skip
apply.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
data |
object | A simple, non-null and non-array source object. If it is anything else, the method will throw TypeError = |
|
columns |
array | helpers.Column | helpers.ColumnSet |
<optional> |
Columns for which to set values. When not specified, properties of the When no effective columns are found, an empty string is returned. |
- Source:
- See:
Returns:
- comma-separated value-set statements for the
data
object - an empty string, if no effective columns found
- Type
- string
Examples
const pgp = require('pg-promise')();
const data = {id: 1, val: 123, msg: 'hello'};
// Properties can be pulled automatically from the object:
pgp.helpers.sets(data);
//=> "id"=1,"val"=123,"msg"='hello'
// Column details from a reusable ColumnSet (recommended for performance);
// NOTE: Conditional columns (start with '?') are skipped:
const {ColumnSet, sets} = pgp.helpers;
const cs = new ColumnSet(['?id','val', 'msg']);
sets(data, cs);
//=> "val"=123,"msg"='hello'
(static) update(data, columnsopt, tableopt, optionsopt) → {*}
Generates a simplified UPDATE
query for either one object or an array of objects.
The resulting query needs a WHERE
clause to be appended to it, to specify the update logic.
This is to allow for update conditions of any complexity that are easy to add.
Parameters:
Name | Type | Attributes | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data |
object | Array.<object> | An update object with properties for update values, or an array of such objects. When When When |
|||||||||||||||||||||
columns |
array | helpers.Column | helpers.ColumnSet |
<optional> |
Set of columns to be updated. It is optional when When When the final ColumnSet is empty (no columns in it), the method will throw
Error = |
||||||||||||||||||||
table |
helpers.TableName | Table | string |
<optional> |
Table to be updated. It is normally a required parameter. But when |
||||||||||||||||||||
options |
Object |
<optional> |
An object with formatting options for multi-row Properties
|
- Source:
- See:
Returns:
An UPDATE
query string that needs a WHERE
condition appended.
If it results in an empty update, and option emptyUpdate
was passed in, then the method returns the value
to which the option was set.
- Type
- *
Examples
const pgp = require('pg-promise')({
capSQL: true // if you want all generated SQL capitalized
});
const {update} = pgp.helpers;
const dataSingle = {id: 1, val: 123, msg: 'hello'};
const dataMulti = [{id: 1, val: 123, msg: 'hello'}, {id: 2, val: 456, msg: 'world!'}];
// Although column details can be taken from the data object, it is not
// a likely scenario for an update, unless updating the whole table:
update(dataSingle, null, 'my-table');
//=> UPDATE "my-table" SET "id"=1,"val"=123,"msg"='hello'
// A typical single-object update:
// Dynamic conditions must be escaped/formatted properly:
const condition = pgp.as.format(' WHERE id = ${id}', dataSingle);
update(dataSingle, ['val', 'msg'], 'my-table') + condition;
//=> UPDATE "my-table" SET "val"=123,"msg"='hello' WHERE id = 1
// Column details are required for a multi-row `UPDATE`;
// Adding '?' in front of a column name means it is only for a WHERE condition:
update(dataMulti, ['?id', 'val', 'msg'], 'my-table') + ' WHERE v.id = t.id';
//=> UPDATE "my-table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
// AS v("id","val","msg") WHERE v.id = t.id
// Column details from a reusable ColumnSet (recommended for performance):
const {ColumnSet, update} = pgp.helpers;
const cs = new ColumnSet(['?id', 'val', 'msg'], {table: 'my-table'});
update(dataMulti, cs) + ' WHERE v.id = t.id';
//=> UPDATE "my-table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
// AS v("id","val","msg") WHERE v.id = t.id
// Using parameter `options` to change the default alias names:
update(dataMulti, cs, null, {tableAlias: 'X', valueAlias: 'Y'}) + ' WHERE Y.id = X.id';
//=> UPDATE "my-table" AS X SET "val"=Y."val","msg"=Y."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
// AS Y("id","val","msg") WHERE Y.id = X.id
// Handling an empty update
const {ColumnSet, update} = pgp.helpers;
const cs = new ColumnSet(['?id', '?name'], {table: 'tt'}); // no actual update-able columns
const result = update(dataMulti, cs, null, {emptyUpdate: 123});
if(result === 123) {
// We know the update is empty, i.e. no columns that can be updated;
// And it didn't throw because we specified `emptyUpdate` option.
}
(static) values(data, columnsopt) → {string}
Generates a string of comma-separated value groups from either one object or an array of objects, to be used as part of a query:
- from a single object:
(val_1, val_2, ...)
- from an array of objects:
(val_11, val_12, ...), (val_21, val_22, ...)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
data |
object | Array.<object> | A source object with properties as values, or an array of such objects. If it is anything else, the method will throw TypeError = When When |
|
columns |
array | helpers.Column | helpers.ColumnSet |
<optional> |
Columns for which to return values. It is optional when When the final ColumnSet is empty (no columns in it), the method will throw
Error = |
- Source:
- See:
Returns:
- comma-separated value groups, according to
data
- an empty string, if
data
is an empty array
- Type
- string
Examples
const pgp = require('pg-promise')();
const dataSingle = {val: 123, msg: 'hello'};
const dataMulti = [{val: 123, msg: 'hello'}, {val: 456, msg: 'world!'}];
// Properties can be pulled automatically from a single object:
pgp.helpers.values(dataSingle);
//=> (123,'hello')
// Column details are required when using an array of objects:
pgp.helpers.values(dataMulti, ['val', 'msg']);
//=> (123,'hello'),(456,'world!')
// Column details from a reusable ColumnSet (recommended for performance):
const {ColumnSet, values} = pgp.helpers;
const cs = new ColumnSet(['val', 'msg']);
values(dataMulti, cs);
//=> (123,'hello'),(456,'world!')
Type Definitions
ColumnConfig
A simple structure with column details, to be passed into the Column constructor for initialization.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
name |
string | Destination column name + source property name (if |
|
prop |
string |
<optional> |
Source property name, if different from the column's name. It must adhere to JavaScript syntax for variables. It is ignored when it is the same as |
mod |
string |
<optional> |
Formatting modifier, as supported by method as.format: |
cast |
string |
<optional> |
Server-side type casting. Leading |
cnd |
boolean |
<optional> |
Conditional column flag. Used by methods update and sets, ignored by methods insert and
values. It indicates that the column is reserved for a It can be set from a string initialization, by adding |
def |
* |
<optional> |
Default value for the property, to be used only when the source object doesn't have the property.
It is ignored when property |
init |
helpers.initCB |
<optional> |
Override callback for the value. |
skip |
helpers.skipCB |
<optional> |
An override for skipping columns dynamically. Used by methods update (for a single object) and sets, ignored by methods insert and values. It is also ignored when conditional flag |
- Source:
QueryFormat
A simple structure of parameters to be passed into method as.format exactly as they are, used by helpers.concat.
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
query |
string | value | object | A query string or a value/object that implements Custom Type Formatting, to be formatted according to |
|
values |
array | object | value |
<optional> |
Query-formatting values. |
options |
object |
<optional> |
Query-formatting options, as supported by method as.format. |
- Source:
- See:
initCB(col) → {*}
A callback function type used by parameter init
within ColumnConfig.
It works as an override for the corresponding property value in the source
object.
The function is called with this
set to the source
object.
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
col |
* | Column-to-property descriptor. Properties
|
- Source:
Returns:
The new value to be used for the corresponding column.
- Type
- *
skipCB(col) → {boolean}
A callback function type used by parameter skip
within ColumnConfig.
It is to dynamically determine when the property with specified name
in the source
object is to be skipped.
The function is called with this
set to the source
object.
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
col |
* | Column-to-property descriptor. Properties
|
- Source:
Returns:
A truthy value that indicates whether the column is to be skipped.
- Type
- boolean