
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
ts-postgres
Advanced tools
Non-blocking PostgreSQL client for Node.js written in TypeScript.
To install the latest version of this library:
$ npm install ts-postgres@latest
The client uses an async/await-based programming model.
import { Client } from 'ts-postgres';
async function main() {
const client = new Client();
await client.connect();
const stream = client.query(
`SELECT 'Hello ' || $1 || '!' AS message`,
['world']
);
for await (const row of stream) {
console.log(row.get('message')); // 'Hello world!'
}
await client.end();
}
main()
The example above uses the variable stream
to indicate that the result set is made available as it arrives on the connection. But we'll often want to just wait for the entire result set to arrive before starting to process the data.
const result = await client.query('select generate_series(1, 10)');
If the query fails, waiting for the result will throw an exception.
Whether we're operating on a stream or an already waited for result set, the iterator interface provides the most high-level row interface. This also applies when using the spread operator:
const rows = [...result];
Each row provides direct access to values through its data
attribute, but we can also get a value by name using the get(name)
method.
for (const row of rows) {
console.log('The number is: ' + row.get('i')); // 1, 2, 3, ...
}
Note that values are polymorphic and need to be explicitly cast to a concrete type such as number
or string
.
This interface is available on the already waited for result object. It makes data available in the rows
attribute as an array of arrays (of values).
for (const row of result.rows) {
console.log('The number is: ' + row[0]); // 1, 2, 3, ...
}
This is the most efficient way to work with result data. Column names are available as the names
attribute of a result.
The query command accepts a single query only. If you need to send multiple queries, just call the method multiple times. For example, to send an update command in a transaction:
client.query('begin');
client.query('update ...');
await client.query('commit');
The queries are sent back to back over the wire, but PostgreSQL still processes them one at a time, in the order they were sent (first in, first out).
You can prepare a query and subsequently execute it multiple times. This is also known as a "prepared statement".
const statement = await client.prepare(
`SELECT 'Hello ' || $1 || '!' AS message`
);
for await (const row of statement.execute(['world'])) {
console.log(row.get('message')); // 'Hello world!'
}
When the prepared statement is no longer needed, it should be closed to release the resource.
await statement.close();
Prepared statements can be used (executed) multiple times, even concurrently.
Queries with parameters are sent using the prepared statement variant of the extended query protocol. In this variant, the type of each parameter is determined prior to parameter binding, ensuring that values are encoded in the correct format.
If a query has no parameters, it uses the portal variant which saves a round trip.
The copy commands are not supported.
How do I set up a pool of connections? You can for example use the generic-pool library:
import { createPool } from 'generic-pool';
const pool = createPool({
create: async () => {
const client = new Client();
return client.connect().then(() => {
client.on('error', console.log);
return client;
});
},
destroy: async (client: Client) => {
return client.end().then(() => { })
},
validate: (client: Client) => {
return Promise.resolve(!client.closed);
}
}, { testOnBorrow: true });
pool.use(...)
Use the following environment variable to run tests in "benchmark" mode.
$ NODE_ENV=benchmark npm run test
ts-postgres is free software. If you encounter a bug with the library please open an issue on the GitHub repo.
Copyright (c) 2018-2019 Malthe Borch (mborch@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
v1.1.2 (2019-12-28)
FAQs
PostgreSQL client in TypeScript
The npm package ts-postgres receives a total of 6,850 weekly downloads. As such, ts-postgres popularity was classified as popular.
We found that ts-postgres demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.