{"id":16796663,"url":"https://github.com/langpavel/node-pg-async","last_synced_at":"2025-03-17T03:31:02.806Z","repository":{"id":57322524,"uuid":"51899793","full_name":"langpavel/node-pg-async","owner":"langpavel","description":"PostgreSQL :elephant: client for node.js designed for easy use with ES7 async/await based on node-postgres","archived":false,"fork":false,"pushed_at":"2020-05-23T12:09:25.000Z","size":967,"stargazers_count":43,"open_issues_count":17,"forks_count":4,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-02-23T02:38:12.400Z","etag":null,"topics":["es7-async","node-postgres","pg-async","postgres","promise"],"latest_commit_sha":null,"homepage":"http://langpavel.github.io/node-pg-async","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/langpavel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-02-17T06:18:52.000Z","updated_at":"2022-12-16T09:27:33.000Z","dependencies_parsed_at":"2022-08-26T01:10:38.081Z","dependency_job_id":null,"html_url":"https://github.com/langpavel/node-pg-async","commit_stats":null,"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langpavel%2Fnode-pg-async","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langpavel%2Fnode-pg-async/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langpavel%2Fnode-pg-async/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langpavel%2Fnode-pg-async/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/langpavel","download_url":"https://codeload.github.com/langpavel/node-pg-async/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243841204,"owners_count":20356441,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["es7-async","node-postgres","pg-async","postgres","promise"],"created_at":"2024-10-13T09:19:45.389Z","updated_at":"2025-03-17T03:31:02.511Z","avatar_url":"https://github.com/langpavel.png","language":"JavaScript","readme":"# pg-async \n\n[![Greenkeeper badge](https://badges.greenkeeper.io/langpavel/node-pg-async.svg)](https://greenkeeper.io/)\n\n[![Npm Version](https://badge.fury.io/js/pg-async.svg)](https://badge.fury.io/js/pg-async)\n[![NPM downloads](http://img.shields.io/npm/dm/pg-async.svg)](https://www.npmjs.com/package/pg-async)\n[![Dependency Status](https://david-dm.org/langpavel/node-pg-async.svg)](https://david-dm.org/langpavel/node-pg-async)\n[![devDependency Status](https://david-dm.org/langpavel/node-pg-async/dev-status.svg)](https://david-dm.org/langpavel/node-pg-async#info=devDependencies)\n[![Build Status](https://travis-ci.org/langpavel/node-pg-async.svg?branch=master)](https://travis-ci.org/langpavel/node-pg-async)\n[![Coverage Status](https://coveralls.io/repos/github/langpavel/node-pg-async/badge.svg?branch=master)](https://coveralls.io/github/langpavel/node-pg-async?branch=master)\n[![Join the chat at https://gitter.im/langpavel/node-pg-async](https://badges.gitter.im/langpavel/node-pg-async.svg)](https://gitter.im/langpavel/node-pg-async?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n\nTiny but powerful Promise based PostgreSQL client for node.js\ndesigned for easy use with ES7 async/await.\u003cbr/\u003e\nBased on [node-postgres](https://github.com/brianc/node-postgres) (known as `pg` in npm registry).\nCan use `pg` or native `pg-native` backend.\n\n## Example\n\n```js\nimport PgAsync, {SQL} from 'pg-async';\n\n// using default connection\nconst pgAsync = new PgAsync();\n\nconst userTable = 'user';\nconst sqlUserByLogin = (login) =\u003e SQL`\n  select id\n  from $ID${userTable}\n  where login = ${login}\n`;\n\nasync function setPassword(login, newPwd) {\n  const userId = await pgAsync.value(sqlUserByLogin(login));\n  // userId is guaranted here,\n  // pgAsync.value requires query yielding exactly one row with one column.\n  await pgAsync.query(SQL`\n    update $ID${userTable} set\n      passwd = ${newPwd}\n    where userId = ${userId}\n  `);\n}\n\n```\n\n## Install\n\n```\n$ npm install --save pg-async\n```\n\n## API\n\n#### Configuring Connection Options\n```js\nnew PgAsync([connectionOptions], [driver])\n```\n\n* The default export of `pg-async` is `PgAsync` class which let you configure connection options\n* Connection options defaults to [`pg.defaults`](https://github.com/brianc/node-postgres/wiki/pg#pgdefaults)\n* Optional `driver` let you choose underlying library\n* To use the [native bindings](https://github.com/brianc/node-pg-native.git) you must `npm install --save pg-native`\n\n```js\nimport PgAsync from 'pg-async';\n\n// using default connection\nconst pgAsync = new PgAsync();\n\n// using connection string\nconst pgAsync = new PgAsync({connectionString: 'postgres://user:secret@host:port/database'});\n\n// using connection object\nconst pgAsync = new PgAsync({user, password, host, port, database, ...});\n\n// using default for current user, with native driver\n// install pg-native package manually\nconst pgAsync = new PgAsync(null, 'native');\nconst pgAsync = new PgAsync(null, require('pg').native);\n```\n\n---\n\n#### ```await pgAsync.query(SQL`...`) -\u003e pg.Result```\n#### `await pgAsync.query(sql, values...) -\u003e pg.Result`\n#### `await pgAsync.queryArgs(sql, [values]) -\u003e pg.Result`\n\n* Execute SQL and return `Result` object from underlying `pg` library\n* Interesting properties on `Result` object are:\n  * `rowCount` Number ­– returned rows\n  * `oid` Number ­– Postgres oid\n  * `rows` Array ­– Actual result of `pgAsync.rows()`\n  * `rowAsArray` Boolean\n  * `fields` Array of:\n    * `name` String ­– name or alias of column\n    * `tableID` Number ­– oid of table or 0\n    * `columnID` Number ­– index of column in table or 0\n    * `dataTypeID` Number ­– oid of data type\n    * `dataTypeSize` Number ­– size in bytes od colum, -1 for variable length\n    * ­`dataTypeModifier` Number \n\n---\n\n#### ```await pgAsync.rows(SQL`...`) -\u003e array of objects```\n#### `await pgAsync.rows(sql, values...) -\u003e array of objects`\n#### `await pgAsync.rowsArgs(sql, [values]) -\u003e array of objects`\n\n* Execute SQL and return array of key/value objects (`result.rows`)\n\n---\n\n#### ```await pgAsync.row(SQL`...`) -\u003e object```\n#### `await pgAsync.row(sql, values...) -\u003e object`\n#### `await pgAsync.rowArgs(sql, [values]) -\u003e object`\n\n* Execute SQL and return single key/value object.\n  If query yields more than one or none rows, promise will be rejected.\n* Rejected promise throw exception at **`await`** location.\n\n---\n\n#### ```await pgAsync.value(SQL`...`) -\u003e any```\n#### `await pgAsync.value(sql, values...) -\u003e any`\n#### `await pgAsync.valueArgs(sql, [values]) -\u003e any`\n\n* Same as row, but query must yields single column in single row, otherwise throws.\n\n---\n\n#### `await pgAsync.connect(async (client) =\u003e innerResult) -\u003e innerResult`\n\n* Execute multiple queries in sequence on same connection. This is handy for transactions.\n* `asyncFunc` here has signature `async (client, pgClient) =\u003e { ... }`\n* provided `client` has async methods:\n  * `query`, `rows`, `row`, `value` as above\n  * `queryArgs`, `rowsArgs`, `rowArgs`, `valueArgs` as above\n  * `startTransaction`, `commit`, `rollback` - start new transaction manually. Use `pgAsync.transaction` when possible\n* `client` itself is shorthand for `query`\n\n---\n\n#### `await pgAsync.transaction(async (client) =\u003e innerResult) -\u003e innerResult`\n\nTransaction is similar to `connect` but automatically start and commit transaction,\nrollback on throwen error\n__Example:__\n\n```js\nconst pgAsync = new PgAsync();\n\nfunction moveMoney(fromAccount, toAccount, amount) {\n  return pgAsync.transaction(async (client) =\u003e {\n    let movementFrom, movementTo, movementId;\n    const sql = `\n      INSERT INTO bank_account (account, amount)\n      VALUES ($1, $2)\n      RETURNING id\n    `;\n    movementFrom = await client.value(sql, [fromAccount, -amount]);\n    movementTo = await client.value(sql, [toAccount, amount]);\n    return {movementFrom, movementTo}\n  });\n}\n\nasync function doTheWork() {\n  // ...\n  try {\n    const result = await moveMoney('alice', 'bob', 19.95);\n    // transaction is commited\n  } catch (err) {\n    // transaction is rollbacked\n  }\n  // ...\n}\n```\n\n---\n\n#### `await pgAsync.getClient([connectionOptions]) -\u003e {client, done}`\n\n* Get unwrapped `pg.Client` callback based instance.\u003cbr/\u003e\n  You should not call this method unless you know what are you doing.\n* Client must be returned to pool manually by calling `done()`\n\n---\n\n#### `pgAsync.closeConnections()`\n\n* Disconnects all idle clients within all active pools, and has all client pools terminate.\n  See [`pool.end()`](https://node-postgres.com/api/pool#pool-end)\n* This actually terminates all connections on driver used by Pg instance\n\n---\n\n## Features\n\n * [x] `pg` driver support\n * [x] `pg.native` driver support\n * [x] [`debug`](https://github.com/visionmedia/debug#readme) — Enable debugging with `DEBUG=\"pg-async\"` environment variable\n * [x] Transaction API wrapper - Postgres does not support nested transactions\n * [x] Template tag SQL formatting\n * [ ] Transaction `SAVEPOINT` support\n * [ ] Cursor API wrapper\n\nIf you miss something, don't be shy, just\n[open new issue!](https://github.com/langpavel/node-pg-async/issues)\nIt will be nice if you label your issue with prefix `[bug]` `[doc]` `[question]` `[typo]`\netc.\n\n## License (MIT)\n\nCopyright (c) 2016 Pavel Lang (langpavel@phpskelet.org)\n\n\u003csmall\u003e\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n\u003c/small\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangpavel%2Fnode-pg-async","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flangpavel%2Fnode-pg-async","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangpavel%2Fnode-pg-async/lists"}