All Projects → langpavel → Node Pg Async

langpavel / Node Pg Async

Licence: mit
PostgreSQL 🐘 client for node.js designed for easy use with ES7 async/await based on node-postgres

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Node Pg Async

Massive Js
A data mapper for Node.js and PostgreSQL.
Stars: ✭ 2,521 (+6048.78%)
Mutual labels:  promise, postgres
Goqu
SQL builder and query library for golang
Stars: ✭ 984 (+2300%)
Mutual labels:  postgres
Ecoleta
Ecoleta - Developed during the event NLW 1.0 by @Rocketseat
Stars: ✭ 29 (-29.27%)
Mutual labels:  postgres
Hapi Node Postgres
📦 Wrap hapi requests with a pg connection
Stars: ✭ 32 (-21.95%)
Mutual labels:  postgres
Entityframeworkcore.bootkit
EntityFrameworkCore Start Kit
Stars: ✭ 29 (-29.27%)
Mutual labels:  postgres
Nodespider
[DEPRECATED] Simple, flexible, delightful web crawler/spider package
Stars: ✭ 33 (-19.51%)
Mutual labels:  promise
Example Api
A base API project to bootstrap and prototype quickly.
Stars: ✭ 27 (-34.15%)
Mutual labels:  postgres
Niklick
Rails Versioned API solution template for hipsters! (Ruby, Ruby on Rails, REST API, GraphQL, Docker, RSpec, Devise, Postgress DB)
Stars: ✭ 39 (-4.88%)
Mutual labels:  postgres
Fritzbox.js
☎️ The leading AVM Fritz!Box API for NodeJS and JavaScript.
Stars: ✭ 36 (-12.2%)
Mutual labels:  promise
Pgwatch2
PostgreSQL metrics monitor/dashboard
Stars: ✭ 960 (+2241.46%)
Mutual labels:  postgres
Docker Pgredshift
Redshift docker image based on postgres
Stars: ✭ 32 (-21.95%)
Mutual labels:  postgres
Zeeql3
The ZeeQL (EOF/CoreData/AR like) Database Toolkit for Swift
Stars: ✭ 29 (-29.27%)
Mutual labels:  postgres
Create Request
Apply interceptors to `fetch` and create a custom request function.
Stars: ✭ 34 (-17.07%)
Mutual labels:  promise
Python Database Sanitizer
Python based database sanitizer for removing sensitive data from your database dumps
Stars: ✭ 29 (-29.27%)
Mutual labels:  postgres
Breeze
Javascript async flow control manager
Stars: ✭ 38 (-7.32%)
Mutual labels:  promise
Franticapparatus
Type and memory safe promises for Swift, supports cancellation
Stars: ✭ 27 (-34.15%)
Mutual labels:  promise
Promise.hpp
C++ asynchronous promises like a Promises/A+
Stars: ✭ 31 (-24.39%)
Mutual labels:  promise
Djangorestframework Mvt
Serve Mapbox Vector Tiles with Django and Postgres
Stars: ✭ 33 (-19.51%)
Mutual labels:  postgres
Toro
Multithreaded message processing on Postgres
Stars: ✭ 39 (-4.88%)
Mutual labels:  postgres
Dbdpg
Perl Postgres driver DBD::Pg aka dbdpg
Stars: ✭ 38 (-7.32%)
Mutual labels:  postgres

pg-async

Greenkeeper badge

Npm Version NPM downloads Dependency Status devDependency Status Build Status Coverage Status Join the chat at https://gitter.im/langpavel/node-pg-async

Tiny but powerful Promise based PostgreSQL client for node.js designed for easy use with ES7 async/await.
Based on node-postgres (known as pg in npm registry). Can use pg or native pg-native backend.

Example

import PgAsync, {SQL} from 'pg-async';

// using default connection
const pgAsync = new PgAsync();

const userTable = 'user';
const sqlUserByLogin = (login) => SQL`
  select id
  from $ID${userTable}
  where login = ${login}
`;

async function setPassword(login, newPwd) {
  const userId = await pgAsync.value(sqlUserByLogin(login));
  // userId is guaranted here,
  // pgAsync.value requires query yielding exactly one row with one column.
  await pgAsync.query(SQL`
    update $ID${userTable} set
      passwd = ${newPwd}
    where userId = ${userId}
  `);
}

Install

$ npm install --save pg-async

API

Configuring Connection Options

