Giter Club home page Giter Club logo

node-pg-async's Introduction

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:secret@host: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

  • pg driver support
  • pg.native driver support
  • debug — Enable debugging with DEBUG="pg-async" environment variable
  • Transaction API wrapper - Postgres does not support nested transactions
  • 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.

node-pg-async's People

Contributors

gitter-badger avatar greenkeeper[bot] avatar greenkeeperio-bot avatar langpavel avatar metainfa avatar ulan08 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-pg-async's Issues

pool, node-postgres and node-pg-async?

Into v5.2.0 node-postgres replace internal pooling code with pg-pool changelog v.5.2.0, with v.6.0.0 add new pg.Pool() changelog v.6.2.0.

My questions is:

  1. node-pg-async uses Client connection with default pool through pg.connect getClient?
  2. will plan replace pg.connect(deprecated) to new pg.Pool() API?
  3. if i want to use, for example PgBouncer as pool tool, will i can disable pg-pool by set pg.defaults.poolSize: 0?

An in-range update of debug is breaking the build 🚨

Version 3.2.0 of debug was just published.

Branch Build failing 🚨
Dependency debug
Current Version 3.1.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

debug is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes 3.2.0

A long-awaited release to debug is available now: 3.2.0.

Due to the delay in release and the number of changes made (including bumping dependencies in order to mitigate vulnerabilities), it is highly recommended maintainers update to the latest package version and test thoroughly.


Minor Changes

Patches

Credits

Huge thanks to @DanielRuf, @EirikBirkeland, @KyleStay, @Qix-, @abenhamdine, @alexey-pelykh, @DiegoRBaquero, @febbraro, @kwolfy, and @TooTallNate for their help!

Commits

The new version differs by 25 commits.

There are 25 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Should PgAsync async instance live the entire duration or be created per use?

Sorry for the question-as-an-issue. I'm unsure of the appropriate scope for PgAsync instance, though. It sounds like it uses connection pooling, but does this mean I'm free to create an instance of this whenever needed and it'll pick up a connection from a pool, or does this mean I should have a single instance of PgAsync used throughout the entire application lifetime?

Thanks!

Transaction, PG connection and Async IO

Does transaction requires a given Postgres connection to be reserved exclusively until commit command or it can be used in another transaction ?

Assuming that someone is using this driver for web application for which all HTTP requests needs transaction, if Postgres connection need to reserved exclusively, then there would be 1 Postgres connection per HTTP request. I wonder How much benefit one might achieve by using this async (non-blocking) driver instead of sync (blocking) driver ?

PG syntax in doc

Hi! In example you write:
INSERT INTO bank_account (account, amount) VALUES ($1, $2) RETURNS id
But in PG syntax yiu shoud use RETURNING

Problem after upgrading to 3.1.0

Using this connection uri postgres://postgres@localhost:5432/db gives out error role {{rolename}} does not exist. It was working fine before updating. It seems that it is reverting to the default options. Is there something that I may have missed?

Improve debug output

Output of debug package is not much pretty, especially when query got SqlFragment as input (using template tag):

  pg-async query params: ["2016-03-23T22:28:59.609Z","0.0.0","1.8","Platne","Plna","S query: {"_parts":["\n      INSERT INTO \"ruian_file\" (\"import_od\",\"verze_cli\",\"verze_vfr\",\"typ_zaznamu\",\"typ_davky\",\"typ_souboru\",\"datum\",\"transakce_od_id\",\"transakce_od_zapsano\",\"transakce_do_id\",\"transakce_do_zapsano\",\"platnost_dat_isui\",\"platnost_dat_iskn\") VALUES (",",",",",",",",",",",",",",",",",",",",",",",",",") RETURNING id\n    "],"values":["2016-03-23T22:28:59.609Z","0.0.0","1.8","Platne","Plna","ST_UCIS","2016-02-04T00:10:09.000Z","0","2012-06-29T01:36:44.000Z","1104587","2016-02-03T15:59:47.000Z","2016-02-03T14:27:41.000Z","2016-02-03T15:59:47.000Z"],"text":"\n      INSERT INTO \"ruian_file\" (\"import_od\",\"verze_cli\",\"verze_vfr\",\"typ_zaznamu\",\"typ_davky\",\"typ_souboru\",\"datum\",\"transakce_od_id\",\"transakce_od_zapsano\",\"transakce_do_id\",\"transakce_do_zapsano\",\"platnost_dat_isui\",\"platnost_dat_iskn\") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) RETURNING id\n    ","rowMode":"array"} +7ms

Process not exiting

I'm running a dummy

"use strict";
require("babel-polyfill");
import PgAsync from 'pg-async';
// using connection string 
var pgAsync = new PgAsync("postgres://postgres@localhost/databas");

async function run(){
  var rows = await pgAsync.rows("SELECT * FROM files_list");
  console.log(rows);

  //pgAsync.closeConnections(); //nope
}

run();

With my .babelrc as

{
  "presets": ["es2015"],
  "plugins": ["syntax-async-functions","transform-regenerator"]
}

All is working fine but the nodejs process running after the final output.
I guess there is a need to "close" the sql link, i tried closeConnections/close/end with no success.
Can you help me here ?

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

PG.connect is deprecated

Looks like pg changed how they do connection pooling. Here's what I see when using pg-async ...

(node:6300) DeprecationWarning: PG.connect is deprecated - please see the upgrade guide at https://node-postgres.com/guides/upgrading

Access pg client events?

I am trying to implement pg NOTIFY , LISTEN and I saw this example.

var pg = require ('pg'),    
    pgConnectionString = "postgres://user:pass@localhost/db"; 
var client = new pg.Client(pgConnectionString);
client.connect();
client.query('LISTEN "article_watcher"');
client.on('notification', function(data) {    console.log(data.payload);});

Is this possible using this package?

I tried doing

const pg = new PgAsync(uri)
// create schema, trigger functions code
pg.connect((client) => {
	client.on('notification', (msg) => {
                console.log(JSON.parse(msg.payload))
	})
})

But it's just giving out errors.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.