All Projects → malthe → Ts Postgres

malthe / Ts Postgres

Licence: other
Non-blocking PostgreSQL client for Node.js written in TypeScript.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Ts Postgres

Parse Server
API server module for Node/Express
Stars: ✭ 19,165 (+37478.43%)
Mutual labels:  hacktoberfest, postgres
Prest
PostgreSQL ➕ REST, low-code, simplify and accelerate development, ⚡ instant, realtime, high-performance on any Postgres application, existing or new
Stars: ✭ 3,023 (+5827.45%)
Mutual labels:  hacktoberfest, postgres
Grafana
The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
Stars: ✭ 45,930 (+89958.82%)
Mutual labels:  hacktoberfest, postgres
Zws
Shorten URLs using invisible spaces.
Stars: ✭ 780 (+1429.41%)
Mutual labels:  hacktoberfest, postgres
Graphql Engine
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
Stars: ✭ 24,845 (+48615.69%)
Mutual labels:  hacktoberfest, postgres
Deno Nessie
A modular Deno library for PostgreSQL, MySQL, MariaDB and SQLite migrations
Stars: ✭ 381 (+647.06%)
Mutual labels:  hacktoberfest, postgres
Sqlcell
SQLCell is a magic function for the Jupyter Notebook that executes raw, parallel, parameterized SQL queries with the ability to accept Python values as parameters and assign output data to Python variables while concurrently running Python code. And *much* more.
Stars: ✭ 145 (+184.31%)
Mutual labels:  hacktoberfest, postgres
Check postgres
Nagios check_postgres plugin for checking status of PostgreSQL databases
Stars: ✭ 438 (+758.82%)
Mutual labels:  hacktoberfest, postgres
Migrate
Database migrations. CLI and Golang library.
Stars: ✭ 7,712 (+15021.57%)
Mutual labels:  hacktoberfest, postgres
Dbdpg
Perl Postgres driver DBD::Pg aka dbdpg
Stars: ✭ 38 (-25.49%)
Mutual labels:  hacktoberfest, postgres
Tiled
Flexible level editor
Stars: ✭ 8,411 (+16392.16%)
Mutual labels:  hacktoberfest
Sympy
A computer algebra system written in pure Python
Stars: ✭ 8,688 (+16935.29%)
Mutual labels:  hacktoberfest
Cloudsplaining
Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report.
Stars: ✭ 1,057 (+1972.55%)
Mutual labels:  hacktoberfest
Flutter Guide
📚 Flutter Guide on becoming a Master Flutterista
Stars: ✭ 51 (+0%)
Mutual labels:  hacktoberfest
Awesomo
Cool open source projects written in C, C++, Clojure, Lisp, Elixir, Erlang, Elm, Golang, Haskell, JavaScript, Lua, OCaml, Python, R, Ruby, Rust, Scala, etc.
Stars: ✭ 8,237 (+16050.98%)
Mutual labels:  hacktoberfest
Redux Query
A library for managing network state in Redux
Stars: ✭ 1,055 (+1968.63%)
Mutual labels:  hacktoberfest
Cockatrice
A cross-platform virtual tabletop for multiplayer card games
Stars: ✭ 1,053 (+1964.71%)
Mutual labels:  hacktoberfest
Laravel Packager
A cli tool for creating Laravel packages
Stars: ✭ 1,049 (+1956.86%)
Mutual labels:  hacktoberfest
Curriculum
Workshop documentation and scripts
Stars: ✭ 50 (-1.96%)
Mutual labels:  hacktoberfest
R6 Operator Counters
A website with a graph visualisation of how operators counter each other in Rainbow Six Siege.
Stars: ✭ 51 (+0%)
Mutual labels:  hacktoberfest

ts-postgres

Build Status NPM version NPM downloads

Non-blocking PostgreSQL client for Node.js written in TypeScript.

Install

To install the latest version of this library:

$ npm install [email protected]

Features

  • Fast!
  • Supports both binary and text value formats
    • Result data is currently sent in binary format only
  • Multiple queries can be sent at once (pipeline)
  • Extensible value model
  • Hybrid query result object
    • Iterable (synchronous or asynchronous; one row at a time)
    • Promise-based

Usage

The client uses an async/await-based programming model.

import { Client } from 'ts-postgres';

async function main() {
    const client = new Client();
    await client.connect();

    try {
        // Querying the client returns a query result promise
        // which is also an asynchronous result iterator.
        const resultIterator = client.query(
            `SELECT 'Hello ' || $1 || '!' AS message`,
            ['world']
        );

        for await (const row of resultIterator) {
            // 'Hello world!'
            console.log(row.get('message'));
        }
    } finally {
        await client.end();
    }
}

main()

Waiting on the result iterator returns the complete query result.

const result = await client.query(...)

If the query fails, an exception is thrown.

Connection options

The client constructor takes an optional Configuration object.

For example, to connect to a remote host use the host configuration key:

const client = new Client({"host": <hostname>});

The following table lists the various configuration options and their default value when applicable.

Key Type Default
host string "localhost"
port number 5432
user string The username of the process owner
database string "postgres"
password string
types Map<DataType, ValueTypeReader> Default value mapping for built-in types
extraFloatDigits number 0
keepAlive boolean true
preparedStatementPrefix string "tsp_"

Passing query parameters

Query parameters use the format $1, $2 etc.

When a specific data type is not inferrable from the query, PostgreSQL uses DataType.Text as the default data type (which is mapped to the string type in TypeScript). An explicit type can be provided in two different ways:

  1. Using type cast in the query, e.g. $1::int.

  2. By passing a list of types to the query method:

    import { DataType } from 'ts-postgres';
    const result = await client.query(
       "select $1 || ' bottles of beer'", [99], [DataType.Int4]
    );
    

Note that the number type in TypeScript has a maximum safe integer value which lies between and DataType.Int8 – given by Number.MAX_SAFE_INTEGER. The maximum safe integer data type to use is therefore DataType.Int4.

The bigint type is not currently supported.

Iterator interface

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.

Result interface

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.

Multiple queries

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

Prepared statements

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.

Notes

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.

FAQ

  1. 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(...)
    

Benchmarking

Use the following environment variable to run tests in "benchmark" mode.

$ NODE_ENV=benchmark npm run test

Support

ts-postgres is free software. If you encounter a bug with the library please open an issue on the GitHub repo.

License

Copyright (c) 2018-2020 Malthe Borch ([email protected])

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].