new PgAsync([connectionOptions], [driver])
  • The default export of pg-async is PgAsync class which let you configure connection options
  • Connection options defaults to pg.defaults
  • Optional driver let you choose underlying library
  • To use the native bindings you must npm install --save pg-native
import PgAsync from 'pg-async';

// using default connection
const pgAsync = new PgAsync();

// using connection string
const pgAsync = new PgAsync({connectionString: 'postgres://user:[email protected]:port/database'});

// using connection object
const pgAsync = new PgAsync({user, password, host, port, database, ...});

// using default for current user, with native driver
// install pg-native package manually
const pgAsync = new PgAsync(null, 'native');
const pgAsync = new PgAsync(null, require('pg').native);

await pgAsync.query(SQL`...`) -> pg.Result

await pgAsync.query(sql, values...) -> pg.Result

await pgAsync.queryArgs(sql, [values]) -> pg.Result

  • Execute SQL and return Result object from underlying pg library
  • Interesting properties on Result object are:
    • rowCount Number ­– returned rows
    • oid Number ­– Postgres oid
    • rows Array ­– Actual result of pgAsync.rows()
    • rowAsArray Boolean
    • fields Array of:
      • name String ­– name or alias of column
      • tableID Number ­– oid of table or 0
      • columnID Number ­– index of column in table or 0
      • dataTypeID Number ­– oid of data type
      • dataTypeSize Number ­– size in bytes od colum, -1 for variable length
      • ­dataTypeModifier Number

await pgAsync.rows(SQL`...`) -> array of objects

await pgAsync.rows(sql, values...) -> array of objects

await pgAsync.rowsArgs(sql, [values]) -> array of objects

  • Execute SQL and return array of key/value objects (result.rows)

await pgAsync.row(SQL`...`) -> object

await pgAsync.row(sql, values...) -> object

await pgAsync.rowArgs(sql, [values]) -> object

  • Execute SQL and return single key/value object. If query yields more than one or none rows, promise will be rejected.
  • Rejected promise throw exception at await location.

await pgAsync.value(SQL`...`) -> any

await pgAsync.value(sql, values...) -> any

await pgAsync.valueArgs(sql, [values]) -> any

  • Same as row, but query must yields single column in single row, otherwise throws.

await pgAsync.connect(async (client) => innerResult) -> innerResult

  • Execute multiple queries in sequence on same connection. This is handy for transactions.
  • asyncFunc here has signature async (client, pgClient) => { ... }
  • provided client has async methods:
    • query, rows, row, value as above
    • queryArgs, rowsArgs, rowArgs, valueArgs as above
    • startTransaction, commit, rollback - start new transaction manually. Use pgAsync.transaction when possible
  • client itself is shorthand for query

await pgAsync.transaction(async (client) => innerResult) -> innerResult

Transaction is similar to connect but automatically start and commit transaction, rollback on throwen error Example:

const pgAsync = new PgAsync();

function moveMoney(fromAccount, toAccount, amount) {
  return pgAsync.transaction(async (client) => {
    let movementFrom, movementTo, movementId;
    const sql = `
      INSERT INTO bank_account (account, amount)
      VALUES ($1, $2)
      RETURNING id
    `;
    movementFrom = await client.value(sql, [fromAccount, -amount]);
    movementTo = await client.value(sql, [toAccount, amount]);
    return {movementFrom, movementTo}
  });
}

async function doTheWork() {
  // ...
  try {
    const result = await moveMoney('alice', 'bob', 19.95);
    // transaction is commited
  } catch (err) {
    // transaction is rollbacked
  }
  // ...
}

await pgAsync.getClient([connectionOptions]) -> {client, done}

  • Get unwrapped pg.Client callback based instance.
    You should not call this method unless you know what are you doing.
  • Client must be returned to pool manually by calling done()

pgAsync.closeConnections()

  • Disconnects all idle clients within all active pools, and has all client pools terminate. See pool.end()
  • This actually terminates all connections on driver used by Pg instance

Features

  • [x] pg driver support
  • [x] pg.native driver support
  • [x] debug — Enable debugging with DEBUG="pg-async" environment variable
  • [x] Transaction API wrapper - Postgres does not support nested transactions
  • [x] Template tag SQL formatting
  • [ ] Transaction SAVEPOINT support
  • [ ] Cursor API wrapper

If you miss something, don't be shy, just open new issue! It will be nice if you label your issue with prefix [bug] [doc] [question] [typo] etc.

License (MIT)

Copyright (c) 2016 Pavel Lang ([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].