mirror of
https://github.com/brianc/node-postgres.git
synced 2025-12-08 20:16:25 +00:00
Compare commits
57 Commits
pg-esm-tes
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d493f3b55 | ||
|
|
917478397b | ||
|
|
f5c90a5484 | ||
|
|
65bc3d4884 | ||
|
|
a6c1084db1 | ||
|
|
1b2bedc9c8 | ||
|
|
27a2754787 | ||
|
|
01fadd93d7 | ||
|
|
43b8692019 | ||
|
|
fab87b28af | ||
|
|
c8fb1e9261 | ||
|
|
54e0424991 | ||
|
|
235d7ad5e2 | ||
|
|
8f8e7315e8 | ||
|
|
f0d1c4868a | ||
|
|
0ad6c9b71e | ||
|
|
54964ecff7 | ||
|
|
1a25d12817 | ||
|
|
e00aac1398 | ||
|
|
cd877a5761 | ||
|
|
607efc1b6e | ||
|
|
14dc8dd100 | ||
|
|
8608fb84c8 | ||
|
|
114a03e887 | ||
|
|
7ab5923fad | ||
|
|
6b016b37d4 | ||
|
|
0ada72e608 | ||
|
|
03642abec1 | ||
|
|
a4888ee028 | ||
|
|
411869df65 | ||
|
|
26ace0ac8f | ||
|
|
3e7bd2f681 | ||
|
|
9cf2184d09 | ||
|
|
c9353acbc0 | ||
|
|
26fa32c133 | ||
|
|
a47c480055 | ||
|
|
abff18d6f9 | ||
|
|
e43d4b7eb6 | ||
|
|
e8fde07227 | ||
|
|
27f34c6aee | ||
|
|
e30b41d481 | ||
|
|
6be857e9d3 | ||
|
|
9bfc967e91 | ||
|
|
79351af32e | ||
|
|
52ec1293f2 | ||
|
|
2647f7ecaf | ||
|
|
980752ce00 | ||
|
|
264e30f424 | ||
|
|
f528433e9d | ||
|
|
93aa1ba2f1 | ||
|
|
9e7a5d97cf | ||
|
|
7a009381e6 | ||
|
|
ff40638868 | ||
|
|
229de3006b | ||
|
|
81d875fe09 | ||
|
|
39e134d0b5 | ||
|
|
0c1629bea2 |
10
.eslintrc
10
.eslintrc
@ -14,9 +14,15 @@
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/no-unused-vars": ["error", {
|
||||
"args": "none"
|
||||
"args": "none",
|
||||
"varsIgnorePattern": "^_$"
|
||||
}],
|
||||
"no-unused-vars": "off"
|
||||
"no-unused-vars": ["error", {
|
||||
"args": "none",
|
||||
"varsIgnorePattern": "^_$"
|
||||
}],
|
||||
"no-var": "error",
|
||||
"prefer-const": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
|
||||
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
@ -42,7 +42,8 @@ jobs:
|
||||
- '18'
|
||||
- '20'
|
||||
- '22'
|
||||
- '23'
|
||||
- '24'
|
||||
- '25'
|
||||
os:
|
||||
- ubuntu-latest
|
||||
name: Node.js ${{ matrix.node }}
|
||||
|
||||
@ -4,6 +4,10 @@ For richer information consult the commit log on github with referenced pull req
|
||||
|
||||
We do not include break-fix version release in this file.
|
||||
|
||||
## pg@8.16.0
|
||||
|
||||
- Add support for [min connection pool size](https://github.com/brianc/node-postgres/pull/3438).
|
||||
|
||||
## pg@8.15.0
|
||||
|
||||
- Add support for [esm](https://github.com/brianc/node-postgres/pull/3423) importing. CommonJS importing is still also supported.
|
||||
|
||||
20
docs/README.md
Normal file
20
docs/README.md
Normal file
@ -0,0 +1,20 @@
|
||||
# node-postgres docs website
|
||||
|
||||
This is the documentation for node-postgres which is currently hosted at [https://node-postgres.com](https://node-postgres.com).
|
||||
|
||||
## Development
|
||||
|
||||
To run the documentation locally, you need to have [Node.js](https://nodejs.org) installed. Then, you can clone the repository and install the dependencies:
|
||||
|
||||
```bash
|
||||
cd docs
|
||||
yarn
|
||||
```
|
||||
|
||||
Once you've installed the deps, you can run the development server:
|
||||
|
||||
```bash
|
||||
yarn dev
|
||||
```
|
||||
|
||||
This will start a local server at [http://localhost:3000](http://localhost:3000) where you can view the documentation and see your changes.
|
||||
@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { Callout } from 'nextra-theme-docs'
|
||||
|
||||
export const Alert = ({ children }) => {
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { Callout } from 'nextra-theme-docs'
|
||||
|
||||
export const Info = ({ children }) => {
|
||||
|
||||
9
docs/components/logo.tsx
Normal file
9
docs/components/logo.tsx
Normal file
@ -0,0 +1,9 @@
|
||||
type Props = {
|
||||
src: string
|
||||
alt?: string
|
||||
}
|
||||
|
||||
export function Logo(props: Props) {
|
||||
const alt = props.alt || 'Logo'
|
||||
return <img src={props.src} alt={alt} width={100} height={100} style={{ width: 400, height: 'auto' }} />
|
||||
}
|
||||
@ -1,9 +1,5 @@
|
||||
import 'nextra-theme-docs/style.css'
|
||||
|
||||
export default function Nextra({ Component, pageProps }) {
|
||||
return (
|
||||
<>
|
||||
<Component {...pageProps} />
|
||||
</>
|
||||
)
|
||||
return <Component {...pageProps} />
|
||||
}
|
||||
|
||||
@ -23,6 +23,7 @@ type Config = {
|
||||
lock_timeout?: number, // number of milliseconds a query is allowed to be en lock state before it's cancelled due to lock timeout
|
||||
application_name?: string, // The name of the application that created this Client instance
|
||||
connectionTimeoutMillis?: number, // number of milliseconds to wait for connection, default is no timeout
|
||||
keepAliveInitialDelayMillis?: number, // set the initial delay before the first keepalive probe is sent on an idle socket
|
||||
idle_in_transaction_session_timeout?: number, // number of milliseconds before terminating any session with an open idle transaction, default is no timeout
|
||||
client_encoding?: string, // specifies the character set encoding that the database uses for sending data to the client
|
||||
fallback_application_name?: string, // provide an application name to use if application_name is not set
|
||||
@ -33,8 +34,7 @@ type Config = {
|
||||
example to create a client with specific connection information:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
|
||||
const client = new Client({
|
||||
user: 'database-user',
|
||||
@ -48,8 +48,7 @@ const client = new Client({
|
||||
## client.connect
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
const client = new Client()
|
||||
|
||||
await client.connect()
|
||||
@ -91,8 +90,7 @@ client.query(text: string, values?: any[]) => Promise<Result>
|
||||
**Plain text query**
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
const client = new Client()
|
||||
|
||||
await client.connect()
|
||||
@ -106,8 +104,7 @@ await client.end()
|
||||
**Parameterized query**
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
const client = new Client()
|
||||
|
||||
await client.connect()
|
||||
@ -145,8 +142,7 @@ await client.end()
|
||||
If you pass an object to `client.query` and the object has a `.submit` function on it, the client will pass it's PostgreSQL server connection to the object and delegate query dispatching to the supplied object. This is an advanced feature mostly intended for library authors. It is incidentally also currently how the callback and promise based queries above are handled internally, but this is subject to change. It is also how [pg-cursor](https://github.com/brianc/node-pg-cursor) and [pg-query-stream](https://github.com/brianc/node-pg-query-stream) work.
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Query } = pg
|
||||
import { Query } from 'pg'
|
||||
const query = new Query('select $1::text as name', ['brianc'])
|
||||
|
||||
const result = client.query(query)
|
||||
|
||||
@ -18,8 +18,7 @@ $ npm install pg pg-cursor
|
||||
Instantiates a new Cursor. A cursor is an instance of `Submittable` and should be passed directly to the `client.query` method.
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
import Cursor from 'pg-cursor'
|
||||
|
||||
const pool = new Pool()
|
||||
@ -29,11 +28,9 @@ const values = [10]
|
||||
|
||||
const cursor = client.query(new Cursor(text, values))
|
||||
|
||||
cursor.read(100, (err, rows) => {
|
||||
cursor.close(() => {
|
||||
client.release()
|
||||
})
|
||||
})
|
||||
const { rows } = await cursor.read(100)
|
||||
console.log(rows.length) // 100 (unless the table has fewer than 100 rows)
|
||||
client.release()
|
||||
```
|
||||
|
||||
```ts
|
||||
@ -58,8 +55,7 @@ If the cursor has read to the end of the result sets all subsequent calls to cur
|
||||
Here is an example of reading to the end of a cursor:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
import Cursor from 'pg-cursor'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
@ -29,9 +29,17 @@ type Config = {
|
||||
idleTimeoutMillis?: number
|
||||
|
||||
// maximum number of clients the pool should contain
|
||||
// by default this is set to 10.
|
||||
// by default this is set to 10. There is some nuance to setting the maximum size of your pool.
|
||||
// see https://node-postgres.com/guides/pool-sizing for more information
|
||||
max?: number
|
||||
|
||||
// minimum number of clients the pool should hold on to and _not_ destroy with the idleTimeoutMillis
|
||||
// this can be useful if you get very bursty traffic and want to keep a few clients around.
|
||||
// note: current the pool will not automatically create and connect new clients up to the min, it will
|
||||
// only not evict and close clients except those which exceed the min count.
|
||||
// the default is 0 which disables this behavior.
|
||||
min?: number
|
||||
|
||||
// Default behavior is the pool will keep clients open & connected to the backend
|
||||
// until idleTimeoutMillis expire for each client and node will maintain a ref
|
||||
// to the socket on the client, keeping the event loop alive until all clients are closed
|
||||
@ -42,14 +50,19 @@ type Config = {
|
||||
// to the postgres server. This can be handy in scripts & tests
|
||||
// where you don't want to wait for your clients to go idle before your process exits.
|
||||
allowExitOnIdle?: boolean
|
||||
|
||||
// Sets a max overall life for the connection.
|
||||
// A value of 60 would evict connections that have been around for over 60 seconds,
|
||||
// regardless of whether they are idle. It's useful to force rotation of connection pools through
|
||||
// middleware so that you can rotate the underlying servers. The default is disabled (value of zero)
|
||||
maxLifetimeSeconds?: number
|
||||
}
|
||||
```
|
||||
|
||||
example to create a new pool with configuration:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool({
|
||||
host: 'localhost',
|
||||
@ -57,6 +70,7 @@ const pool = new Pool({
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
maxLifetimeSeconds: 60
|
||||
})
|
||||
```
|
||||
|
||||
@ -69,8 +83,7 @@ pool.query(text: string, values?: any[]) => Promise<pg.Result>
|
||||
```
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
@ -78,7 +91,7 @@ const result = await pool.query('SELECT $1::text as name', ['brianc'])
|
||||
console.log(result.rows[0].name) // brianc
|
||||
```
|
||||
|
||||
Notice in the example above there is no need to check out or release a client. The pool is doing the acquiring and releasing internally. I find `pool.query` to be a handy shortcut many situations and use it exclusively unless I need a transaction.
|
||||
Notice in the example above there is no need to check out or release a client. The pool is doing the acquiring and releasing internally. I find `pool.query` to be a handy shortcut in many situations and I use it exclusively unless I need a transaction.
|
||||
|
||||
<Alert>
|
||||
<div>
|
||||
@ -99,11 +112,10 @@ Acquires a client from the pool.
|
||||
|
||||
- If there are idle clients in the pool one will be returned to the callback on `process.nextTick`.
|
||||
- If the pool is not full but all current clients are checked out a new client will be created & returned to this callback.
|
||||
- If the pool is 'full' and all clients are currently checked out will wait in a FIFO queue until a client becomes available by it being released back to the pool.
|
||||
- If the pool is 'full' and all clients are currently checked out, requests will wait in a FIFO queue until a client becomes available by being released back to the pool.
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
@ -121,8 +133,7 @@ Client instances returned from `pool.connect` will have a `release` method which
|
||||
The `release` method on an acquired client returns it back to the pool. If you pass a truthy value in the `destroy` parameter, instead of releasing the client to the pool, the pool will be instructed to disconnect and destroy this client, leaving a space within itself for a new client.
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
@ -134,8 +145,7 @@ client.release()
|
||||
```
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
assert(pool.totalCount === 0)
|
||||
@ -168,8 +178,7 @@ Calling `pool.end` will drain the pool of all active clients, disconnect them, a
|
||||
|
||||
```js
|
||||
// again both promises and callbacks are supported:
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
|
||||
@ -9,7 +9,7 @@ import { Alert } from '/components/alert.tsx'
|
||||
Escapes a string as a [SQL identifier](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).
|
||||
|
||||
```js
|
||||
const { escapeIdentifier } = require('pg')
|
||||
import { escapeIdentifier } from 'pg';
|
||||
const escapedIdentifier = escapeIdentifier('FooIdentifier')
|
||||
console.log(escapedIdentifier) // '"FooIdentifier"'
|
||||
```
|
||||
@ -27,7 +27,7 @@ console.log(escapedIdentifier) // '"FooIdentifier"'
|
||||
Escapes a string as a [SQL literal](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS).
|
||||
|
||||
```js
|
||||
const { escapeLiteral } = require('pg')
|
||||
import { escapeLiteral } from 'pg';
|
||||
const escapedLiteral = escapeLiteral("hello 'world'")
|
||||
console.log(escapedLiteral) // "'hello ''world'''"
|
||||
```
|
||||
|
||||
@ -5,5 +5,7 @@
|
||||
"transactions": "Transactions",
|
||||
"types": "Data Types",
|
||||
"ssl": "SSL",
|
||||
"native": "Native"
|
||||
"native": "Native",
|
||||
"esm": "ESM",
|
||||
"callbacks": "Callbacks"
|
||||
}
|
||||
|
||||
39
docs/pages/features/callbacks.mdx
Normal file
39
docs/pages/features/callbacks.mdx
Normal file
@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Callbacks
|
||||
---
|
||||
|
||||
## Callback Support
|
||||
|
||||
`async` / `await` is the preferred way to write async code these days with node, but callbacks are supported in the `pg` module and the `pg-pool` module. To use them, pass a callback function as the last argument to the following methods & it will be called and a promise will not be returned:
|
||||
|
||||
|
||||
```js
|
||||
const { Pool, Client } = require('pg')
|
||||
|
||||
// pool
|
||||
const pool = new Pool()
|
||||
// run a query on an available client
|
||||
pool.query('SELECT NOW()', (err, res) => {
|
||||
console.log(err, res)
|
||||
})
|
||||
|
||||
// check out a client to do something more complex like a transaction
|
||||
pool.connect((err, client, release) => {
|
||||
client.query('SELECT NOW()', (err, res) => {
|
||||
release()
|
||||
console.log(err, res)
|
||||
pool.end()
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
// single client
|
||||
const client = new Client()
|
||||
client.connect((err) => {
|
||||
if (err) throw err
|
||||
client.query('SELECT NOW()', (err, res) => {
|
||||
console.log(err, res)
|
||||
client.end()
|
||||
})
|
||||
})
|
||||
```
|
||||
@ -101,9 +101,9 @@ const signerOptions = {
|
||||
username: 'api-user',
|
||||
}
|
||||
|
||||
const signer = new RDS.Signer()
|
||||
const signer = new RDS.Signer(signerOptions)
|
||||
|
||||
const getPassword = () => signer.getAuthToken(signerOptions)
|
||||
const getPassword = () => signer.getAuthToken()
|
||||
|
||||
const pool = new Pool({
|
||||
user: signerOptions.username,
|
||||
|
||||
37
docs/pages/features/esm.mdx
Normal file
37
docs/pages/features/esm.mdx
Normal file
@ -0,0 +1,37 @@
|
||||
---
|
||||
title: ESM
|
||||
---
|
||||
|
||||
## ESM Support
|
||||
|
||||
As of v8.15.x node-postgres supporters the __ECMAScript Module__ (ESM) format. This means you can use `import` statements instead of `require` or `import pg from 'pg'`.
|
||||
|
||||
CommonJS modules are still supported. The ESM format is an opt-in feature and will not affect existing codebases that use CommonJS.
|
||||
|
||||
The docs have been changed to show ESM usage, but in a CommonJS context you can still use the same code, you just need to change the import format.
|
||||
|
||||
If you're using CommonJS, you can use the following code to import the `pg` module:
|
||||
|
||||
```js
|
||||
const pg = require('pg')
|
||||
const { Client } = pg
|
||||
// etc...
|
||||
```
|
||||
|
||||
### ESM Usage
|
||||
|
||||
If you're using ESM, you can use the following code to import the `pg` module:
|
||||
|
||||
```js
|
||||
import { Client } from 'pg'
|
||||
// etc...
|
||||
```
|
||||
|
||||
|
||||
Previously if you were using ESM you would have to use the following code:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
// etc...
|
||||
```
|
||||
@ -22,8 +22,7 @@ const config = {
|
||||
},
|
||||
}
|
||||
|
||||
import pg from 'pg'
|
||||
const { Client, Pool } = pg
|
||||
import { Client, Pool } from 'pg'
|
||||
|
||||
const client = new Client(config)
|
||||
await client.connect()
|
||||
|
||||
@ -16,8 +16,7 @@ To execute a transaction with node-postgres you simply execute `BEGIN / COMMIT /
|
||||
## Examples
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
const pool = new Pool()
|
||||
|
||||
const client = await pool.connect()
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
{
|
||||
"project-structure": "Suggested Code Structure",
|
||||
"async-express": "Express with Async/Await",
|
||||
"pool-sizing": "Pool Sizing",
|
||||
"upgrading": "Upgrading"
|
||||
}
|
||||
|
||||
@ -22,8 +22,7 @@ That's the same structure I used in the [project structure](/guides/project-stru
|
||||
My `db/index.js` file usually starts out like this:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
|
||||
25
docs/pages/guides/pool-sizing.md
Normal file
25
docs/pages/guides/pool-sizing.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Pool Sizing
|
||||
---
|
||||
|
||||
If you're using a [pool](/apis/pool) in an application with multiple instances of your service running (common in most cloud/container environments currently), you'll need to think a bit about the `max` parameter of your pool across all services and all _instances_ of all services which are connecting to your Postgres server.
|
||||
|
||||
This can get pretty complex depending on your cloud environment. Further nuance is introduced with things like pg-bouncer, RDS connection proxies, etc., which will do some forms of connection pooling and connection multiplexing. So, it's definitely worth thinking about. Let's run through a few setups. While certainly not exhaustive, these examples hopefully prompt you into thinking about what's right for your setup.
|
||||
|
||||
## Simple apps, dev mode, fixed instance counts, etc.
|
||||
|
||||
If your app isn't running in a k8s style env with containers scaling automatically or lambdas or cloud functions etc., you can do some "napkin math" for the `max` pool config you can use. Let's assume your Postgres instance is configured to have a maximum of 200 connections at any one time. You know your service is going to run on 4 instances. You can set the `max` pool size to 50, but if all your services are saturated waiting on database connections, you won't be able to connect to the database from any mgmt tools or scale up your services without changing config/code to adjust the max size.
|
||||
|
||||
In this situation, I'd probably set the `max` to 20 or 25. This lets you have plenty of headroom for scaling more instances and realistically, if your app is starved for db connections, you probably want to take a look at your queries and make them execute faster, or cache, or something else to reduce the load on the database. I worked on a more reporting-heavy application with limited users, but each running 5-6 queries at a time which all took 100-200 milliseconds to run. In that situation, I upped the `max` to 50. Typically, though, I don't bother setting it to anything other than the default of `10` as that's usually _fine_.
|
||||
|
||||
## Auto-scaling, cloud-functions, multi-tenancy, etc.
|
||||
|
||||
If the number of instances of your services which connect to your database is more dynamic and based on things like load, auto-scaling containers, or running in cloud-functions, you need to be a bit more thoughtful about what your max might be. Often in these environments, there will be another database pooling proxy in front of the database like pg-bouncer or the RDS-proxy, etc. I'm not sure how all these function exactly, and they all have some trade-offs, but let's assume you're not using a proxy. Then I'd be pretty cautious about how large you set any individual pool. If you're running an application under pretty serious load where you need dynamic scaling or lots of lambdas spinning up and sending queries, your queries are likely fast and you should be fine setting the `max` to a low value like 10 -- or just leave it alone, since `10` is the default.
|
||||
|
||||
## pg-bouncer, RDS-proxy, etc.
|
||||
|
||||
I'm not sure of all the pooling services for Postgres. I haven't used any myself. Throughout the years of working on `pg`, I've addressed issues caused by various proxies behaving differently than an actual Postgres backend. There are also gotchas with things like transactions. On the other hand, plenty of people run these with much success. In this situation, I would just recommend using some small but reasonable `max` value like the default value of `10` as it can still be helpful to keep a few TCP sockets from your services to the Postgres proxy open.
|
||||
|
||||
## Conclusion, tl;dr
|
||||
|
||||
It's a bit of a complicated topic and doesn't have much impact on things until you need to start scaling. At that point, your number of connections _still_ probably won't be your scaling bottleneck. It's worth thinking about a bit, but mostly I'd just leave the pool size to the default of `10` until you run into troubles: hopefully you never do!
|
||||
@ -27,13 +27,12 @@ The location doesn't really matter - I've found it usually ends up being somewha
|
||||
Typically I'll start out my `db/index.js` file like so:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
export const query = (text, params, callback) => {
|
||||
return pool.query(text, params, callback)
|
||||
export const query = (text, params) => {
|
||||
return pool.query(text, params)
|
||||
}
|
||||
```
|
||||
|
||||
@ -55,8 +54,7 @@ app.get('/:id', async (req, res, next) => {
|
||||
Imagine we have lots of routes scattered throughout many files under our `routes/` directory. We now want to go back and log every single query that's executed, how long it took, and the number of rows it returned. If we had required node-postgres directly in every route file we'd have to go edit every single route - that would take forever & be really error prone! But thankfully we put our data access into `db/index.js`. Let's go add some logging:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
@ -76,8 +74,7 @@ _note: I didn't log the query parameters. Depending on your application you migh
|
||||
Now what if we need to check out a client from the pool to run several queries in a row in a transaction? We can add another method to our `db/index.js` file when we need to do this:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Pool } = pg
|
||||
import { Pool } from 'pg'
|
||||
|
||||
const pool = new Pool()
|
||||
|
||||
|
||||
@ -50,7 +50,7 @@ pg.end()
|
||||
// new way, available since 6.0.0:
|
||||
|
||||
// create a pool
|
||||
var pool = new pg.Pool()
|
||||
const pool = new pg.Pool()
|
||||
|
||||
// connection using created pool
|
||||
pool.connect(function (err, client, done) {
|
||||
|
||||
@ -3,6 +3,8 @@ title: Welcome
|
||||
slug: /
|
||||
---
|
||||
|
||||
import { Logo } from '/components/logo.tsx'
|
||||
|
||||
node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, streaming results, C/C++ bindings, rich type parsing, and more! Just like PostgreSQL itself there are a lot of features: this documentation aims to get you up and running quickly and in the right direction. It also tries to provide guides for more advanced & edge-case topics allowing you to tap into the full power of PostgreSQL from node.js.
|
||||
|
||||
## Install
|
||||
@ -15,19 +17,33 @@ $ npm install pg
|
||||
|
||||
node-postgres continued development and support is made possible by the many [supporters](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md).
|
||||
|
||||
Special thanks to [Medplum](https://www.medplum.com/) for sponsoring node-postgres for a whole year!
|
||||
|
||||
<a href="https://www.medplum.com/">
|
||||
<img
|
||||
alt="Medplum"
|
||||
src="https://raw.githubusercontent.com/medplum/medplum-logo/refs/heads/main/medplum-logo.png"
|
||||
style={{
|
||||
width: '300px',
|
||||
height: 'auto',
|
||||
margin: '0 auto',
|
||||
display: 'block',
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
|
||||
If you or your company would like to sponsor node-postgres stop by [GitHub Sponsors](https://github.com/sponsors/brianc) and sign up or feel free to [email me](mailto:brian@pecanware.com) if you want to add your logo to the documentation or discuss higher tiers of sponsorship!
|
||||
|
||||
# Version compatibility
|
||||
|
||||
node-postgres strives to be compatible with all recent LTS versions of node & the most recent "stable" version. At the time of this writing node-postgres is compatible with node 8.x, 10.x, 12.x and 14.x To use node >= 14.x you will need to install `pg@8.2.x` or later due to some internal stream changes on the node 14 branch. Dropping support for an old node lts version will always be considered a breaking change in node-postgres and will be done on _major_ version number changes only, and we will try to keep support for 8.x for as long as reasonably possible.
|
||||
node-postgres strives to be compatible with all recent LTS versions of node & the most recent "stable" version. At the time of this writing node-postgres is compatible with node 18.x, 20.x, 22.x, and 24.x.
|
||||
|
||||
## Getting started
|
||||
|
||||
The simplest possible way to connect, query, and disconnect is with async/await:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
const client = new Client()
|
||||
await client.connect()
|
||||
|
||||
@ -41,8 +57,7 @@ await client.end()
|
||||
For the sake of simplicity, these docs will assume that the methods are successful. In real life use, make sure to properly handle errors thrown in the methods. A `try/catch` block is a great way to do so:
|
||||
|
||||
```ts
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
import { Client } from 'pg'
|
||||
const client = new Client()
|
||||
await client.connect()
|
||||
|
||||
@ -56,22 +71,17 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
### Callbacks
|
||||
### Pooling
|
||||
|
||||
If you prefer a callback-style approach to asynchronous programming, all async methods support an optional callback parameter as well:
|
||||
In most applications you'll want to use a [connection pool](/features/pooling) to manage your connections. This is a more advanced topic, but here's a simple example of how to use it:
|
||||
|
||||
```js
|
||||
import pg from 'pg'
|
||||
const { Client } = pg
|
||||
const client = new Client()
|
||||
|
||||
client.connect((err) => {
|
||||
client.query('SELECT $1::text as message', ['Hello world!'], (err, res) => {
|
||||
console.log(err ? err.stack : res.rows[0].message) // Hello World!
|
||||
client.end()
|
||||
})
|
||||
})
|
||||
|
||||
import { Pool } from 'pg'
|
||||
const pool = new Pool()
|
||||
const res = await pool.query('SELECT $1::text as message', ['Hello world!'])
|
||||
console.log(res.rows[0].message) // Hello world!
|
||||
```
|
||||
|
||||
Our real-world apps are almost always more complicated than that, and I urge you to read on!
|
||||
|
||||
|
||||
|
||||
BIN
docs/public/favicon.ico
Normal file
BIN
docs/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@ -10,7 +10,6 @@ export default {
|
||||
docsRepositoryBase: 'https://github.com/brianc/node-postgres/blob/master/docs', // base URL for the docs repository
|
||||
titleSuffix: ' – node-postgres',
|
||||
darkMode: true,
|
||||
footer: true,
|
||||
navigation: {
|
||||
prev: true,
|
||||
next: true,
|
||||
@ -23,13 +22,43 @@ export default {
|
||||
},
|
||||
logo: (
|
||||
<>
|
||||
<svg>...</svg>
|
||||
<span>node-postgres</span>
|
||||
<svg
|
||||
version="1.0"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={48}
|
||||
width={48}
|
||||
viewBox="0 0 1024.000000 1024.000000"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
>
|
||||
<g transform="translate(0.000000,1024.000000) scale(0.100000,-0.100000)" fill="#3c873a" stroke="none">
|
||||
<path
|
||||
d="M4990 7316 c-391 -87 -703 -397 -1003 -996 -285 -568 -477 -1260
|
||||
-503 -1811 l-7 -142 -112 7 c-103 5 -207 27 -382 78 -37 11 -44 10 -63 -7 -61
|
||||
-55 17 -180 177 -285 91 -60 194 -103 327 -137 l104 -26 17 -71 c44 -183 152
|
||||
-441 256 -613 125 -207 322 -424 493 -541 331 -229 774 -291 1113 -156 112 45
|
||||
182 94 209 147 13 24 13 35 -1 90 -22 87 -88 219 -134 267 -46 49 -79 52 -153
|
||||
14 -168 -85 -360 -54 -508 83 -170 157 -244 440 -195 743 50 304 231 601 430
|
||||
706 168 89 332 60 463 -81 66 -71 110 -140 197 -315 83 -166 116 -194 203
|
||||
-170 88 23 370 258 637 531 411 420 685 806 808 1139 54 145 71 243 71 410 1
|
||||
128 -3 157 -27 243 -86 310 -243 543 -467 690 -207 137 -440 157 -966 85
|
||||
l-161 -22 -94 41 c-201 87 -327 113 -533 112 -77 -1 -166 -7 -196 -13z m-89
|
||||
-1357 c15 -10 34 -38 43 -61 23 -56 13 -111 -28 -156 -59 -64 -171 -54 -216
|
||||
21 -35 57 -22 145 28 190 44 40 122 43 173 6z m-234 -1361 c-46 -74 -156 -188
|
||||
-249 -258 -211 -159 -459 -219 -734 -179 l-76 12 89 28 c187 60 485 229 683
|
||||
388 l75 60 122 0 122 1 -32 -52z"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
<span style={{ fontWeight: 800 }}>node-postgres</span>
|
||||
</>
|
||||
),
|
||||
chat: {
|
||||
link: 'https://discord.gg/2afXp5vUWm',
|
||||
},
|
||||
head: (
|
||||
<>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="shortcut icon" href="/favicon.ico" />
|
||||
<meta
|
||||
name="description"
|
||||
content="node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database."
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
||||
"@typescript-eslint/parser": "^6.17.0",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-config-prettier": "^10.1.2",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.2",
|
||||
"lerna": "^3.19.0",
|
||||
|
||||
8
packages/pg-bundler-test/esbuild-cloudflare.config.mjs
Normal file
8
packages/pg-bundler-test/esbuild-cloudflare.config.mjs
Normal file
@ -0,0 +1,8 @@
|
||||
import * as esbuild from 'esbuild'
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: ['./src/index.mjs'],
|
||||
bundle: true,
|
||||
outfile: './dist/esbuild-cloudflare.js',
|
||||
conditions: ['import', 'workerd'],
|
||||
})
|
||||
7
packages/pg-bundler-test/esbuild-empty.config.mjs
Normal file
7
packages/pg-bundler-test/esbuild-empty.config.mjs
Normal file
@ -0,0 +1,7 @@
|
||||
import * as esbuild from 'esbuild'
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: ['./src/index.mjs'],
|
||||
bundle: true,
|
||||
outfile: './dist/esbuild-empty.js',
|
||||
})
|
||||
25
packages/pg-bundler-test/package.json
Normal file
25
packages/pg-bundler-test/package.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "pg-bundler-test",
|
||||
"version": "0.0.2",
|
||||
"description": "Test bundlers with pg-cloudflare, https://github.com/brianc/node-postgres/issues/3452",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^28.0.3",
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"esbuild": "^0.25.5",
|
||||
"pg-cloudflare": "^1.2.7",
|
||||
"rollup": "^4.41.1",
|
||||
"vite": "^6.3.5",
|
||||
"webpack": "^5.99.9",
|
||||
"webpack-cli": "^6.0.1"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "yarn webpack && yarn rollup && yarn vite && yarn esbuild",
|
||||
"webpack": "webpack --config webpack-empty.config.mjs && webpack --config webpack-cloudflare.config.mjs",
|
||||
"rollup": "rollup --config rollup-empty.config.mjs --failAfterWarnings && rollup --config rollup-cloudflare.config.mjs --failAfterWarnings",
|
||||
"vite": "[ $(node --version | sed 's/v//' | cut -d'.' -f1) -ge 18 ] && vite build --config vite-empty.config.mjs && vite build --config vite-cloudflare.config.mjs || echo 'Skip Vite test'",
|
||||
"esbuild": "node esbuild-empty.config.mjs && node esbuild-cloudflare.config.mjs"
|
||||
}
|
||||
}
|
||||
13
packages/pg-bundler-test/rollup-cloudflare.config.mjs
Normal file
13
packages/pg-bundler-test/rollup-cloudflare.config.mjs
Normal file
@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'rollup'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
import commonjs from '@rollup/plugin-commonjs'
|
||||
|
||||
export default defineConfig({
|
||||
input: './src/index.mjs',
|
||||
output: {
|
||||
file: 'dist/rollup-cloudflare.js',
|
||||
format: 'es',
|
||||
},
|
||||
plugins: [nodeResolve({ exportConditions: ['import', 'workerd'], preferBuiltins: true }), commonjs()],
|
||||
external: ['cloudflare:sockets'],
|
||||
})
|
||||
12
packages/pg-bundler-test/rollup-empty.config.mjs
Normal file
12
packages/pg-bundler-test/rollup-empty.config.mjs
Normal file
@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'rollup'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
import commonjs from '@rollup/plugin-commonjs'
|
||||
|
||||
export default defineConfig({
|
||||
input: './src/index.mjs',
|
||||
output: {
|
||||
file: 'dist/rollup-empty.js',
|
||||
format: 'es',
|
||||
},
|
||||
plugins: [nodeResolve(), commonjs()],
|
||||
})
|
||||
1
packages/pg-bundler-test/src/index.mjs
Normal file
1
packages/pg-bundler-test/src/index.mjs
Normal file
@ -0,0 +1 @@
|
||||
import 'pg-cloudflare'
|
||||
20
packages/pg-bundler-test/vite-cloudflare.config.mjs
Normal file
20
packages/pg-bundler-test/vite-cloudflare.config.mjs
Normal file
@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import commonjs from '@rollup/plugin-commonjs'
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
emptyOutDir: false,
|
||||
lib: {
|
||||
entry: './src/index.mjs',
|
||||
fileName: 'vite-cloudflare',
|
||||
formats: ['es'],
|
||||
},
|
||||
rollupOptions: {
|
||||
external: ['cloudflare:sockets'],
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
conditions: ['import', 'workerd'],
|
||||
},
|
||||
plugins: [commonjs()],
|
||||
})
|
||||
12
packages/pg-bundler-test/vite-empty.config.mjs
Normal file
12
packages/pg-bundler-test/vite-empty.config.mjs
Normal file
@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
emptyOutDir: false,
|
||||
lib: {
|
||||
entry: './src/index.mjs',
|
||||
fileName: 'vite-empty',
|
||||
formats: ['es'],
|
||||
},
|
||||
},
|
||||
})
|
||||
16
packages/pg-bundler-test/webpack-cloudflare.config.mjs
Normal file
16
packages/pg-bundler-test/webpack-cloudflare.config.mjs
Normal file
@ -0,0 +1,16 @@
|
||||
import webpack from 'webpack'
|
||||
|
||||
export default {
|
||||
mode: 'production',
|
||||
entry: './src/index.mjs',
|
||||
output: {
|
||||
filename: 'webpack-cloudflare.js',
|
||||
},
|
||||
resolve: { conditionNames: ['import', 'workerd'] },
|
||||
plugins: [
|
||||
// ignore cloudflare:sockets imports
|
||||
new webpack.IgnorePlugin({
|
||||
resourceRegExp: /^cloudflare:sockets$/,
|
||||
}),
|
||||
],
|
||||
}
|
||||
7
packages/pg-bundler-test/webpack-empty.config.mjs
Normal file
7
packages/pg-bundler-test/webpack-empty.config.mjs
Normal file
@ -0,0 +1,7 @@
|
||||
export default {
|
||||
mode: 'production',
|
||||
entry: './src/index.mjs',
|
||||
output: {
|
||||
filename: 'webpack-empty.js',
|
||||
},
|
||||
}
|
||||
@ -10,6 +10,64 @@
|
||||
npm i --save-dev pg-cloudflare
|
||||
```
|
||||
|
||||
The package uses conditional exports to support bundlers that don't know about
|
||||
`cloudflare:sockets`, so the consumer code by default imports an empty file. To
|
||||
enable the package, resolve to the `cloudflare` condition in your bundler's
|
||||
config. For example:
|
||||
|
||||
- `webpack.config.js`
|
||||
```js
|
||||
export default {
|
||||
...,
|
||||
resolve: { conditionNames: [..., "workerd"] },
|
||||
plugins: [
|
||||
// ignore cloudflare:sockets imports
|
||||
new webpack.IgnorePlugin({
|
||||
resourceRegExp: /^cloudflare:sockets$/,
|
||||
}),
|
||||
],
|
||||
}
|
||||
```
|
||||
- `vite.config.js`
|
||||
|
||||
> [!NOTE]
|
||||
> If you are using the [Cloudflare Vite plugin](https://www.npmjs.com/package/@cloudflare/vite-plugin) then the following configuration is not necessary.
|
||||
|
||||
```js
|
||||
export default defineConfig({
|
||||
...,
|
||||
resolve: {
|
||||
conditions: [..., "workerd"],
|
||||
},
|
||||
build: {
|
||||
...,
|
||||
// don't try to bundle cloudflare:sockets
|
||||
rollupOptions: {
|
||||
external: [..., 'cloudflare:sockets'],
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
- `rollup.config.js`
|
||||
```js
|
||||
export default defineConfig({
|
||||
...,
|
||||
plugins: [..., nodeResolve({ exportConditions: [..., 'workerd'] })],
|
||||
// don't try to bundle cloudflare:sockets
|
||||
external: [..., 'cloudflare:sockets'],
|
||||
})
|
||||
```
|
||||
- `esbuild.config.js`
|
||||
```js
|
||||
await esbuild.build({
|
||||
...,
|
||||
conditions: [..., 'workerd'],
|
||||
})
|
||||
```
|
||||
|
||||
The concrete examples can be found in `packages/pg-bundler-test`.
|
||||
|
||||
## How to use conditionally, in non-Node.js environments
|
||||
|
||||
As implemented in `pg` [here](https://github.com/brianc/node-postgres/commit/07553428e9c0eacf761a5d4541a3300ff7859578#diff-34588ad868ebcb232660aba7ee6a99d1e02f4bc93f73497d2688c3f074e60533R5-R13), a typical use case might look as follows, where in a Node.js environment the `net` module is used, while in a non-Node.js environment, where `net` is unavailable, `pg-cloudflare` is used instead, providing an equivalent interface:
|
||||
@ -21,14 +79,13 @@ module.exports.getStream = function getStream(ssl = false) {
|
||||
return net.Socket()
|
||||
}
|
||||
const { CloudflareSocket } = require('pg-cloudflare')
|
||||
return new CloudflareSocket(ssl);
|
||||
return new CloudflareSocket(ssl)
|
||||
}
|
||||
```
|
||||
|
||||
## Node.js implementation of the Socket API proposal
|
||||
|
||||
If you're looking for a way to rely on `connect()` as the interface you use to interact with raw sockets, but need this interface to be availble in a Node.js environment, [`@arrowood.dev/socket`](https://github.com/Ethan-Arrowood/socket) provides a Node.js implementation of the Socket API.
|
||||
|
||||
If you're looking for a way to rely on `connect()` as the interface you use to interact with raw sockets, but need this interface to be available in a Node.js environment, [`@arrowood.dev/socket`](https://github.com/Ethan-Arrowood/socket) provides a Node.js implementation of the Socket API.
|
||||
|
||||
### license
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-cloudflare",
|
||||
"version": "1.2.5",
|
||||
"version": "1.2.7",
|
||||
"description": "A socket implementation that can run on Cloudflare Workers using native TCP connections.",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@ -11,10 +11,13 @@
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./esm/index.mjs",
|
||||
"require": "./dist/index.js",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
"workerd": {
|
||||
"import": "./esm/index.mjs",
|
||||
"require": "./dist/index.js"
|
||||
},
|
||||
"default": "./dist/empty.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
|
||||
6
packages/pg-connection-string/.gitignore
vendored
6
packages/pg-connection-string/.gitignore
vendored
@ -12,6 +12,7 @@ lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
@ -23,4 +24,7 @@ build/Release
|
||||
# Deployed apps should consider commenting this line out:
|
||||
# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git
|
||||
node_modules
|
||||
package-lock.json
|
||||
package-lock.json
|
||||
|
||||
# TypeScript output directory
|
||||
dist
|
||||
|
||||
4
packages/pg-connection-string/.mocharc.json
Normal file
4
packages/pg-connection-string/.mocharc.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extension": ["js", "ts"],
|
||||
"require": "tsx"
|
||||
}
|
||||
@ -3,9 +3,6 @@ pg-connection-string
|
||||
|
||||
[](https://nodei.co/npm/pg-connection-string/)
|
||||
|
||||
[](https://travis-ci.org/iceddev/pg-connection-string)
|
||||
[](https://coveralls.io/github/iceddev/pg-connection-string?branch=master)
|
||||
|
||||
Functions for dealing with a PostgresSQL connection string
|
||||
|
||||
`parse` method taken from [node-postgres](https://github.com/brianc/node-postgres.git)
|
||||
@ -15,9 +12,9 @@ MIT License
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var parse = require('pg-connection-string').parse;
|
||||
const parse = require('pg-connection-string').parse;
|
||||
|
||||
var config = parse('postgres://someuser:somepassword@somehost:381/somedatabase')
|
||||
const config = parse('postgres://someuser:somepassword@somehost:381/somedatabase')
|
||||
```
|
||||
|
||||
The resulting config contains a subset of the following properties:
|
||||
@ -88,11 +85,11 @@ Query parameters follow a `?` character, including the following special query p
|
||||
* `encoding=<encoding>` - sets the `client_encoding` property
|
||||
* `ssl=1`, `ssl=true`, `ssl=0`, `ssl=false` - sets `ssl` to true or false, accordingly
|
||||
* `uselibpqcompat=true` - use libpq semantics
|
||||
* `sslmode=<sslmode>` when `sslcompat` is not set
|
||||
* `sslmode=<sslmode>` when `uselibpqcompat=true` is not set
|
||||
* `sslmode=disable` - sets `ssl` to false
|
||||
* `sslmode=no-verify` - sets `ssl` to `{ rejectUnauthorized: false }`
|
||||
* `sslmode=prefer`, `sslmode=require`, `sslmode=verify-ca`, `sslmode=verify-full` - sets `ssl` to true
|
||||
* `sslmode=<sslmode>` when `sslcompat=libpq`
|
||||
* `sslmode=<sslmode>` when `uselibpqcompat=true`
|
||||
* `sslmode=disable` - sets `ssl` to false
|
||||
* `sslmode=prefer` - sets `ssl` to `{ rejectUnauthorized: false }`
|
||||
* `sslmode=require` - sets `ssl` to `{ rejectUnauthorized: false }` unless `sslrootcert` is specified, in which case it behaves like `verify-ca`
|
||||
|
||||
13
packages/pg-connection-string/index.d.ts
vendored
13
packages/pg-connection-string/index.d.ts
vendored
@ -7,6 +7,13 @@ export interface Options {
|
||||
useLibpqCompat?: boolean
|
||||
}
|
||||
|
||||
interface SSLConfig {
|
||||
ca?: string
|
||||
cert?: string | null
|
||||
key?: string
|
||||
rejectUnauthorized?: boolean
|
||||
}
|
||||
|
||||
export interface ConnectionOptions {
|
||||
host: string | null
|
||||
password?: string
|
||||
@ -14,11 +21,15 @@ export interface ConnectionOptions {
|
||||
port?: string | null
|
||||
database: string | null | undefined
|
||||
client_encoding?: string
|
||||
ssl?: boolean | string
|
||||
ssl?: boolean | string | SSLConfig
|
||||
|
||||
application_name?: string
|
||||
fallback_application_name?: string
|
||||
options?: string
|
||||
keepalives?: number
|
||||
|
||||
// We allow any other options to be passed through
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export function toClientConfig(config: ConnectionOptions): ClientConfig
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const { emitWarning } = require('node:process')
|
||||
|
||||
//Parse method copied from https://github.com/brianc/node-postgres
|
||||
//Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com)
|
||||
//MIT License
|
||||
@ -23,11 +25,17 @@ function parse(str, options = {}) {
|
||||
}
|
||||
|
||||
try {
|
||||
result = new URL(str, 'postgres://base')
|
||||
} catch (e) {
|
||||
// The URL is invalid so try again with a dummy host
|
||||
result = new URL(str.replace('@/', '@___DUMMY___/'), 'postgres://base')
|
||||
dummyHost = true
|
||||
try {
|
||||
result = new URL(str, 'postgres://base')
|
||||
} catch (e) {
|
||||
// The URL is invalid so try again with a dummy host
|
||||
result = new URL(str.replace('@/', '@___DUMMY___/'), 'postgres://base')
|
||||
dummyHost = true
|
||||
}
|
||||
} catch (err) {
|
||||
// Remove the input from the error message to avoid leaking sensitive information
|
||||
err.input && (err.input = '*****REDACTED*****')
|
||||
throw err
|
||||
}
|
||||
|
||||
// We'd like to use Object.fromEntries() here but Node.js 10 does not support it
|
||||
@ -133,6 +141,9 @@ function parse(str, options = {}) {
|
||||
case 'require':
|
||||
case 'verify-ca':
|
||||
case 'verify-full': {
|
||||
if (config.sslmode !== 'verify-full') {
|
||||
deprecatedSslModeWarning(config.sslmode)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'no-verify': {
|
||||
@ -169,12 +180,8 @@ function toClientConfig(config) {
|
||||
if (typeof sslConfig === 'boolean') {
|
||||
c[key] = sslConfig
|
||||
}
|
||||
// else path is taken. multiple tests produce a sslConfig that is an object
|
||||
// and we can console.log to see that we take this path
|
||||
//
|
||||
// see https://github.com/istanbuljs/babel-plugin-istanbul/issues/186#issuecomment-1137765139
|
||||
// istanbul ignore else
|
||||
else if (typeof sslConfig === 'object') {
|
||||
|
||||
if (typeof sslConfig === 'object') {
|
||||
c[key] = toConnectionOptions(sslConfig)
|
||||
}
|
||||
} else if (value !== undefined && value !== null) {
|
||||
@ -205,6 +212,20 @@ function parseIntoClientConfig(str) {
|
||||
return toClientConfig(parse(str))
|
||||
}
|
||||
|
||||
function deprecatedSslModeWarning(sslmode) {
|
||||
if (!deprecatedSslModeWarning.warned) {
|
||||
deprecatedSslModeWarning.warned = true
|
||||
emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
|
||||
In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
|
||||
|
||||
To prepare for this change:
|
||||
- If you want the current behavior, explicitly use 'sslmode=verify-full'
|
||||
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
|
||||
|
||||
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = parse
|
||||
|
||||
parse.parse = parse
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-connection-string",
|
||||
"version": "2.8.5",
|
||||
"version": "2.9.1",
|
||||
"description": "Functions for dealing with a PostgresSQL connection string",
|
||||
"main": "./index.js",
|
||||
"types": "./index.d.ts",
|
||||
@ -13,9 +13,8 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "istanbul cover _mocha && npm run check-coverage",
|
||||
"check-coverage": "istanbul check-coverage --statements 100 --branches 100 --lines 100 --functions 100",
|
||||
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
|
||||
"test": "nyc --reporter=lcov mocha && npm run check-coverage",
|
||||
"check-coverage": "nyc check-coverage --statements 100 --branches 100 --lines 100 --functions 100"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -35,10 +34,14 @@
|
||||
},
|
||||
"homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string",
|
||||
"devDependencies": {
|
||||
"@types/pg": "^8.12.0",
|
||||
"chai": "^4.1.1",
|
||||
"coveralls": "^3.0.4",
|
||||
"istanbul": "^0.4.5",
|
||||
"mocha": "^10.5.2"
|
||||
"mocha": "^10.5.2",
|
||||
"nyc": "^15",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
|
||||
@ -1,21 +1,19 @@
|
||||
'use strict'
|
||||
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
const expect = chai.expect
|
||||
chai.should()
|
||||
|
||||
const { parse, toClientConfig, parseIntoClientConfig } = require('../')
|
||||
import { parse, toClientConfig, parseIntoClientConfig } from '../'
|
||||
|
||||
describe('toClientConfig', function () {
|
||||
it('converts connection info', function () {
|
||||
const config = parse('postgres://brian:pw@boom:381/lala')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.user.should.equal('brian')
|
||||
clientConfig.password.should.equal('pw')
|
||||
clientConfig.host.should.equal('boom')
|
||||
clientConfig.port.should.equal(381)
|
||||
clientConfig.database.should.equal('lala')
|
||||
clientConfig.user?.should.equal('brian')
|
||||
clientConfig.password?.should.equal('pw')
|
||||
clientConfig.host?.should.equal('boom')
|
||||
clientConfig.port?.should.equal(381)
|
||||
clientConfig.database?.should.equal('lala')
|
||||
})
|
||||
|
||||
it('converts query params', function () {
|
||||
@ -24,45 +22,47 @@ describe('toClientConfig', function () {
|
||||
)
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.application_name.should.equal('TheApp')
|
||||
clientConfig.fallback_application_name.should.equal('TheAppFallback')
|
||||
clientConfig.client_encoding.should.equal('utf8')
|
||||
clientConfig.options.should.equal('-c geqo=off')
|
||||
clientConfig.application_name?.should.equal('TheApp')
|
||||
clientConfig.fallback_application_name?.should.equal('TheAppFallback')
|
||||
clientConfig.client_encoding?.should.equal('utf8')
|
||||
clientConfig.options?.should.equal('-c geqo=off')
|
||||
})
|
||||
|
||||
it('converts SSL boolean', function () {
|
||||
const config = parse('pg:///?ssl=true')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.should.equal(true)
|
||||
clientConfig.ssl?.should.equal(true)
|
||||
})
|
||||
|
||||
it('converts sslmode=disable', function () {
|
||||
const config = parse('pg:///?sslmode=disable')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.should.equal(false)
|
||||
clientConfig.ssl?.should.equal(false)
|
||||
})
|
||||
|
||||
it('converts sslmode=noverify', function () {
|
||||
const config = parse('pg:///?sslmode=no-verify')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.rejectUnauthorized.should.equal(false)
|
||||
clientConfig.ssl?.should.deep.equal({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('converts other sslmode options', function () {
|
||||
const config = parse('pg:///?sslmode=verify-ca')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.should.deep.equal({})
|
||||
clientConfig.ssl?.should.deep.equal({})
|
||||
})
|
||||
|
||||
it('converts other sslmode options', function () {
|
||||
const config = parse('pg:///?sslmode=verify-ca')
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.should.deep.equal({})
|
||||
clientConfig.ssl?.should.deep.equal({})
|
||||
})
|
||||
|
||||
it('converts ssl cert options', function () {
|
||||
@ -77,7 +77,7 @@ describe('toClientConfig', function () {
|
||||
const config = parse(connectionString)
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.ssl.should.deep.equal({
|
||||
clientConfig.ssl?.should.deep.equal({
|
||||
ca: 'example ca\n',
|
||||
cert: 'example cert\n',
|
||||
key: 'example key\n',
|
||||
@ -87,9 +87,9 @@ describe('toClientConfig', function () {
|
||||
it('converts unix domain sockets', function () {
|
||||
const config = parse('socket:/some path/?db=my[db]&encoding=utf8&client_encoding=bogus')
|
||||
const clientConfig = toClientConfig(config)
|
||||
clientConfig.host.should.equal('/some path/')
|
||||
clientConfig.database.should.equal('my[db]', 'must to be escaped and unescaped through "my%5Bdb%5D"')
|
||||
clientConfig.client_encoding.should.equal('utf8')
|
||||
clientConfig.host?.should.equal('/some path/')
|
||||
clientConfig.database?.should.equal('my[db]', 'must to be escaped and unescaped through "my%5Bdb%5D"')
|
||||
clientConfig.client_encoding?.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('handles invalid port', function () {
|
||||
@ -106,9 +106,9 @@ describe('toClientConfig', function () {
|
||||
|
||||
const clientConfig = toClientConfig(config)
|
||||
|
||||
clientConfig.host.should.equal('boom')
|
||||
clientConfig.database.should.equal('lala')
|
||||
clientConfig.ssl.should.deep.equal({})
|
||||
clientConfig.host?.should.equal('boom')
|
||||
clientConfig.database?.should.equal('lala')
|
||||
clientConfig.ssl?.should.deep.equal({})
|
||||
})
|
||||
})
|
||||
|
||||
@ -116,10 +116,10 @@ describe('parseIntoClientConfig', function () {
|
||||
it('converts url', function () {
|
||||
const clientConfig = parseIntoClientConfig('postgres://brian:pw@boom:381/lala')
|
||||
|
||||
clientConfig.user.should.equal('brian')
|
||||
clientConfig.password.should.equal('pw')
|
||||
clientConfig.host.should.equal('boom')
|
||||
clientConfig.port.should.equal(381)
|
||||
clientConfig.database.should.equal('lala')
|
||||
clientConfig.user?.should.equal('brian')
|
||||
clientConfig.password?.should.equal('pw')
|
||||
clientConfig.host?.should.equal('boom')
|
||||
clientConfig.port?.should.equal(381)
|
||||
clientConfig.database?.should.equal('lala')
|
||||
})
|
||||
})
|
||||
@ -1,435 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var chai = require('chai')
|
||||
var expect = chai.expect
|
||||
chai.should()
|
||||
|
||||
var parse = require('../').parse
|
||||
|
||||
describe('parse', function () {
|
||||
it('using connection string in client constructor', function () {
|
||||
var subject = parse('postgres://brian:pw@boom:381/lala')
|
||||
subject.user.should.equal('brian')
|
||||
subject.password.should.equal('pw')
|
||||
subject.host.should.equal('boom')
|
||||
subject.port.should.equal('381')
|
||||
subject.database.should.equal('lala')
|
||||
})
|
||||
|
||||
it('escape spaces if present', function () {
|
||||
var subject = parse('postgres://localhost/post gres')
|
||||
subject.database.should.equal('post gres')
|
||||
})
|
||||
|
||||
it('do not double escape spaces', function () {
|
||||
var subject = parse('postgres://localhost/post%20gres')
|
||||
subject.database.should.equal('post gres')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket', function () {
|
||||
var subject = parse('/var/run/')
|
||||
subject.host.should.equal('/var/run/')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket and a specific database, the simple way', function () {
|
||||
var subject = parse('/var/run/ mydb')
|
||||
subject.host.should.equal('/var/run/')
|
||||
subject.database.should.equal('mydb')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, the health way', function () {
|
||||
var subject = parse('socket:/some path/?db=my[db]&encoding=utf8')
|
||||
subject.host.should.equal('/some path/')
|
||||
subject.database.should.equal('my[db]', 'must to be escaped and unescaped trough "my%5Bdb%5D"')
|
||||
subject.client_encoding.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, the escaped health way', function () {
|
||||
var subject = parse('socket:/some%20path/?db=my%2Bdb&encoding=utf8')
|
||||
subject.host.should.equal('/some path/')
|
||||
subject.database.should.equal('my+db')
|
||||
subject.client_encoding.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, username and password', function () {
|
||||
var subject = parse('socket://brian:pw@/var/run/?db=mydb')
|
||||
subject.user.should.equal('brian')
|
||||
subject.password.should.equal('pw')
|
||||
subject.host.should.equal('/var/run/')
|
||||
subject.database.should.equal('mydb')
|
||||
})
|
||||
|
||||
it('password contains < and/or > characters', function () {
|
||||
var sourceConfig = {
|
||||
user: 'brian',
|
||||
password: 'hello<ther>e',
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
}
|
||||
var connectionString =
|
||||
'postgres://' +
|
||||
sourceConfig.user +
|
||||
':' +
|
||||
sourceConfig.password +
|
||||
'@' +
|
||||
sourceConfig.host +
|
||||
':' +
|
||||
sourceConfig.port +
|
||||
'/' +
|
||||
sourceConfig.database
|
||||
var subject = parse(connectionString)
|
||||
subject.password.should.equal(sourceConfig.password)
|
||||
})
|
||||
|
||||
it('password contains colons', function () {
|
||||
var sourceConfig = {
|
||||
user: 'brian',
|
||||
password: 'hello:pass:world',
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
}
|
||||
var connectionString =
|
||||
'postgres://' +
|
||||
sourceConfig.user +
|
||||
':' +
|
||||
sourceConfig.password +
|
||||
'@' +
|
||||
sourceConfig.host +
|
||||
':' +
|
||||
sourceConfig.port +
|
||||
'/' +
|
||||
sourceConfig.database
|
||||
var subject = parse(connectionString)
|
||||
subject.password.should.equal(sourceConfig.password)
|
||||
})
|
||||
|
||||
it('username or password contains weird characters', function () {
|
||||
var strang = 'pg://my f%irst name:is&%awesome!@localhost:9000'
|
||||
var subject = parse(strang)
|
||||
subject.user.should.equal('my f%irst name')
|
||||
subject.password.should.equal('is&%awesome!')
|
||||
subject.host.should.equal('localhost')
|
||||
})
|
||||
|
||||
it('url is properly encoded', function () {
|
||||
var encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl'
|
||||
var subject = parse(encoded)
|
||||
subject.user.should.equal('bi%na%%ry ')
|
||||
subject.password.should.equal('s@f#')
|
||||
subject.host.should.equal('localhost')
|
||||
subject.database.should.equal(' u%20rl')
|
||||
})
|
||||
|
||||
it('relative url sets database', function () {
|
||||
var relative = 'different_db_on_default_host'
|
||||
var subject = parse(relative)
|
||||
subject.database.should.equal('different_db_on_default_host')
|
||||
})
|
||||
|
||||
it('no pathname returns null database', function () {
|
||||
var subject = parse('pg://myhost')
|
||||
;(subject.database === null).should.equal(true)
|
||||
})
|
||||
|
||||
it('pathname of "/" returns null database', function () {
|
||||
var subject = parse('pg://myhost/')
|
||||
subject.host.should.equal('myhost')
|
||||
;(subject.database === null).should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter host', function () {
|
||||
var subject = parse('pg://user:pass@/dbname?host=/unix/socket')
|
||||
subject.user.should.equal('user')
|
||||
subject.password.should.equal('pass')
|
||||
subject.host.should.equal('/unix/socket')
|
||||
subject.database.should.equal('dbname')
|
||||
})
|
||||
|
||||
it('configuration parameter host overrides url host', function () {
|
||||
var subject = parse('pg://user:pass@localhost/dbname?host=/unix/socket')
|
||||
subject.database.should.equal('dbname')
|
||||
subject.host.should.equal('/unix/socket')
|
||||
})
|
||||
|
||||
it('url with encoded socket', function () {
|
||||
var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname')
|
||||
subject.user.should.equal('user')
|
||||
subject.password.should.equal('pass')
|
||||
subject.host.should.equal('/unix/socket')
|
||||
subject.database.should.equal('dbname')
|
||||
})
|
||||
|
||||
it('url with real host and an encoded db name', function () {
|
||||
var subject = parse('pg://user:pass@localhost/%2Fdbname')
|
||||
subject.user.should.equal('user')
|
||||
subject.password.should.equal('pass')
|
||||
subject.host.should.equal('localhost')
|
||||
subject.database.should.equal('%2Fdbname')
|
||||
})
|
||||
|
||||
it('configuration parameter host treats encoded host as part of the db name', function () {
|
||||
var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname?host=localhost')
|
||||
subject.user.should.equal('user')
|
||||
subject.password.should.equal('pass')
|
||||
subject.host.should.equal('localhost')
|
||||
subject.database.should.equal('%2Funix%2Fsocket/dbname')
|
||||
})
|
||||
|
||||
it('configuration parameter application_name', function () {
|
||||
var connectionString = 'pg:///?application_name=TheApp'
|
||||
var subject = parse(connectionString)
|
||||
subject.application_name.should.equal('TheApp')
|
||||
})
|
||||
|
||||
it('configuration parameter fallback_application_name', function () {
|
||||
var connectionString = 'pg:///?fallback_application_name=TheAppFallback'
|
||||
var subject = parse(connectionString)
|
||||
subject.fallback_application_name.should.equal('TheAppFallback')
|
||||
})
|
||||
|
||||
it('configuration parameter options', function () {
|
||||
var connectionString = 'pg:///?options=-c geqo=off'
|
||||
var subject = parse(connectionString)
|
||||
subject.options.should.equal('-c geqo=off')
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true', function () {
|
||||
var connectionString = 'pg:///?ssl=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=1', function () {
|
||||
var connectionString = 'pg:///?ssl=1'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=0', function () {
|
||||
var connectionString = 'pg:///?ssl=0'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.equal(false)
|
||||
})
|
||||
|
||||
it('set ssl', function () {
|
||||
var subject = parse('pg://myhost/db?ssl=1')
|
||||
subject.ssl.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter sslcert=/path/to/cert', function () {
|
||||
var connectionString = 'pg:///?sslcert=' + __dirname + '/example.cert'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
cert: 'example cert\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslkey=/path/to/key', function () {
|
||||
var connectionString = 'pg:///?sslkey=' + __dirname + '/example.key'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
key: 'example key\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslrootcert=/path/to/ca', function () {
|
||||
var connectionString = 'pg:///?sslrootcert=' + __dirname + '/example.ca'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
ca: 'example ca\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=no-verify', function () {
|
||||
var connectionString = 'pg:///?sslmode=no-verify'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable', function () {
|
||||
var connectionString = 'pg:///?sslmode=disable'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer', function () {
|
||||
var connectionString = 'pg:///?sslmode=prefer'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require', function () {
|
||||
var connectionString = 'pg:///?sslmode=require'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-ca'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-full'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca', function () {
|
||||
var connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
ca: 'example ca\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=disable&uselibpqcompat=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=prefer&uselibpqcompat=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=require&uselibpqcompat=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-ca&uselibpqcompat=true'
|
||||
expect(function () {
|
||||
parse(connectionString)
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca and sslrootcert with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-ca&uselibpqcompat=true&sslrootcert=' + __dirname + '/example.ca'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
expect(subject.ssl.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full with uselibpqcompat query param', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-full&uselibpqcompat=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca with uselibpqcompat query param', function () {
|
||||
var connectionString =
|
||||
'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require&uselibpqcompat=true'
|
||||
var subject = parse(connectionString)
|
||||
subject.ssl.should.have.property('ca', 'example ca\n')
|
||||
subject.ssl.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
expect(subject.ssl.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=disable'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=prefer'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=require'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-ca'
|
||||
expect(function () {
|
||||
parse(connectionString, { useLibpqCompat: true })
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca and sslrootcert with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-ca&sslrootcert=' + __dirname + '/example.ca'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
expect(subject.ssl.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?sslmode=verify-full'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca with useLibpqCompat option', function () {
|
||||
var connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require'
|
||||
var subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl.should.have.property('ca', 'example ca\n')
|
||||
subject.ssl.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
expect(subject.ssl.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('does not allow sslcompat query parameter and useLibpqCompat option at the same time', function () {
|
||||
var connectionString = 'pg:///?uselibpqcompat=true'
|
||||
expect(function () {
|
||||
parse(connectionString, { useLibpqCompat: true })
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('allow other params like max, ...', function () {
|
||||
var subject = parse('pg://myhost/db?max=18&min=4')
|
||||
subject.max.should.equal('18')
|
||||
subject.min.should.equal('4')
|
||||
})
|
||||
|
||||
it('configuration parameter keepalives', function () {
|
||||
var connectionString = 'pg:///?keepalives=1'
|
||||
var subject = parse(connectionString)
|
||||
subject.keepalives.should.equal('1')
|
||||
})
|
||||
|
||||
it('unknown configuration parameter is passed into client', function () {
|
||||
var connectionString = 'pg:///?ThereIsNoSuchPostgresParameter=1234'
|
||||
var subject = parse(connectionString)
|
||||
subject.ThereIsNoSuchPostgresParameter.should.equal('1234')
|
||||
})
|
||||
|
||||
it('do not override a config field with value from query string', function () {
|
||||
var subject = parse('socket:/some path/?db=my[db]&encoding=utf8&client_encoding=bogus')
|
||||
subject.host.should.equal('/some path/')
|
||||
subject.database.should.equal('my[db]', 'must to be escaped and unescaped through "my%5Bdb%5D"')
|
||||
subject.client_encoding.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('return last value of repeated parameter', function () {
|
||||
var connectionString = 'pg:///?keepalives=1&keepalives=0'
|
||||
var subject = parse(connectionString)
|
||||
subject.keepalives.should.equal('0')
|
||||
})
|
||||
|
||||
it('use the port specified in the query parameters', function () {
|
||||
var connectionString = 'postgres:///?host=localhost&port=1234'
|
||||
var subject = parse(connectionString)
|
||||
subject.port.should.equal('1234')
|
||||
})
|
||||
})
|
||||
470
packages/pg-connection-string/test/parse.ts
Normal file
470
packages/pg-connection-string/test/parse.ts
Normal file
@ -0,0 +1,470 @@
|
||||
import chai from 'chai'
|
||||
const expect = chai.expect
|
||||
chai.should()
|
||||
|
||||
import { parse } from '../'
|
||||
|
||||
describe('parse', function () {
|
||||
it('using connection string in client constructor', function () {
|
||||
const subject = parse('postgres://brian:pw@boom:381/lala')
|
||||
subject.user?.should.equal('brian')
|
||||
subject.password?.should.equal('pw')
|
||||
subject.host?.should.equal('boom')
|
||||
subject.port?.should.equal('381')
|
||||
subject.database?.should.equal('lala')
|
||||
})
|
||||
|
||||
it('escape spaces if present', function () {
|
||||
const subject = parse('postgres://localhost/post gres')
|
||||
subject.database?.should.equal('post gres')
|
||||
})
|
||||
|
||||
it('do not double escape spaces', function () {
|
||||
const subject = parse('postgres://localhost/post%20gres')
|
||||
subject.database?.should.equal('post gres')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket', function () {
|
||||
const subject = parse('/const/run/')
|
||||
subject.host?.should.equal('/const/run/')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket and a specific database, the simple way', function () {
|
||||
const subject = parse('/const/run/ mydb')
|
||||
subject.host?.should.equal('/const/run/')
|
||||
subject.database?.should.equal('mydb')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, the health way', function () {
|
||||
const subject = parse('socket:/some path/?db=my[db]&encoding=utf8')
|
||||
subject.host?.should.equal('/some path/')
|
||||
subject.database?.should.equal('my[db]', 'must to be escaped and unescaped trough "my%5Bdb%5D"')
|
||||
subject.client_encoding?.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, the escaped health way', function () {
|
||||
const subject = parse('socket:/some%20path/?db=my%2Bdb&encoding=utf8')
|
||||
subject.host?.should.equal('/some path/')
|
||||
subject.database?.should.equal('my+db')
|
||||
subject.client_encoding?.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('initializing with unix domain socket, username and password', function () {
|
||||
const subject = parse('socket://brian:pw@/const/run/?db=mydb')
|
||||
subject.user?.should.equal('brian')
|
||||
subject.password?.should.equal('pw')
|
||||
subject.host?.should.equal('/const/run/')
|
||||
subject.database?.should.equal('mydb')
|
||||
})
|
||||
|
||||
it('password contains < and/or > characters', function () {
|
||||
const sourceConfig = {
|
||||
user: 'brian',
|
||||
password: 'hello<ther>e',
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
}
|
||||
const connectionString =
|
||||
'postgres://' +
|
||||
sourceConfig.user +
|
||||
':' +
|
||||
sourceConfig.password +
|
||||
'@' +
|
||||
sourceConfig.host +
|
||||
':' +
|
||||
sourceConfig.port +
|
||||
'/' +
|
||||
sourceConfig.database
|
||||
const subject = parse(connectionString)
|
||||
subject.password?.should.equal(sourceConfig.password)
|
||||
})
|
||||
|
||||
it('password contains colons', function () {
|
||||
const sourceConfig = {
|
||||
user: 'brian',
|
||||
password: 'hello:pass:world',
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'postgres',
|
||||
}
|
||||
const connectionString =
|
||||
'postgres://' +
|
||||
sourceConfig.user +
|
||||
':' +
|
||||
sourceConfig.password +
|
||||
'@' +
|
||||
sourceConfig.host +
|
||||
':' +
|
||||
sourceConfig.port +
|
||||
'/' +
|
||||
sourceConfig.database
|
||||
const subject = parse(connectionString)
|
||||
subject.password?.should.equal(sourceConfig.password)
|
||||
})
|
||||
|
||||
it('username or password contains weird characters', function () {
|
||||
const strang = 'pg://my f%irst name:is&%awesome!@localhost:9000'
|
||||
const subject = parse(strang)
|
||||
subject.user?.should.equal('my f%irst name')
|
||||
subject.password?.should.equal('is&%awesome!')
|
||||
subject.host?.should.equal('localhost')
|
||||
})
|
||||
|
||||
it('url is properly encoded', function () {
|
||||
const encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl'
|
||||
const subject = parse(encoded)
|
||||
subject.user?.should.equal('bi%na%%ry ')
|
||||
subject.password?.should.equal('s@f#')
|
||||
subject.host?.should.equal('localhost')
|
||||
subject.database?.should.equal(' u%20rl')
|
||||
})
|
||||
|
||||
it('relative url sets database', function () {
|
||||
const relative = 'different_db_on_default_host'
|
||||
const subject = parse(relative)
|
||||
subject.database?.should.equal('different_db_on_default_host')
|
||||
})
|
||||
|
||||
it('no pathname returns null database', function () {
|
||||
const subject = parse('pg://myhost')
|
||||
;(subject.database === null).should.equal(true)
|
||||
})
|
||||
|
||||
it('pathname of "/" returns null database', function () {
|
||||
const subject = parse('pg://myhost/')
|
||||
subject.host?.should.equal('myhost')
|
||||
;(subject.database === null).should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter host', function () {
|
||||
const subject = parse('pg://user:pass@/dbname?host=/unix/socket')
|
||||
subject.user?.should.equal('user')
|
||||
subject.password?.should.equal('pass')
|
||||
subject.host?.should.equal('/unix/socket')
|
||||
subject.database?.should.equal('dbname')
|
||||
})
|
||||
|
||||
it('configuration parameter host overrides url host', function () {
|
||||
const subject = parse('pg://user:pass@localhost/dbname?host=/unix/socket')
|
||||
subject.database?.should.equal('dbname')
|
||||
subject.host?.should.equal('/unix/socket')
|
||||
})
|
||||
|
||||
it('url with encoded socket', function () {
|
||||
const subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname')
|
||||
subject.user?.should.equal('user')
|
||||
subject.password?.should.equal('pass')
|
||||
subject.host?.should.equal('/unix/socket')
|
||||
subject.database?.should.equal('dbname')
|
||||
})
|
||||
|
||||
it('url with real host and an encoded db name', function () {
|
||||
const subject = parse('pg://user:pass@localhost/%2Fdbname')
|
||||
subject.user?.should.equal('user')
|
||||
subject.password?.should.equal('pass')
|
||||
subject.host?.should.equal('localhost')
|
||||
subject.database?.should.equal('%2Fdbname')
|
||||
})
|
||||
|
||||
it('configuration parameter host treats encoded host as part of the db name', function () {
|
||||
const subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname?host=localhost')
|
||||
subject.user?.should.equal('user')
|
||||
subject.password?.should.equal('pass')
|
||||
subject.host?.should.equal('localhost')
|
||||
subject.database?.should.equal('%2Funix%2Fsocket/dbname')
|
||||
})
|
||||
|
||||
it('configuration parameter application_name', function () {
|
||||
const connectionString = 'pg:///?application_name=TheApp'
|
||||
const subject = parse(connectionString)
|
||||
subject.application_name?.should.equal('TheApp')
|
||||
})
|
||||
|
||||
it('configuration parameter fallback_application_name', function () {
|
||||
const connectionString = 'pg:///?fallback_application_name=TheAppFallback'
|
||||
const subject = parse(connectionString)
|
||||
subject.fallback_application_name?.should.equal('TheAppFallback')
|
||||
})
|
||||
|
||||
it('configuration parameter options', function () {
|
||||
const connectionString = 'pg:///?options=-c geqo=off'
|
||||
const subject = parse(connectionString)
|
||||
subject.options?.should.equal('-c geqo=off')
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true', function () {
|
||||
const connectionString = 'pg:///?ssl=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=1', function () {
|
||||
const connectionString = 'pg:///?ssl=1'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=0', function () {
|
||||
const connectionString = 'pg:///?ssl=0'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.equal(false)
|
||||
})
|
||||
|
||||
it('set ssl', function () {
|
||||
const subject = parse('pg://myhost/db?ssl=1')
|
||||
subject.ssl?.should.equal(true)
|
||||
})
|
||||
|
||||
it('configuration parameter sslcert=/path/to/cert', function () {
|
||||
const connectionString = 'pg:///?sslcert=' + __dirname + '/example.cert'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
cert: 'example cert\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslkey=/path/to/key', function () {
|
||||
const connectionString = 'pg:///?sslkey=' + __dirname + '/example.key'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
key: 'example key\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslrootcert=/path/to/ca', function () {
|
||||
const connectionString = 'pg:///?sslrootcert=' + __dirname + '/example.ca'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
ca: 'example ca\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=no-verify', function () {
|
||||
const connectionString = 'pg:///?sslmode=no-verify'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable', function () {
|
||||
const connectionString = 'pg:///?sslmode=disable'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer', function () {
|
||||
const connectionString = 'pg:///?sslmode=prefer'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require', function () {
|
||||
const connectionString = 'pg:///?sslmode=require'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-ca'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-full'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca', function () {
|
||||
const connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
ca: 'example ca\n',
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=disable&uselibpqcompat=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=prefer&uselibpqcompat=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=require&uselibpqcompat=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-ca&uselibpqcompat=true'
|
||||
expect(function () {
|
||||
parse(connectionString)
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('when throwing on invalid url does not print out the password in the error message', function () {
|
||||
const host = 'localhost'
|
||||
const port = 5432
|
||||
const user = 'user'
|
||||
const password = 'g#4624$@F$#v`'
|
||||
const database = 'db'
|
||||
|
||||
const connectionString = `postgres://${user}:${password}@${host}:${port}/${database}`
|
||||
expect(function () {
|
||||
parse(connectionString)
|
||||
}).to.throw()
|
||||
try {
|
||||
parse(connectionString)
|
||||
} catch (err: unknown) {
|
||||
expect(JSON.stringify(err)).to.not.include(password, 'Password should not be in the error message')
|
||||
expect(JSON.stringify(err)).to.include('REDACTED', 'The thrown error should contain the redacted URL')
|
||||
return
|
||||
}
|
||||
throw new Error('Expected an error to be thrown')
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca and sslrootcert with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-ca&uselibpqcompat=true&sslrootcert=' + __dirname + '/example.ca'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
// We prove above that the checkServerIdentity function is defined
|
||||
//
|
||||
// FIXME: remove this if we upgrade to TypeScript 5
|
||||
// @ts-ignore
|
||||
expect(subject.ssl.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full with uselibpqcompat query param', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-full&uselibpqcompat=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca with uselibpqcompat query param', function () {
|
||||
const connectionString =
|
||||
'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require&uselibpqcompat=true'
|
||||
const subject = parse(connectionString)
|
||||
subject.ssl?.should.have.property('ca', 'example ca\n')
|
||||
subject.ssl?.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
// We prove above that the checkServerIdentity function is defined
|
||||
//
|
||||
// FIXME: remove this if we upgrade to TypeScript 5
|
||||
// @ts-ignore
|
||||
expect(subject.ssl?.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=disable with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=disable'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.eql(false)
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=prefer with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=prefer'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=require with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=require'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.eql({
|
||||
rejectUnauthorized: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-ca'
|
||||
expect(function () {
|
||||
parse(connectionString, { useLibpqCompat: true })
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-ca and sslrootcert with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-ca&sslrootcert=' + __dirname + '/example.ca'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
// We prove above that the checkServerIdentity function is defined
|
||||
//
|
||||
// FIXME: remove this if we upgrade to TypeScript 5
|
||||
// @ts-ignore
|
||||
expect(subject.ssl?.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('configuration parameter sslmode=verify-full with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?sslmode=verify-full'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.eql({})
|
||||
})
|
||||
|
||||
it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca with useLibpqCompat option', function () {
|
||||
const connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require'
|
||||
const subject = parse(connectionString, { useLibpqCompat: true })
|
||||
subject.ssl?.should.have.property('ca', 'example ca\n')
|
||||
subject.ssl?.should.have.property('checkServerIdentity').that.is.a('function')
|
||||
// We prove above that the checkServerIdentity function is defined
|
||||
//
|
||||
// FIXME: remove this if we upgrade to TypeScript 5
|
||||
// @ts-ignore
|
||||
expect(subject.ssl?.checkServerIdentity()).be.undefined
|
||||
})
|
||||
|
||||
it('does not allow uselibpqcompat query parameter and useLibpqCompat option at the same time', function () {
|
||||
const connectionString = 'pg:///?uselibpqcompat=true'
|
||||
expect(function () {
|
||||
parse(connectionString, { useLibpqCompat: true })
|
||||
}).to.throw()
|
||||
})
|
||||
|
||||
it('allow other params like max, ...', function () {
|
||||
const subject = parse('pg://myhost/db?max=18&min=4')
|
||||
subject.max?.should.equal('18')
|
||||
subject.min?.should.equal('4')
|
||||
})
|
||||
|
||||
it('configuration parameter keepalives', function () {
|
||||
const connectionString = 'pg:///?keepalives=1'
|
||||
const subject = parse(connectionString)
|
||||
subject.keepalives?.should.equal('1')
|
||||
})
|
||||
|
||||
it('unknown configuration parameter is passed into client', function () {
|
||||
const connectionString = 'pg:///?ThereIsNoSuchPostgresParameter=1234'
|
||||
const subject = parse(connectionString)
|
||||
subject.ThereIsNoSuchPostgresParameter?.should.equal('1234')
|
||||
})
|
||||
|
||||
it('do not override a config field with value from query string', function () {
|
||||
const subject = parse('socket:/some path/?db=my[db]&encoding=utf8&client_encoding=bogus')
|
||||
subject.host?.should.equal('/some path/')
|
||||
subject.database?.should.equal('my[db]', 'must to be escaped and unescaped through "my%5Bdb%5D"')
|
||||
subject.client_encoding?.should.equal('utf8')
|
||||
})
|
||||
|
||||
it('return last value of repeated parameter', function () {
|
||||
const connectionString = 'pg:///?keepalives=1&keepalives=0'
|
||||
const subject = parse(connectionString)
|
||||
subject.keepalives?.should.equal('0')
|
||||
})
|
||||
|
||||
it('use the port specified in the query parameters', function () {
|
||||
const connectionString = 'postgres:///?host=localhost&port=1234'
|
||||
const subject = parse(connectionString)
|
||||
subject.port?.should.equal('1234')
|
||||
})
|
||||
})
|
||||
19
packages/pg-connection-string/tsconfig.json
Normal file
19
packages/pg-connection-string/tsconfig.json
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"target": "es6",
|
||||
"noImplicitAny": true,
|
||||
"moduleResolution": "node",
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"incremental": true,
|
||||
"baseUrl": ".",
|
||||
"declaration": true
|
||||
},
|
||||
"include": [
|
||||
"test/**/*"
|
||||
]
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
const pg = require('pg')
|
||||
const { Result, utils } = pg
|
||||
const prepare = utils.prepareValue
|
||||
// note: can remove these deep requires when we bump min version of pg to 9.x
|
||||
const Result = require('pg/lib/result.js')
|
||||
const prepare = require('pg/lib/utils.js').prepareValue
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const util = require('util')
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-cursor",
|
||||
"version": "2.14.5",
|
||||
"version": "2.15.3",
|
||||
"description": "Query cursor extension for node-postgres",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
@ -25,7 +25,7 @@
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"mocha": "^10.5.2",
|
||||
"pg": "^8.15.5"
|
||||
"pg": "^8.16.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg": "^8"
|
||||
|
||||
3
packages/pg-esm-test/README.md
Normal file
3
packages/pg-esm-test/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
This is an internal package for node-postgres used to test esm & cjs module export compatibility.
|
||||
|
||||
The only thing you really need to do is `yarn && yarn test` from the root of the project & these tests will run as well as all the other tests. So, basically, you can ignore this. 😄
|
||||
@ -5,9 +5,14 @@ const { describe, it } = test
|
||||
const paths = [
|
||||
'pg',
|
||||
'pg/lib/index.js',
|
||||
'pg/lib/index',
|
||||
'pg/lib/connection-parameters',
|
||||
'pg/lib/connection-parameters.js',
|
||||
'pg/lib/type-overrides',
|
||||
'pg-protocol/dist/messages.js',
|
||||
'pg-protocol/dist/messages',
|
||||
'pg-native/lib/build-result.js',
|
||||
'pg-cloudflare/package.json',
|
||||
]
|
||||
for (const path of paths) {
|
||||
describe(`importing ${path}`, () => {
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "pg-esm-test",
|
||||
"version": "1.1.5",
|
||||
"version": "1.2.3",
|
||||
"description": "A test module for PostgreSQL with ESM support",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --test"
|
||||
"test": "node --test --conditions=workerd"
|
||||
},
|
||||
"keywords": [
|
||||
"postgres",
|
||||
@ -14,13 +14,13 @@
|
||||
"test"
|
||||
],
|
||||
"devDependencies": {
|
||||
"pg": "^8.15.5",
|
||||
"pg-cloudflare": "^1.2.5",
|
||||
"pg-cursor": "^2.14.5",
|
||||
"pg-native": "^3.4.5",
|
||||
"pg-pool": "^3.9.5",
|
||||
"pg-protocol": "^1.9.5",
|
||||
"pg-query-stream": "^4.9.5"
|
||||
"pg": "^8.16.3",
|
||||
"pg-cloudflare": "^1.2.7",
|
||||
"pg-cursor": "^2.15.3",
|
||||
"pg-native": "^3.5.2",
|
||||
"pg-pool": "^3.10.1",
|
||||
"pg-protocol": "^1.10.3",
|
||||
"pg-query-stream": "^4.10.3"
|
||||
},
|
||||
"author": "Brian M. Carlson <brian.m.carlson@gmail.com>",
|
||||
"license": "MIT"
|
||||
|
||||
@ -30,40 +30,40 @@ $ npm i pg-native
|
||||
### async
|
||||
|
||||
```js
|
||||
var Client = require('pg-native')
|
||||
const Client = require('pg-native')
|
||||
|
||||
var client = new Client();
|
||||
const client = new Client();
|
||||
client.connect(function(err) {
|
||||
if(err) throw err
|
||||
|
||||
//text queries
|
||||
// text queries
|
||||
client.query('SELECT NOW() AS the_date', function(err, rows) {
|
||||
if(err) throw err
|
||||
|
||||
console.log(rows[0].the_date) //Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)
|
||||
console.log(rows[0].the_date) // Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)
|
||||
|
||||
//parameterized statements
|
||||
// parameterized statements
|
||||
client.query('SELECT $1::text as twitter_handle', ['@briancarlson'], function(err, rows) {
|
||||
if(err) throw err
|
||||
|
||||
console.log(rows[0].twitter_handle) //@briancarlson
|
||||
})
|
||||
|
||||
//prepared statements
|
||||
// prepared statements
|
||||
client.prepare('get_twitter', 'SELECT $1::text as twitter_handle', 1, function(err) {
|
||||
if(err) throw err
|
||||
|
||||
//execute the prepared, named statement
|
||||
// execute the prepared, named statement
|
||||
client.execute('get_twitter', ['@briancarlson'], function(err, rows) {
|
||||
if(err) throw err
|
||||
|
||||
console.log(rows[0].twitter_handle) //@briancarlson
|
||||
|
||||
//execute the prepared, named statement again
|
||||
// execute the prepared, named statement again
|
||||
client.execute('get_twitter', ['@realcarrotfacts'], function(err, rows) {
|
||||
if(err) throw err
|
||||
|
||||
console.log(rows[0].twitter_handle) //@realcarrotfacts
|
||||
console.log(rows[0].twitter_handle) // @realcarrotfacts
|
||||
|
||||
client.end(function() {
|
||||
console.log('ended')
|
||||
@ -81,27 +81,27 @@ client.connect(function(err) {
|
||||
Because `pg-native` is bound to [libpq](https://github.com/brianc/node-libpq) it is able to provide _sync_ operations for both connecting and queries. This is a bad idea in _non-blocking systems_ like web servers, but is exteremly convienent in scripts and bootstrapping applications - much the same way `fs.readFileSync` comes in handy.
|
||||
|
||||
```js
|
||||
var Client = require('pg-native')
|
||||
const Client = require('pg-native')
|
||||
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
|
||||
//text queries
|
||||
var rows = client.querySync('SELECT NOW() AS the_date')
|
||||
console.log(rows[0].the_date) //Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)
|
||||
// text queries
|
||||
const rows = client.querySync('SELECT NOW() AS the_date')
|
||||
console.log(rows[0].the_date) // Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)
|
||||
|
||||
//parameterized queries
|
||||
var rows = client.querySync('SELECT $1::text as twitter_handle', ['@briancarlson'])
|
||||
console.log(rows[0].twitter_handle) //@briancarlson
|
||||
// parameterized queries
|
||||
const rows = client.querySync('SELECT $1::text as twitter_handle', ['@briancarlson'])
|
||||
console.log(rows[0].twitter_handle) // @briancarlson
|
||||
|
||||
//prepared statements
|
||||
// prepared statements
|
||||
client.prepareSync('get_twitter', 'SELECT $1::text as twitter_handle', 1)
|
||||
|
||||
var rows = client.executeSync('get_twitter', ['@briancarlson'])
|
||||
console.log(rows[0].twitter_handle) //@briancarlson
|
||||
const rows = client.executeSync('get_twitter', ['@briancarlson'])
|
||||
console.log(rows[0].twitter_handle) // @briancarlson
|
||||
|
||||
var rows = client.executeSync('get_twitter', ['@realcarrotfacts'])
|
||||
console.log(rows[0].twitter_handle) //@realcarrotfacts
|
||||
const rows = client.executeSync('get_twitter', ['@realcarrotfacts'])
|
||||
console.log(rows[0].twitter_handle) // @realcarrotfacts
|
||||
```
|
||||
|
||||
## api
|
||||
@ -125,14 +125,14 @@ Returns an `Error` to the `callback` if the connection was unsuccessful. `callb
|
||||
##### example
|
||||
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function(err) {
|
||||
if(err) throw err
|
||||
|
||||
console.log('connected!')
|
||||
})
|
||||
|
||||
var client2 = new Client()
|
||||
const client2 = new Client()
|
||||
client2.connect('postgresql://user:password@host:5432/database?param=value', function(err) {
|
||||
if(err) throw err
|
||||
|
||||
@ -147,7 +147,7 @@ Execute a query with the text of `queryText` and _optional_ parameters specified
|
||||
##### example
|
||||
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function(err) {
|
||||
if (err) throw err
|
||||
|
||||
@ -175,7 +175,7 @@ Prepares a _named statement_ for later execution. You _must_ supply the name of
|
||||
##### example
|
||||
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function(err) {
|
||||
if(err) throw err
|
||||
|
||||
@ -197,7 +197,7 @@ Executes a previously prepared statement on this client with the name of `statem
|
||||
|
||||
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function(err) {
|
||||
if(err) throw err
|
||||
|
||||
@ -221,7 +221,7 @@ Ends the connection. Calls the _optional_ callback when the connection is termin
|
||||
##### example
|
||||
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function(err) {
|
||||
if(err) throw err
|
||||
client.end(function() {
|
||||
@ -236,9 +236,9 @@ Cancels the active query on the client. Callback receives an error if there was
|
||||
|
||||
##### example
|
||||
```js
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
//sleep for 100 seconds
|
||||
// sleep for 100 seconds
|
||||
client.query('select pg_sleep(100)', function(err) {
|
||||
console.log(err) // [Error: ERROR: canceling statement due to user request]
|
||||
})
|
||||
@ -264,7 +264,7 @@ Prepares a name statement with name of `statementName` and a query text of `quer
|
||||
|
||||
- __`client.executeSync(statementName:string, <values:string[]>) -> results:Object[]`__
|
||||
|
||||
Executes a previously prepared statement on this client with the name of `statementName`, passing it the optional array of query paramters as a `values` array. Throws an `Error` if the execution fails, otherwas returns an array of results.
|
||||
Executes a previously prepared statement on this client with the name of `statementName`, passing it the optional array of query parameters as a `values` array. Throws an `Error` if the execution fails, otherwise returns an array of results.
|
||||
|
||||
## testing
|
||||
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
var pg = require('pg').native
|
||||
var Native = require('../')
|
||||
const pg = require('pg').native
|
||||
const Native = require('../')
|
||||
|
||||
var warmup = function (fn, cb) {
|
||||
var count = 0
|
||||
var max = 10
|
||||
var run = function (err) {
|
||||
const warmup = function (fn, cb) {
|
||||
let count = 0
|
||||
const max = 10
|
||||
const run = function (err) {
|
||||
if (err) return cb(err)
|
||||
|
||||
if (max >= count++) {
|
||||
@ -16,26 +16,26 @@ var warmup = function (fn, cb) {
|
||||
run()
|
||||
}
|
||||
|
||||
var native = Native()
|
||||
const native = Native()
|
||||
native.connectSync()
|
||||
|
||||
var queryText = 'SELECT generate_series(0, 1000) as X, generate_series(0, 1000) as Y, generate_series(0, 1000) as Z'
|
||||
var client = new pg.Client()
|
||||
const queryText = 'SELECT generate_series(0, 1000) as X, generate_series(0, 1000) as Y, generate_series(0, 1000) as Z'
|
||||
const client = new pg.Client()
|
||||
client.connect(function () {
|
||||
var pure = function (cb) {
|
||||
const pure = function (cb) {
|
||||
client.query(queryText, function (err) {
|
||||
if (err) throw err
|
||||
cb(err)
|
||||
})
|
||||
}
|
||||
var nativeQuery = function (cb) {
|
||||
const nativeQuery = function (cb) {
|
||||
native.query(queryText, function (err) {
|
||||
if (err) throw err
|
||||
cb(err)
|
||||
})
|
||||
}
|
||||
|
||||
var run = function () {
|
||||
const run = function () {
|
||||
console.time('pure')
|
||||
warmup(pure, function () {
|
||||
console.timeEnd('pure')
|
||||
|
||||
@ -1,29 +1,29 @@
|
||||
var Client = require('../')
|
||||
var async = require('async')
|
||||
const Client = require('../')
|
||||
const async = require('async')
|
||||
|
||||
var loop = function () {
|
||||
var client = new Client()
|
||||
const loop = function () {
|
||||
const client = new Client()
|
||||
|
||||
var connect = function (cb) {
|
||||
const connect = function (cb) {
|
||||
client.connect(cb)
|
||||
}
|
||||
|
||||
var simpleQuery = function (cb) {
|
||||
const simpleQuery = function (cb) {
|
||||
client.query('SELECT NOW()', cb)
|
||||
}
|
||||
|
||||
var paramsQuery = function (cb) {
|
||||
const paramsQuery = function (cb) {
|
||||
client.query('SELECT $1::text as name', ['Brian'], cb)
|
||||
}
|
||||
|
||||
var prepared = function (cb) {
|
||||
const prepared = function (cb) {
|
||||
client.prepare('test', 'SELECT $1::text as name', 1, function (err) {
|
||||
if (err) return cb(err)
|
||||
client.execute('test', ['Brian'], cb)
|
||||
})
|
||||
}
|
||||
|
||||
var sync = function (cb) {
|
||||
const sync = function (cb) {
|
||||
client.querySync('SELECT NOW()')
|
||||
client.querySync('SELECT $1::text as name', ['Brian'])
|
||||
client.prepareSync('boom', 'SELECT $1::text as name', 1)
|
||||
@ -31,16 +31,16 @@ var loop = function () {
|
||||
setImmediate(cb)
|
||||
}
|
||||
|
||||
var end = function (cb) {
|
||||
const end = function (cb) {
|
||||
client.end(cb)
|
||||
}
|
||||
|
||||
var ops = [connect, simpleQuery, paramsQuery, prepared, sync, end]
|
||||
const ops = [connect, simpleQuery, paramsQuery, prepared, sync, end]
|
||||
|
||||
var start = Date.now()
|
||||
const start = performance.now()
|
||||
async.series(ops, function (err) {
|
||||
if (err) throw err
|
||||
console.log(Date.now() - start)
|
||||
console.log(performance.now() - start)
|
||||
setImmediate(loop)
|
||||
})
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
var Libpq = require('libpq')
|
||||
var EventEmitter = require('events').EventEmitter
|
||||
var util = require('util')
|
||||
var assert = require('assert')
|
||||
var types = require('pg-types')
|
||||
var buildResult = require('./lib/build-result')
|
||||
var CopyStream = require('./lib/copy-stream')
|
||||
const Libpq = require('libpq')
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const util = require('util')
|
||||
const assert = require('assert')
|
||||
const types = require('pg-types')
|
||||
const buildResult = require('./lib/build-result')
|
||||
const CopyStream = require('./lib/copy-stream')
|
||||
|
||||
var Client = (module.exports = function (config) {
|
||||
const Client = (module.exports = function (config) {
|
||||
if (!(this instanceof Client)) {
|
||||
return new Client(config)
|
||||
}
|
||||
@ -18,7 +18,7 @@ var Client = (module.exports = function (config) {
|
||||
this._reading = false
|
||||
this._read = this._read.bind(this)
|
||||
|
||||
// allow custom type converstion to be passed in
|
||||
// allow custom type conversion to be passed in
|
||||
this._types = config.types || types
|
||||
|
||||
// allow config to specify returning results
|
||||
@ -51,34 +51,31 @@ Client.prototype.connectSync = function (params) {
|
||||
}
|
||||
|
||||
Client.prototype.query = function (text, values, cb) {
|
||||
var queryFn
|
||||
let queryFn
|
||||
|
||||
if (typeof values === 'function') {
|
||||
cb = values
|
||||
}
|
||||
|
||||
if (Array.isArray(values)) {
|
||||
queryFn = function () {
|
||||
return self.pq.sendQueryParams(text, values)
|
||||
queryFn = () => {
|
||||
return this.pq.sendQueryParams(text, values)
|
||||
}
|
||||
} else {
|
||||
queryFn = function () {
|
||||
return self.pq.sendQuery(text)
|
||||
queryFn = () => {
|
||||
return this.pq.sendQuery(text)
|
||||
}
|
||||
}
|
||||
|
||||
var self = this
|
||||
|
||||
self._dispatchQuery(self.pq, queryFn, function (err) {
|
||||
this._dispatchQuery(this.pq, queryFn, (err) => {
|
||||
if (err) return cb(err)
|
||||
|
||||
self._awaitResult(cb)
|
||||
this._awaitResult(cb)
|
||||
})
|
||||
}
|
||||
|
||||
Client.prototype.prepare = function (statementName, text, nParams, cb) {
|
||||
var self = this
|
||||
var fn = function () {
|
||||
const self = this
|
||||
const fn = function () {
|
||||
return self.pq.sendPrepare(statementName, text, nParams)
|
||||
}
|
||||
|
||||
@ -89,9 +86,9 @@ Client.prototype.prepare = function (statementName, text, nParams, cb) {
|
||||
}
|
||||
|
||||
Client.prototype.execute = function (statementName, parameters, cb) {
|
||||
var self = this
|
||||
const self = this
|
||||
|
||||
var fn = function () {
|
||||
const fn = function () {
|
||||
return self.pq.sendQueryPrepared(statementName, parameters)
|
||||
}
|
||||
|
||||
@ -111,7 +108,7 @@ Client.prototype.getCopyStream = function () {
|
||||
Client.prototype.cancel = function (cb) {
|
||||
assert(cb, 'Callback is required')
|
||||
// result is either true or a string containing an error
|
||||
var result = this.pq.cancel()
|
||||
const result = this.pq.cancel()
|
||||
return setImmediate(function () {
|
||||
cb(result === true ? undefined : new Error(result))
|
||||
})
|
||||
@ -158,7 +155,7 @@ Client.prototype.end = function (cb) {
|
||||
}
|
||||
|
||||
Client.prototype._readError = function (message) {
|
||||
var err = new Error(message || this.pq.errorMessage())
|
||||
const err = new Error(message || this.pq.errorMessage())
|
||||
this.emit('error', err)
|
||||
}
|
||||
|
||||
@ -174,7 +171,7 @@ Client.prototype._consumeQueryResults = function (pq) {
|
||||
}
|
||||
|
||||
Client.prototype._emitResult = function (pq) {
|
||||
var status = pq.resultStatus()
|
||||
const status = pq.resultStatus()
|
||||
switch (status) {
|
||||
case 'PGRES_FATAL_ERROR':
|
||||
this._queryError = new Error(this.pq.resultErrorMessage())
|
||||
@ -203,7 +200,7 @@ Client.prototype._emitResult = function (pq) {
|
||||
|
||||
// called when libpq is readable
|
||||
Client.prototype._read = function () {
|
||||
var pq = this.pq
|
||||
const pq = this.pq
|
||||
// read waiting data from the socket
|
||||
// e.g. clear the pending 'select'
|
||||
if (!pq.consumeInput()) {
|
||||
@ -238,7 +235,7 @@ Client.prototype._read = function () {
|
||||
|
||||
this.emit('readyForQuery')
|
||||
|
||||
var notice = this.pq.notifies()
|
||||
let notice = this.pq.notifies()
|
||||
while (notice) {
|
||||
this.emit('notification', notice)
|
||||
notice = this.pq.notifies()
|
||||
@ -254,8 +251,8 @@ Client.prototype._startReading = function () {
|
||||
this.pq.startReader()
|
||||
}
|
||||
|
||||
var throwIfError = function (pq) {
|
||||
var err = pq.resultErrorMessage() || pq.errorMessage()
|
||||
const throwIfError = function (pq) {
|
||||
const err = pq.resultErrorMessage() || pq.errorMessage()
|
||||
if (err) {
|
||||
throw new Error(err)
|
||||
}
|
||||
@ -268,7 +265,7 @@ Client.prototype._awaitResult = function (cb) {
|
||||
|
||||
// wait for the writable socket to drain
|
||||
Client.prototype._waitForDrain = function (pq, cb) {
|
||||
var res = pq.flush()
|
||||
const res = pq.flush()
|
||||
// res of 0 is success
|
||||
if (res === 0) return cb()
|
||||
|
||||
@ -277,7 +274,7 @@ Client.prototype._waitForDrain = function (pq, cb) {
|
||||
|
||||
// otherwise outgoing message didn't flush to socket
|
||||
// wait for it to flush and try again
|
||||
var self = this
|
||||
const self = this
|
||||
// you cannot read & write on a socket at the same time
|
||||
return pq.writable(function () {
|
||||
self._waitForDrain(pq, cb)
|
||||
@ -288,9 +285,9 @@ Client.prototype._waitForDrain = function (pq, cb) {
|
||||
// finish writing query text to the socket
|
||||
Client.prototype._dispatchQuery = function (pq, fn, cb) {
|
||||
this._stopReading()
|
||||
var success = pq.setNonBlocking(true)
|
||||
const success = pq.setNonBlocking(true)
|
||||
if (!success) return cb(new Error('Unable to set non-blocking to true'))
|
||||
var sent = fn()
|
||||
const sent = fn()
|
||||
if (!sent) return cb(new Error(pq.errorMessage() || 'Something went wrong dispatching the query'))
|
||||
this._waitForDrain(pq, cb)
|
||||
}
|
||||
|
||||
@ -20,9 +20,9 @@ class Result {
|
||||
consumeFields(pq) {
|
||||
const nfields = pq.nfields()
|
||||
this.fields = new Array(nfields)
|
||||
var row = {}
|
||||
for (var x = 0; x < nfields; x++) {
|
||||
var name = pq.fname(x)
|
||||
const row = {}
|
||||
for (let x = 0; x < nfields; x++) {
|
||||
const name = pq.fname(x)
|
||||
row[name] = null
|
||||
this.fields[x] = {
|
||||
name: name,
|
||||
@ -35,14 +35,14 @@ class Result {
|
||||
consumeRows(pq) {
|
||||
const tupleCount = pq.ntuples()
|
||||
this.rows = new Array(tupleCount)
|
||||
for (var i = 0; i < tupleCount; i++) {
|
||||
for (let i = 0; i < tupleCount; i++) {
|
||||
this.rows[i] = this._arrayMode ? this.consumeRowAsArray(pq, i) : this.consumeRowAsObject(pq, i)
|
||||
}
|
||||
}
|
||||
|
||||
consumeRowAsObject(pq, rowIndex) {
|
||||
const row = { ...this._prebuiltEmptyResultObject }
|
||||
for (var j = 0; j < this.fields.length; j++) {
|
||||
for (let j = 0; j < this.fields.length; j++) {
|
||||
row[this.fields[j].name] = this.readValue(pq, rowIndex, j)
|
||||
}
|
||||
return row
|
||||
@ -50,14 +50,14 @@ class Result {
|
||||
|
||||
consumeRowAsArray(pq, rowIndex) {
|
||||
const row = new Array(this.fields.length)
|
||||
for (var j = 0; j < this.fields.length; j++) {
|
||||
for (let j = 0; j < this.fields.length; j++) {
|
||||
row[j] = this.readValue(pq, rowIndex, j)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
readValue(pq, rowIndex, colIndex) {
|
||||
var rawValue = pq.getvalue(rowIndex, colIndex)
|
||||
const rawValue = pq.getvalue(rowIndex, colIndex)
|
||||
if (rawValue === '' && pq.getisnull(rowIndex, colIndex)) {
|
||||
return null
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
var Duplex = require('stream').Duplex
|
||||
var Writable = require('stream').Writable
|
||||
var util = require('util')
|
||||
const Duplex = require('stream').Duplex
|
||||
const Writable = require('stream').Writable
|
||||
const util = require('util')
|
||||
|
||||
var CopyStream = (module.exports = function (pq, options) {
|
||||
const CopyStream = (module.exports = function (pq, options) {
|
||||
Duplex.call(this, options)
|
||||
this.pq = pq
|
||||
this._reading = false
|
||||
@ -12,7 +12,7 @@ util.inherits(CopyStream, Duplex)
|
||||
|
||||
// writer methods
|
||||
CopyStream.prototype._write = function (chunk, encoding, cb) {
|
||||
var result = this.pq.putCopyData(chunk)
|
||||
const result = this.pq.putCopyData(chunk)
|
||||
|
||||
// sent successfully
|
||||
if (result === 1) return cb()
|
||||
@ -21,22 +21,22 @@ CopyStream.prototype._write = function (chunk, encoding, cb) {
|
||||
if (result === -1) return cb(new Error(this.pq.errorMessage()))
|
||||
|
||||
// command would block. wait for writable and call again.
|
||||
var self = this
|
||||
const self = this
|
||||
this.pq.writable(function () {
|
||||
self._write(chunk, encoding, cb)
|
||||
})
|
||||
}
|
||||
|
||||
CopyStream.prototype.end = function () {
|
||||
var args = Array.prototype.slice.call(arguments, 0)
|
||||
var self = this
|
||||
const args = Array.prototype.slice.call(arguments, 0)
|
||||
const self = this
|
||||
|
||||
var callback = args.pop()
|
||||
const callback = args.pop()
|
||||
|
||||
if (args.length) {
|
||||
this.write(args[0])
|
||||
}
|
||||
var result = this.pq.putCopyEnd()
|
||||
const result = this.pq.putCopyEnd()
|
||||
|
||||
// sent successfully
|
||||
if (result === 1) {
|
||||
@ -55,7 +55,7 @@ CopyStream.prototype.end = function () {
|
||||
|
||||
// error
|
||||
if (result === -1) {
|
||||
var err = new Error(this.pq.errorMessage())
|
||||
const err = new Error(this.pq.errorMessage())
|
||||
return this.emit('error', err)
|
||||
}
|
||||
|
||||
@ -70,7 +70,7 @@ CopyStream.prototype.end = function () {
|
||||
|
||||
// reader methods
|
||||
CopyStream.prototype._consumeBuffer = function (cb) {
|
||||
var result = this.pq.getCopyData(true)
|
||||
const result = this.pq.getCopyData(true)
|
||||
if (result instanceof Buffer) {
|
||||
return setImmediate(function () {
|
||||
cb(null, result)
|
||||
@ -81,7 +81,7 @@ CopyStream.prototype._consumeBuffer = function (cb) {
|
||||
return cb(null, null)
|
||||
}
|
||||
if (result === 0) {
|
||||
var self = this
|
||||
const self = this
|
||||
this.pq.once('readable', function () {
|
||||
self.pq.stopReader()
|
||||
self.pq.consumeInput()
|
||||
@ -96,7 +96,7 @@ CopyStream.prototype._read = function (size) {
|
||||
if (this._reading) return
|
||||
this._reading = true
|
||||
// console.log('read begin');
|
||||
var self = this
|
||||
const self = this
|
||||
this._consumeBuffer(function (err, buffer) {
|
||||
self._reading = false
|
||||
if (err) {
|
||||
@ -110,18 +110,18 @@ CopyStream.prototype._read = function (size) {
|
||||
})
|
||||
}
|
||||
|
||||
var consumeResults = function (pq, cb) {
|
||||
var cleanup = function () {
|
||||
const consumeResults = function (pq, cb) {
|
||||
const cleanup = function () {
|
||||
pq.removeListener('readable', onReadable)
|
||||
pq.stopReader()
|
||||
}
|
||||
|
||||
var readError = function (message) {
|
||||
const readError = function (message) {
|
||||
cleanup()
|
||||
return cb(new Error(message || pq.errorMessage()))
|
||||
}
|
||||
|
||||
var onReadable = function () {
|
||||
const onReadable = function () {
|
||||
// read waiting data from the socket
|
||||
// e.g. clear the pending 'select'
|
||||
if (!pq.consumeInput()) {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-native",
|
||||
"version": "3.4.5",
|
||||
"version": "3.5.2",
|
||||
"description": "A slightly nicer interface to Postgres over node-libpq",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
@ -34,8 +34,8 @@
|
||||
},
|
||||
"homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-native",
|
||||
"dependencies": {
|
||||
"libpq": "1.8.14",
|
||||
"pg-types": "^2.1.0"
|
||||
"libpq": "^1.8.15",
|
||||
"pg-types": "2.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"async": "^0.9.0",
|
||||
@ -45,7 +45,7 @@
|
||||
"mocha": "10.5.2",
|
||||
"node-gyp": ">=10.x",
|
||||
"okay": "^0.3.0",
|
||||
"semver": "^4.1.0"
|
||||
"semver": "^7.7.2"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('client with arrayMode', function () {
|
||||
it('returns result as array', function (done) {
|
||||
var client = new Client({ arrayMode: true })
|
||||
const client = new Client({ arrayMode: true })
|
||||
client.connectSync()
|
||||
client.querySync('CREATE TEMP TABLE blah(name TEXT)')
|
||||
client.querySync('INSERT INTO blah (name) VALUES ($1)', ['brian'])
|
||||
client.querySync('INSERT INTO blah (name) VALUES ($1)', ['aaron'])
|
||||
var rows = client.querySync('SELECT * FROM blah')
|
||||
const rows = client.querySync('SELECT * FROM blah')
|
||||
assert.equal(rows.length, 2)
|
||||
var row = rows[0]
|
||||
const row = rows[0]
|
||||
assert.equal(row.length, 1)
|
||||
assert.equal(row[0], 'brian')
|
||||
assert.equal(rows[1][0], 'aaron')
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
var Client = require('../')
|
||||
var ok = require('okay')
|
||||
var assert = require('assert')
|
||||
var concat = require('concat-stream')
|
||||
const Client = require('../')
|
||||
const ok = require('okay')
|
||||
const assert = require('assert')
|
||||
const concat = require('concat-stream')
|
||||
|
||||
describe('async workflow', function () {
|
||||
before(function (done) {
|
||||
@ -9,7 +9,7 @@ describe('async workflow', function () {
|
||||
this.client.connect(done)
|
||||
})
|
||||
|
||||
var echoParams = function (params, cb) {
|
||||
const echoParams = function (params, cb) {
|
||||
this.client.query(
|
||||
'SELECT $1::text as first, $2::text as second',
|
||||
params,
|
||||
@ -20,20 +20,20 @@ describe('async workflow', function () {
|
||||
)
|
||||
}
|
||||
|
||||
var checkParams = function (params, rows) {
|
||||
const checkParams = function (params, rows) {
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].first, params[0])
|
||||
assert.equal(rows[0].second, params[1])
|
||||
}
|
||||
|
||||
it('sends async query', function (done) {
|
||||
var params = ['one', 'two']
|
||||
const params = ['one', 'two']
|
||||
echoParams.call(this, params, done)
|
||||
})
|
||||
|
||||
it('sends multiple async queries', function (done) {
|
||||
var self = this
|
||||
var params = ['bang', 'boom']
|
||||
const self = this
|
||||
const params = ['bang', 'boom']
|
||||
echoParams.call(
|
||||
this,
|
||||
params,
|
||||
@ -44,13 +44,13 @@ describe('async workflow', function () {
|
||||
})
|
||||
|
||||
it('sends an async query, copies in, copies out, and sends another query', function (done) {
|
||||
var self = this
|
||||
const self = this
|
||||
this.client.querySync('CREATE TEMP TABLE test(name text, age int)')
|
||||
this.client.query(
|
||||
"INSERT INTO test(name, age) VALUES('brian', 32)",
|
||||
ok(done, function () {
|
||||
self.client.querySync('COPY test FROM stdin')
|
||||
var input = self.client.getCopyStream()
|
||||
const input = self.client.getCopyStream()
|
||||
input.write(Buffer.from('Aaron\t30\n', 'utf8'))
|
||||
input.end(function () {
|
||||
self.client.query(
|
||||
@ -60,7 +60,7 @@ describe('async workflow', function () {
|
||||
self.client.query(
|
||||
'COPY test TO stdout',
|
||||
ok(done, function () {
|
||||
var output = self.client.getCopyStream()
|
||||
const output = self.client.getCopyStream()
|
||||
|
||||
// pump the stream
|
||||
output.read()
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('cancel query', function () {
|
||||
it('works', function (done) {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
client.query('SELECT pg_sleep(1000);', function (err) {
|
||||
assert(err instanceof Error)
|
||||
@ -17,7 +17,7 @@ describe('cancel query', function () {
|
||||
})
|
||||
|
||||
it('does not raise error if no active query', function (done) {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
client.cancel(function (err) {
|
||||
assert.ifError(err)
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('connection errors', function () {
|
||||
it('raise error events', function (done) {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
client.query('SELECT pg_terminate_backend(pg_backend_pid())', assert.fail)
|
||||
client.on('error', function (err) {
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('connection error', function () {
|
||||
it('doesnt segfault', function (done) {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect('asldgsdgasgdasdg', function (err) {
|
||||
assert(err)
|
||||
// calling error on a closed client was segfaulting
|
||||
@ -15,7 +15,7 @@ describe('connection error', function () {
|
||||
|
||||
describe('reading while not connected', function () {
|
||||
it('does not seg fault but does throw execption', function () {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
assert.throws(function () {
|
||||
client.on('notification', function (msg) {})
|
||||
})
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var assert = require('assert')
|
||||
var Client = require('../')
|
||||
const assert = require('assert')
|
||||
const Client = require('../')
|
||||
|
||||
describe('COPY FROM', function () {
|
||||
before(function (done) {
|
||||
@ -12,17 +12,17 @@ describe('COPY FROM', function () {
|
||||
})
|
||||
|
||||
it('works', function (done) {
|
||||
var client = this.client
|
||||
const client = this.client
|
||||
this.client.querySync('CREATE TEMP TABLE blah(name text, age int)')
|
||||
this.client.querySync('COPY blah FROM stdin')
|
||||
var stream = this.client.getCopyStream()
|
||||
const stream = this.client.getCopyStream()
|
||||
stream.write(Buffer.from('Brian\t32\n', 'utf8'))
|
||||
stream.write(Buffer.from('Aaron\t30\n', 'utf8'))
|
||||
stream.write(Buffer.from('Shelley\t28\n', 'utf8'))
|
||||
stream.end()
|
||||
|
||||
stream.once('finish', function () {
|
||||
var rows = client.querySync('SELECT COUNT(*) FROM blah')
|
||||
const rows = client.querySync('SELECT COUNT(*) FROM blah')
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].count, 3)
|
||||
done()
|
||||
@ -30,14 +30,14 @@ describe('COPY FROM', function () {
|
||||
})
|
||||
|
||||
it('works with a callback passed to end', function (done) {
|
||||
var client = this.client
|
||||
const client = this.client
|
||||
this.client.querySync('CREATE TEMP TABLE boom(name text, age int)')
|
||||
this.client.querySync('COPY boom FROM stdin')
|
||||
var stream = this.client.getCopyStream()
|
||||
const stream = this.client.getCopyStream()
|
||||
stream.write(Buffer.from('Brian\t32\n', 'utf8'))
|
||||
stream.write(Buffer.from('Aaron\t30\n', 'utf8'), function () {
|
||||
stream.end(Buffer.from('Shelley\t28\n', 'utf8'), function () {
|
||||
var rows = client.querySync('SELECT COUNT(*) FROM boom')
|
||||
const rows = client.querySync('SELECT COUNT(*) FROM boom')
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].count, 3)
|
||||
done()
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
var assert = require('assert')
|
||||
var Client = require('../')
|
||||
var concat = require('concat-stream')
|
||||
var _ = require('lodash')
|
||||
const assert = require('assert')
|
||||
const Client = require('../')
|
||||
const concat = require('concat-stream')
|
||||
const _ = require('lodash')
|
||||
|
||||
describe('COPY TO', function () {
|
||||
before(function (done) {
|
||||
@ -14,18 +14,18 @@ describe('COPY TO', function () {
|
||||
})
|
||||
|
||||
it('works - basic check', function (done) {
|
||||
var limit = 1000
|
||||
var qText = 'COPY (SELECT * FROM generate_series(0, ' + (limit - 1) + ')) TO stdout'
|
||||
var self = this
|
||||
const limit = 1000
|
||||
const qText = 'COPY (SELECT * FROM generate_series(0, ' + (limit - 1) + ')) TO stdout'
|
||||
const self = this
|
||||
this.client.query(qText, function (err) {
|
||||
if (err) return done(err)
|
||||
var stream = self.client.getCopyStream()
|
||||
const stream = self.client.getCopyStream()
|
||||
// pump the stream for node v0.11.x
|
||||
stream.read()
|
||||
stream.pipe(
|
||||
concat(function (buff) {
|
||||
var res = buff.toString('utf8')
|
||||
var expected = _.range(0, limit).join('\n') + '\n'
|
||||
const res = buff.toString('utf8')
|
||||
const expected = _.range(0, limit).join('\n') + '\n'
|
||||
assert.equal(res, expected)
|
||||
done()
|
||||
})
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
var Client = require('../')
|
||||
var ok = require('okay')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const ok = require('okay')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('Custom type parser', function () {
|
||||
it('is used by client', function (done) {
|
||||
var client = new Client({
|
||||
const client = new Client({
|
||||
types: {
|
||||
getTypeParser: function () {
|
||||
return function () {
|
||||
@ -14,7 +14,7 @@ describe('Custom type parser', function () {
|
||||
},
|
||||
})
|
||||
client.connectSync()
|
||||
var rows = client.querySync('SELECT NOW() AS when')
|
||||
const rows = client.querySync('SELECT NOW() AS when')
|
||||
assert.equal(rows[0].when, 'blah')
|
||||
client.query(
|
||||
'SELECT NOW() as when',
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
var checkDomain = function (domain, when) {
|
||||
const checkDomain = function (domain, when) {
|
||||
assert(process.domain, 'Domain was lost after ' + when)
|
||||
assert.strictEqual(process.domain, domain, 'Domain switched after ' + when)
|
||||
}
|
||||
|
||||
describe('domains', function () {
|
||||
it('remains bound after a query', function (done) {
|
||||
var domain = require('domain').create() // eslint-disable-line
|
||||
const domain = require('domain').create()
|
||||
domain.run(function () {
|
||||
var client = new Client()
|
||||
const client = new Client()
|
||||
client.connect(function () {
|
||||
checkDomain(domain, 'connection')
|
||||
client.query('SELECT NOW()', function () {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('empty query', () => {
|
||||
it('has field metadata in result', (done) => {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('huge async query', function () {
|
||||
before(function (done) {
|
||||
@ -12,12 +12,12 @@ describe('huge async query', function () {
|
||||
})
|
||||
|
||||
it('works', function (done) {
|
||||
var params = ['']
|
||||
var len = 100000
|
||||
for (var i = 0; i < len; i++) {
|
||||
const params = ['']
|
||||
const len = 100000
|
||||
for (let i = 0; i < len; i++) {
|
||||
params[0] += 'A'
|
||||
}
|
||||
var qText = "SELECT '" + params[0] + "'::text as my_text"
|
||||
const qText = "SELECT '" + params[0] + "'::text as my_text"
|
||||
this.client.query(qText, function (err, rows) {
|
||||
if (err) return done(err)
|
||||
assert.equal(rows[0].my_text.length, len)
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('connection', function () {
|
||||
it('works', function (done) {
|
||||
@ -24,7 +24,7 @@ describe('connectSync', function () {
|
||||
})
|
||||
|
||||
it('works with args', function () {
|
||||
var args = 'host=' + (process.env.PGHOST || 'localhost')
|
||||
const args = 'host=' + (process.env.PGHOST || 'localhost')
|
||||
Client().connectSync(args)
|
||||
})
|
||||
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
var Client = require('../')
|
||||
var async = require('async')
|
||||
var ok = require('okay')
|
||||
const Client = require('../')
|
||||
const async = require('async')
|
||||
const ok = require('okay')
|
||||
|
||||
var execute = function (x, done) {
|
||||
var client = new Client()
|
||||
const execute = function (x, done) {
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
var query = function (n, cb) {
|
||||
const query = function (n, cb) {
|
||||
client.query('SELECT $1::int as num', [n], function (err) {
|
||||
cb(err)
|
||||
})
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
var Client = require('../')
|
||||
var async = require('async')
|
||||
var ok = require('okay')
|
||||
var bytes = require('crypto').pseudoRandomBytes
|
||||
const Client = require('../')
|
||||
const async = require('async')
|
||||
const ok = require('okay')
|
||||
const bytes = require('crypto').pseudoRandomBytes
|
||||
|
||||
describe('many connections', function () {
|
||||
describe('async', function () {
|
||||
var test = function (count, times) {
|
||||
const test = function (count, times) {
|
||||
it(`connecting ${count} clients ${times} times`, function (done) {
|
||||
this.timeout(200000)
|
||||
|
||||
var connectClient = function (n, cb) {
|
||||
var client = new Client()
|
||||
const connectClient = function (n, cb) {
|
||||
const client = new Client()
|
||||
client.connect(
|
||||
ok(cb, function () {
|
||||
bytes(
|
||||
@ -29,7 +29,7 @@ describe('many connections', function () {
|
||||
)
|
||||
}
|
||||
|
||||
var run = function (n, cb) {
|
||||
const run = function (n, cb) {
|
||||
async.times(count, connectClient, cb)
|
||||
}
|
||||
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
var Client = require('../')
|
||||
var async = require('async')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const async = require('async')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('many errors', function () {
|
||||
it('functions properly without segfault', function (done) {
|
||||
var throwError = function (n, cb) {
|
||||
var client = new Client()
|
||||
const throwError = function (n, cb) {
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
|
||||
var doIt = function (n, cb) {
|
||||
const doIt = function (n, cb) {
|
||||
client.query('select asdfiasdf', function (err) {
|
||||
assert(err, 'bad query should emit an error')
|
||||
cb(null)
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('multiple commands in a single query', function () {
|
||||
before(function (done) {
|
||||
@ -22,7 +22,7 @@ describe('multiple commands in a single query', function () {
|
||||
})
|
||||
|
||||
it('inserts and reads at once', function (done) {
|
||||
var txt = 'CREATE TEMP TABLE boom(age int);'
|
||||
let txt = 'CREATE TEMP TABLE boom(age int);'
|
||||
txt += 'INSERT INTO boom(age) VALUES(10);'
|
||||
txt += 'SELECT * FROM boom;'
|
||||
this.client.query(txt, function (err, rows, results) {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('multiple statements', () => {
|
||||
before(() => {
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
var Client = require('../')
|
||||
var ok = require('okay')
|
||||
const Client = require('../')
|
||||
const ok = require('okay')
|
||||
|
||||
var notify = function (channel, payload) {
|
||||
var client = new Client()
|
||||
const notify = function (channel, payload) {
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
client.querySync('NOTIFY ' + channel + ", '" + payload + "'")
|
||||
client.end()
|
||||
@ -10,12 +10,12 @@ var notify = function (channel, payload) {
|
||||
|
||||
describe('simple LISTEN/NOTIFY', function () {
|
||||
before(function (done) {
|
||||
var client = (this.client = new Client())
|
||||
const client = (this.client = new Client())
|
||||
client.connect(done)
|
||||
})
|
||||
|
||||
it('works', function (done) {
|
||||
var client = this.client
|
||||
const client = this.client
|
||||
client.querySync('LISTEN boom')
|
||||
client.on('notification', function (msg) {
|
||||
done()
|
||||
@ -31,14 +31,14 @@ describe('simple LISTEN/NOTIFY', function () {
|
||||
if (!process.env.TRAVIS_CI) {
|
||||
describe('async LISTEN/NOTIFY', function () {
|
||||
before(function (done) {
|
||||
var client = (this.client = new Client())
|
||||
const client = (this.client = new Client())
|
||||
client.connect(done)
|
||||
})
|
||||
|
||||
it('works', function (done) {
|
||||
var client = this.client
|
||||
var count = 0
|
||||
var check = function () {
|
||||
const client = this.client
|
||||
let count = 0
|
||||
const check = function () {
|
||||
count++
|
||||
if (count >= 2) return done()
|
||||
}
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
var Client = require('../')
|
||||
var ok = require('okay')
|
||||
var async = require('async')
|
||||
const Client = require('../')
|
||||
const ok = require('okay')
|
||||
const async = require('async')
|
||||
|
||||
describe('async prepare', function () {
|
||||
var run = function (n, cb) {
|
||||
var client = new Client()
|
||||
const run = function (n, cb) {
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
|
||||
var exec = function (x, done) {
|
||||
const exec = function (x, done) {
|
||||
client.prepare('get_now' + x, 'SELECT NOW()', 0, done)
|
||||
}
|
||||
|
||||
@ -20,7 +20,7 @@ describe('async prepare', function () {
|
||||
)
|
||||
}
|
||||
|
||||
var t = function (n) {
|
||||
const t = function (n) {
|
||||
it('works for ' + n + ' clients', function (done) {
|
||||
async.times(n, run, function (err) {
|
||||
done(err)
|
||||
@ -28,17 +28,17 @@ describe('async prepare', function () {
|
||||
})
|
||||
}
|
||||
|
||||
for (var i = 0; i < 10; i++) {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t(i)
|
||||
}
|
||||
})
|
||||
|
||||
describe('async execute', function () {
|
||||
var run = function (n, cb) {
|
||||
var client = new Client()
|
||||
const run = function (n, cb) {
|
||||
const client = new Client()
|
||||
client.connectSync()
|
||||
client.prepareSync('get_now', 'SELECT NOW()', 0)
|
||||
var exec = function (x, cb) {
|
||||
const exec = function (x, cb) {
|
||||
client.execute('get_now', [], cb)
|
||||
}
|
||||
async.timesSeries(
|
||||
@ -50,7 +50,7 @@ describe('async execute', function () {
|
||||
)
|
||||
}
|
||||
|
||||
var t = function (n) {
|
||||
const t = function (n) {
|
||||
it('works for ' + n + ' clients', function (done) {
|
||||
async.times(n, run, function (err) {
|
||||
done(err)
|
||||
@ -58,7 +58,7 @@ describe('async execute', function () {
|
||||
})
|
||||
}
|
||||
|
||||
for (var i = 0; i < 10; i++) {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t(i)
|
||||
}
|
||||
})
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
var async = require('async')
|
||||
var ok = require('okay')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
const async = require('async')
|
||||
const ok = require('okay')
|
||||
|
||||
describe('async query', function () {
|
||||
before(function (done) {
|
||||
@ -24,7 +24,7 @@ describe('async query', function () {
|
||||
})
|
||||
|
||||
it('simple query works', function (done) {
|
||||
var runQuery = function (n, done) {
|
||||
const runQuery = function (n, done) {
|
||||
this.client.query('SELECT NOW() AS the_time', function (err, rows) {
|
||||
if (err) return done(err)
|
||||
assert.equal(rows[0].the_time.getFullYear(), new Date().getFullYear())
|
||||
@ -35,14 +35,14 @@ describe('async query', function () {
|
||||
})
|
||||
|
||||
it('parameters work', function (done) {
|
||||
var runQuery = function (n, done) {
|
||||
const runQuery = function (n, done) {
|
||||
this.client.query('SELECT $1::text AS name', ['Brian'], done)
|
||||
}.bind(this)
|
||||
async.timesSeries(3, runQuery, done)
|
||||
})
|
||||
|
||||
it('prepared, named statements work', function (done) {
|
||||
var client = this.client
|
||||
const client = this.client
|
||||
client.prepare('test', 'SELECT $1::text as name', 1, function (err) {
|
||||
if (err) return done(err)
|
||||
client.execute(
|
||||
@ -80,7 +80,7 @@ describe('async query', function () {
|
||||
})
|
||||
|
||||
it('returns an error if there was a query error', function (done) {
|
||||
var runErrorQuery = function (n, done) {
|
||||
const runErrorQuery = function (n, done) {
|
||||
this.client.query('SELECT ALKJSFDSLFKJ', function (err) {
|
||||
assert(err instanceof Error, 'Should return an error instance')
|
||||
done()
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
|
||||
describe('query sync', function () {
|
||||
before(function () {
|
||||
@ -12,13 +12,13 @@ describe('query sync', function () {
|
||||
})
|
||||
|
||||
it('simple query works', function () {
|
||||
var rows = this.client.querySync('SELECT NOW() AS the_time')
|
||||
const rows = this.client.querySync('SELECT NOW() AS the_time')
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].the_time.getFullYear(), new Date().getFullYear())
|
||||
})
|
||||
|
||||
it('parameterized query works', function () {
|
||||
var rows = this.client.querySync('SELECT $1::text AS name', ['Brian'])
|
||||
const rows = this.client.querySync('SELECT $1::text AS name', ['Brian'])
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].name, 'Brian')
|
||||
})
|
||||
@ -37,11 +37,11 @@ describe('query sync', function () {
|
||||
it('prepared statement works', function () {
|
||||
this.client.prepareSync('test', 'SELECT $1::text as name', 1)
|
||||
|
||||
var rows = this.client.executeSync('test', ['Brian'])
|
||||
const rows = this.client.executeSync('test', ['Brian'])
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].name, 'Brian')
|
||||
|
||||
var rows2 = this.client.executeSync('test', ['Aaron'])
|
||||
const rows2 = this.client.executeSync('test', ['Aaron'])
|
||||
assert.equal(rows2.length, 1)
|
||||
assert.equal(rows2[0].name, 'Aaron')
|
||||
})
|
||||
@ -70,13 +70,13 @@ describe('query sync', function () {
|
||||
})
|
||||
|
||||
it('is still usable after an error', function () {
|
||||
var rows = this.client.querySync('SELECT NOW()')
|
||||
const rows = this.client.querySync('SELECT NOW()')
|
||||
assert(rows, 'should have returned rows')
|
||||
assert.equal(rows.length, 1)
|
||||
})
|
||||
|
||||
it('supports empty query', function () {
|
||||
var rows = this.client.querySync('')
|
||||
const rows = this.client.querySync('')
|
||||
assert(rows, 'should return rows')
|
||||
assert.equal(rows.length, 0, 'should return no rows')
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
var Client = require('../')
|
||||
var assert = require('assert')
|
||||
var semver = require('semver')
|
||||
const Client = require('../')
|
||||
const assert = require('assert')
|
||||
const semver = require('semver')
|
||||
|
||||
describe('version', function () {
|
||||
it('is exported', function () {
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
# pg-pool
|
||||
|
||||
[](https://travis-ci.org/brianc/node-pg-pool)
|
||||
|
||||
A connection pool for node-postgres
|
||||
|
||||
## install
|
||||
|
||||
```sh
|
||||
npm i pg-pool pg
|
||||
```
|
||||
@ -15,17 +17,17 @@ npm i pg-pool pg
|
||||
to use pg-pool you must first create an instance of a pool
|
||||
|
||||
```js
|
||||
var Pool = require('pg-pool')
|
||||
const Pool = require('pg-pool')
|
||||
|
||||
// by default the pool uses the same
|
||||
// configuration as whatever `pg` version you have installed
|
||||
var pool = new Pool()
|
||||
const pool = new Pool()
|
||||
|
||||
// you can pass properties to the pool
|
||||
// these properties are passed unchanged to both the node-postgres Client constructor
|
||||
// and the node-pool (https://github.com/coopernurse/node-pool) constructor
|
||||
// allowing you to fully configure the behavior of both
|
||||
var pool2 = new Pool({
|
||||
const pool2 = new Pool({
|
||||
database: 'postgres',
|
||||
user: 'brianc',
|
||||
password: 'secret!',
|
||||
@ -37,25 +39,26 @@ var pool2 = new Pool({
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
})
|
||||
|
||||
//you can supply a custom client constructor
|
||||
//if you want to use the native postgres client
|
||||
var NativeClient = require('pg').native.Client
|
||||
var nativePool = new Pool({ Client: NativeClient })
|
||||
// you can supply a custom client constructor
|
||||
// if you want to use the native postgres client
|
||||
const NativeClient = require('pg').native.Client
|
||||
const nativePool = new Pool({ Client: NativeClient })
|
||||
|
||||
//you can even pool pg-native clients directly
|
||||
var PgNativeClient = require('pg-native')
|
||||
var pgNativePool = new Pool({ Client: PgNativeClient })
|
||||
// you can even pool pg-native clients directly
|
||||
const PgNativeClient = require('pg-native')
|
||||
const pgNativePool = new Pool({ Client: PgNativeClient })
|
||||
```
|
||||
|
||||
##### Note:
|
||||
|
||||
The Pool constructor does not support passing a Database URL as the parameter. To use pg-pool on heroku, for example, you need to parse the URL into a config object. Here is an example of how to parse a Database URL.
|
||||
|
||||
```js
|
||||
const Pool = require('pg-pool');
|
||||
const Pool = require('pg-pool')
|
||||
const url = require('url')
|
||||
|
||||
const params = url.parse(process.env.DATABASE_URL);
|
||||
const auth = params.auth.split(':');
|
||||
const params = url.parse(process.env.DATABASE_URL)
|
||||
const auth = params.auth.split(':')
|
||||
|
||||
const config = {
|
||||
user: auth[0],
|
||||
@ -63,10 +66,10 @@ const config = {
|
||||
host: params.hostname,
|
||||
port: params.port,
|
||||
database: params.pathname.split('/')[1],
|
||||
ssl: true
|
||||
};
|
||||
ssl: true,
|
||||
}
|
||||
|
||||
const pool = new Pool(config);
|
||||
const pool = new Pool(config)
|
||||
|
||||
/*
|
||||
Transforms, 'postgres://DBuser:secret@DBHost:#####/myDB', into
|
||||
@ -79,23 +82,25 @@ const pool = new Pool(config);
|
||||
ssl: true
|
||||
}
|
||||
*/
|
||||
```
|
||||
```
|
||||
|
||||
### acquire clients with a promise
|
||||
|
||||
pg-pool supports a fully promise-based api for acquiring clients
|
||||
|
||||
```js
|
||||
var pool = new Pool()
|
||||
pool.connect().then(client => {
|
||||
client.query('select $1::text as name', ['pg-pool']).then(res => {
|
||||
client.release()
|
||||
console.log('hello from', res.rows[0].name)
|
||||
})
|
||||
.catch(e => {
|
||||
client.release()
|
||||
console.error('query error', e.message, e.stack)
|
||||
})
|
||||
const pool = new Pool()
|
||||
pool.connect().then((client) => {
|
||||
client
|
||||
.query('select $1::text as name', ['pg-pool'])
|
||||
.then((res) => {
|
||||
client.release()
|
||||
console.log('hello from', res.rows[0].name)
|
||||
})
|
||||
.catch((e) => {
|
||||
client.release()
|
||||
console.error('query error', e.message, e.stack)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
@ -105,27 +110,27 @@ this ends up looking much nicer if you're using [co](https://github.com/tj/co) o
|
||||
|
||||
```js
|
||||
// with async/await
|
||||
(async () => {
|
||||
var pool = new Pool()
|
||||
var client = await pool.connect()
|
||||
;(async () => {
|
||||
const pool = new Pool()
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
var result = await client.query('select $1::text as name', ['brianc'])
|
||||
const result = await client.query('select $1::text as name', ['brianc'])
|
||||
console.log('hello from', result.rows[0])
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
})().catch(e => console.error(e.message, e.stack))
|
||||
})().catch((e) => console.error(e.message, e.stack))
|
||||
|
||||
// with co
|
||||
co(function * () {
|
||||
var client = yield pool.connect()
|
||||
co(function* () {
|
||||
const client = yield pool.connect()
|
||||
try {
|
||||
var result = yield client.query('select $1::text as name', ['brianc'])
|
||||
const result = yield client.query('select $1::text as name', ['brianc'])
|
||||
console.log('hello from', result.rows[0])
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
}).catch(e => console.error(e.message, e.stack))
|
||||
}).catch((e) => console.error(e.message, e.stack))
|
||||
```
|
||||
|
||||
### your new favorite helper method
|
||||
@ -133,32 +138,32 @@ co(function * () {
|
||||
because its so common to just run a query and return the client to the pool afterward pg-pool has this built-in:
|
||||
|
||||
```js
|
||||
var pool = new Pool()
|
||||
var time = await pool.query('SELECT NOW()')
|
||||
var name = await pool.query('select $1::text as name', ['brianc'])
|
||||
const pool = new Pool()
|
||||
const time = await pool.query('SELECT NOW()')
|
||||
const name = await pool.query('select $1::text as name', ['brianc'])
|
||||
console.log(name.rows[0].name, 'says hello at', time.rows[0].now)
|
||||
```
|
||||
|
||||
you can also use a callback here if you'd like:
|
||||
|
||||
```js
|
||||
var pool = new Pool()
|
||||
const pool = new Pool()
|
||||
pool.query('SELECT $1::text as name', ['brianc'], function (err, res) {
|
||||
console.log(res.rows[0].name) // brianc
|
||||
})
|
||||
```
|
||||
|
||||
__pro tip:__ unless you need to run a transaction (which requires a single client for multiple queries) or you
|
||||
**pro tip:** unless you need to run a transaction (which requires a single client for multiple queries) or you
|
||||
have some other edge case like [streaming rows](https://github.com/brianc/node-pg-query-stream) or using a [cursor](https://github.com/brianc/node-pg-cursor)
|
||||
you should almost always just use `pool.query`. Its easy, it does the right thing :tm:, and wont ever forget to return
|
||||
you should almost always just use `pool.query`. Its easy, it does the right thing :tm:, and wont ever forget to return
|
||||
clients back to the pool after the query is done.
|
||||
|
||||
### drop-in backwards compatible
|
||||
|
||||
pg-pool still and will always support the traditional callback api for acquiring a client. This is the exact API node-postgres has shipped with for years:
|
||||
pg-pool still and will always support the traditional callback api for acquiring a client. This is the exact API node-postgres has shipped with for years:
|
||||
|
||||
```js
|
||||
var pool = new Pool()
|
||||
const pool = new Pool()
|
||||
pool.connect((err, client, done) => {
|
||||
if (err) return done(err)
|
||||
|
||||
@ -175,11 +180,11 @@ pool.connect((err, client, done) => {
|
||||
### shut it down
|
||||
|
||||
When you are finished with the pool if all the clients are idle the pool will close them after `config.idleTimeoutMillis` and your app
|
||||
will shutdown gracefully. If you don't want to wait for the timeout you can end the pool as follows:
|
||||
will shutdown gracefully. If you don't want to wait for the timeout you can end the pool as follows:
|
||||
|
||||
```js
|
||||
var pool = new Pool()
|
||||
var client = await pool.connect()
|
||||
const pool = new Pool()
|
||||
const client = await pool.connect()
|
||||
console.log(await client.query('select now()'))
|
||||
client.release()
|
||||
await pool.end()
|
||||
@ -187,14 +192,14 @@ await pool.end()
|
||||
|
||||
### a note on instances
|
||||
|
||||
The pool should be a __long-lived object__ in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place. Example:
|
||||
The pool should be a **long-lived object** in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place. Example:
|
||||
|
||||
```js
|
||||
// assume this is a file in your program at ./your-app/lib/db.js
|
||||
|
||||
// correct usage: create the pool and let it live
|
||||
// 'globally' here, controlling access to it through exported methods
|
||||
var pool = new pg.Pool()
|
||||
const pool = new pg.Pool()
|
||||
|
||||
// this is the right way to export the query method
|
||||
module.exports.query = (text, values) => {
|
||||
@ -208,18 +213,18 @@ module.exports.connect = () => {
|
||||
// every time we called 'connect' to get a new client?
|
||||
// that's a bad thing & results in creating an unbounded
|
||||
// number of pools & therefore connections
|
||||
var aPool = new pg.Pool()
|
||||
const aPool = new pg.Pool()
|
||||
return aPool.connect()
|
||||
}
|
||||
```
|
||||
|
||||
### events
|
||||
|
||||
Every instance of a `Pool` is an event emitter. These instances emit the following events:
|
||||
Every instance of a `Pool` is an event emitter. These instances emit the following events:
|
||||
|
||||
#### error
|
||||
|
||||
Emitted whenever an idle client in the pool encounters an error. This is common when your PostgreSQL server shuts down, reboots, or a network partition otherwise causes it to become unavailable while your pool has connected clients.
|
||||
Emitted whenever an idle client in the pool encounters an error. This is common when your PostgreSQL server shuts down, reboots, or a network partition otherwise causes it to become unavailable while your pool has connected clients.
|
||||
|
||||
Example:
|
||||
|
||||
@ -229,7 +234,7 @@ const pool = new Pool()
|
||||
|
||||
// attach an error handler to the pool for when a connected, idle client
|
||||
// receives an error by being disconnected, etc
|
||||
pool.on('error', function(error, client) {
|
||||
pool.on('error', function (error, client) {
|
||||
// handle this in the same way you would treat process.on('uncaughtException')
|
||||
// it is supplied the error as well as the idle client which received the error
|
||||
})
|
||||
@ -237,7 +242,7 @@ pool.on('error', function(error, client) {
|
||||
|
||||
#### connect
|
||||
|
||||
Fired whenever the pool creates a __new__ `pg.Client` instance and successfully connects it to the backend.
|
||||
Fired whenever the pool creates a **new** `pg.Client` instance and successfully connects it to the backend.
|
||||
|
||||
Example:
|
||||
|
||||
@ -245,22 +250,21 @@ Example:
|
||||
const Pool = require('pg-pool')
|
||||
const pool = new Pool()
|
||||
|
||||
var count = 0
|
||||
const count = 0
|
||||
|
||||
pool.on('connect', client => {
|
||||
pool.on('connect', (client) => {
|
||||
client.count = count++
|
||||
})
|
||||
|
||||
pool
|
||||
.connect()
|
||||
.then(client => {
|
||||
.then((client) => {
|
||||
return client
|
||||
.query('SELECT $1::int AS "clientCount"', [client.count])
|
||||
.then(res => console.log(res.rows[0].clientCount)) // outputs 0
|
||||
.then((res) => console.log(res.rows[0].clientCount)) // outputs 0
|
||||
.then(() => client)
|
||||
})
|
||||
.then(client => client.release())
|
||||
|
||||
.then((client) => client.release())
|
||||
```
|
||||
|
||||
#### acquire
|
||||
@ -272,20 +276,20 @@ Example:
|
||||
This allows you to count the number of clients which have ever been acquired from the pool.
|
||||
|
||||
```js
|
||||
var Pool = require('pg-pool')
|
||||
var pool = new Pool()
|
||||
const Pool = require('pg-pool')
|
||||
const pool = new Pool()
|
||||
|
||||
var acquireCount = 0
|
||||
const acquireCount = 0
|
||||
pool.on('acquire', function (client) {
|
||||
acquireCount++
|
||||
})
|
||||
|
||||
var connectCount = 0
|
||||
const connectCount = 0
|
||||
pool.on('connect', function () {
|
||||
connectCount++
|
||||
})
|
||||
|
||||
for (var i = 0; i < 200; i++) {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
pool.query('SELECT NOW()')
|
||||
}
|
||||
|
||||
@ -293,12 +297,11 @@ setTimeout(function () {
|
||||
console.log('connect count:', connectCount) // output: connect count: 10
|
||||
console.log('acquire count:', acquireCount) // output: acquire count: 200
|
||||
}, 100)
|
||||
|
||||
```
|
||||
|
||||
### environment variables
|
||||
|
||||
pg-pool & node-postgres support some of the same environment variables as `psql` supports. The most common are:
|
||||
pg-pool & node-postgres support some of the same environment variables as `psql` supports. The most common are:
|
||||
|
||||
```
|
||||
PGDATABASE=my_db
|
||||
@ -308,40 +311,19 @@ PGPORT=5432
|
||||
PGSSLMODE=require
|
||||
```
|
||||
|
||||
Usually I will export these into my local environment via a `.env` file with environment settings or export them in `~/.bash_profile` or something similar. This way I get configurability which works with both the postgres suite of tools (`psql`, `pg_dump`, `pg_restore`) and node, I can vary the environment variables locally and in production, and it supports the concept of a [12-factor app](http://12factor.net/) out of the box.
|
||||
|
||||
## bring your own promise
|
||||
|
||||
In versions of node `<=0.12.x` there is no native promise implementation available globally. You can polyfill the promise globally like this:
|
||||
|
||||
```js
|
||||
// first run `npm install promise-polyfill --save
|
||||
if (typeof Promise == 'undefined') {
|
||||
global.Promise = require('promise-polyfill')
|
||||
}
|
||||
```
|
||||
|
||||
You can use any other promise implementation you'd like. The pool also allows you to configure the promise implementation on a per-pool level:
|
||||
|
||||
```js
|
||||
var bluebirdPool = new Pool({
|
||||
Promise: require('bluebird')
|
||||
})
|
||||
```
|
||||
|
||||
__please note:__ in node `<=0.12.x` the pool will throw if you do not provide a promise constructor in one of the two ways mentioned above. In node `>=4.0.0` the pool will use the native promise implementation by default; however, the two methods above still allow you to "bring your own."
|
||||
Usually I will export these into my local environment via a `.env` file with environment settings or export them in `~/.bash_profile` or something similar. This way I get configurability which works with both the postgres suite of tools (`psql`, `pg_dump`, `pg_restore`) and node, I can vary the environment variables locally and in production, and it supports the concept of a [12-factor app](http://12factor.net/) out of the box.
|
||||
|
||||
## maxUses and read-replica autoscaling (e.g. AWS Aurora)
|
||||
|
||||
The maxUses config option can help an application instance rebalance load against a replica set that has been auto-scaled after the connection pool is already full of healthy connections.
|
||||
|
||||
The mechanism here is that a connection is considered "expended" after it has been acquired and released `maxUses` number of times. Depending on the load on your system, this means there will be an approximate time in which any given connection will live, thus creating a window for rebalancing.
|
||||
The mechanism here is that a connection is considered "expended" after it has been acquired and released `maxUses` number of times. Depending on the load on your system, this means there will be an approximate time in which any given connection will live, thus creating a window for rebalancing.
|
||||
|
||||
Imagine a scenario where you have 10 app instances providing an API running against a replica cluster of 3 that are accessed via a round-robin DNS entry. Each instance runs a connection pool size of 20. With an ambient load of 50 requests per second, the connection pool will likely fill up in a few minutes with healthy connections.
|
||||
Imagine a scenario where you have 10 app instances providing an API running against a replica cluster of 3 that are accessed via a round-robin DNS entry. Each instance runs a connection pool size of 20. With an ambient load of 50 requests per second, the connection pool will likely fill up in a few minutes with healthy connections.
|
||||
|
||||
If you have weekly bursts of traffic which peak at 1,000 requests per second, you might want to grow your replicas to 10 during this period. Without setting `maxUses`, the new replicas will not be adopted by the app servers without an intervention -- namely, restarting each in turn in order to build up new connection pools that are balanced against all the replicas. Adding additional app server instances will help to some extent because they will adopt all the replicas in an even way, but the initial app servers will continue to focus additional load on the original replicas.
|
||||
If you have weekly bursts of traffic which peak at 1,000 requests per second, you might want to grow your replicas to 10 during this period. Without setting `maxUses`, the new replicas will not be adopted by the app servers without an intervention -- namely, restarting each in turn in order to build up new connection pools that are balanced against all the replicas. Adding additional app server instances will help to some extent because they will adopt all the replicas in an even way, but the initial app servers will continue to focus additional load on the original replicas.
|
||||
|
||||
This is where the `maxUses` configuration option comes into play. Setting `maxUses` to 7500 will ensure that over a period of 30 minutes or so the new replicas will be adopted as the pre-existing connections are closed and replaced with new ones, thus creating a window for eventual balance.
|
||||
This is where the `maxUses` configuration option comes into play. Setting `maxUses` to 7500 will ensure that over a period of 30 minutes or so the new replicas will be adopted as the pre-existing connections are closed and replaced with new ones, thus creating a window for eventual balance.
|
||||
|
||||
You'll want to test based on your own scenarios, but one way to make a first guess at `maxUses` is to identify an acceptable window for rebalancing and then solve for the value:
|
||||
|
||||
@ -362,7 +344,7 @@ To run tests clone the repo, `npm i` in the working dir, and then run `npm test`
|
||||
|
||||
## contributions
|
||||
|
||||
I love contributions. Please make sure they have tests, and submit a PR. If you're not sure if the issue is worth it or will be accepted it never hurts to open an issue to begin the conversation. If you're interested in keeping up with node-postgres releated stuff, you can follow me on twitter at [@briancarlson](https://twitter.com/briancarlson) - I generally announce any noteworthy updates there.
|
||||
I love contributions. Please make sure they have tests, and submit a PR. If you're not sure if the issue is worth it or will be accepted it never hurts to open an issue to begin the conversation. If you're interested in keeping up with node-postgres releated stuff, you can follow me on twitter at [@briancarlson](https://twitter.com/briancarlson) - I generally announce any noteworthy updates there.
|
||||
|
||||
## license
|
||||
|
||||
|
||||
@ -87,6 +87,7 @@ class Pool extends EventEmitter {
|
||||
}
|
||||
|
||||
this.options.max = this.options.max || this.options.poolSize || 10
|
||||
this.options.min = this.options.min || 0
|
||||
this.options.maxUses = this.options.maxUses || Infinity
|
||||
this.options.allowExitOnIdle = this.options.allowExitOnIdle || false
|
||||
this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0
|
||||
@ -111,6 +112,10 @@ class Pool extends EventEmitter {
|
||||
return this._clients.length >= this.options.max
|
||||
}
|
||||
|
||||
_isAboveMin() {
|
||||
return this._clients.length > this.options.min
|
||||
}
|
||||
|
||||
_pulseQueue() {
|
||||
this.log('pulse queue')
|
||||
if (this.ended) {
|
||||
@ -156,7 +161,7 @@ class Pool extends EventEmitter {
|
||||
throw new Error('unexpected condition')
|
||||
}
|
||||
|
||||
_remove(client) {
|
||||
_remove(client, callback) {
|
||||
const removed = removeWhere(this._idle, (item) => item.client === client)
|
||||
|
||||
if (removed !== undefined) {
|
||||
@ -164,8 +169,14 @@ class Pool extends EventEmitter {
|
||||
}
|
||||
|
||||
this._clients = this._clients.filter((c) => c !== client)
|
||||
client.end()
|
||||
this.emit('remove', client)
|
||||
const context = this
|
||||
client.end(() => {
|
||||
context.emit('remove', client)
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
connect(cb) {
|
||||
@ -346,26 +357,25 @@ class Pool extends EventEmitter {
|
||||
if (client._poolUseCount >= this.options.maxUses) {
|
||||
this.log('remove expended client')
|
||||
}
|
||||
this._remove(client)
|
||||
this._pulseQueue()
|
||||
return
|
||||
|
||||
return this._remove(client, this._pulseQueue.bind(this))
|
||||
}
|
||||
|
||||
const isExpired = this._expired.has(client)
|
||||
if (isExpired) {
|
||||
this.log('remove expired client')
|
||||
this._expired.delete(client)
|
||||
this._remove(client)
|
||||
this._pulseQueue()
|
||||
return
|
||||
return this._remove(client, this._pulseQueue.bind(this))
|
||||
}
|
||||
|
||||
// idle timeout
|
||||
let tid
|
||||
if (this.options.idleTimeoutMillis) {
|
||||
if (this.options.idleTimeoutMillis && this._isAboveMin()) {
|
||||
tid = setTimeout(() => {
|
||||
this.log('remove idle client')
|
||||
this._remove(client)
|
||||
if (this._isAboveMin()) {
|
||||
this.log('remove idle client')
|
||||
this._remove(client, this._pulseQueue.bind(this))
|
||||
}
|
||||
}, this.options.idleTimeoutMillis)
|
||||
|
||||
if (this.options.allowExitOnIdle) {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-pool",
|
||||
"version": "3.9.5",
|
||||
"version": "3.10.1",
|
||||
"description": "Connection pool for node-postgres",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
@ -30,16 +30,15 @@
|
||||
"author": "Brian M. Carlson",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/brianc/node-pg-pool/issues"
|
||||
"url": "https://github.com/brianc/node-postgres/issues"
|
||||
},
|
||||
"homepage": "https://github.com/brianc/node-pg-pool#readme",
|
||||
"homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-pool#readme",
|
||||
"devDependencies": {
|
||||
"bluebird": "3.7.2",
|
||||
"co": "4.6.0",
|
||||
"expect.js": "0.3.1",
|
||||
"lodash": "^4.17.11",
|
||||
"mocha": "^10.5.2",
|
||||
"pg-cursor": "^2.14.5"
|
||||
"mocha": "^10.5.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
|
||||
@ -1,42 +0,0 @@
|
||||
'use strict'
|
||||
const co = require('co')
|
||||
const expect = require('expect.js')
|
||||
|
||||
const describe = require('mocha').describe
|
||||
const it = require('mocha').it
|
||||
const BluebirdPromise = require('bluebird')
|
||||
|
||||
const Pool = require('../')
|
||||
|
||||
const checkType = (promise) => {
|
||||
expect(promise).to.be.a(BluebirdPromise)
|
||||
return promise.catch((e) => undefined)
|
||||
}
|
||||
|
||||
describe('Bring your own promise', function () {
|
||||
it(
|
||||
'uses supplied promise for operations',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ Promise: BluebirdPromise })
|
||||
const client1 = yield checkType(pool.connect())
|
||||
client1.release()
|
||||
yield checkType(pool.query('SELECT NOW()'))
|
||||
const client2 = yield checkType(pool.connect())
|
||||
// TODO - make sure pg supports BYOP as well
|
||||
client2.release()
|
||||
yield checkType(pool.end())
|
||||
})
|
||||
)
|
||||
|
||||
it(
|
||||
'uses promises in errors',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ Promise: BluebirdPromise, port: 48484 })
|
||||
yield checkType(pool.connect())
|
||||
yield checkType(pool.end())
|
||||
yield checkType(pool.connect())
|
||||
yield checkType(pool.query())
|
||||
yield checkType(pool.end())
|
||||
})
|
||||
)
|
||||
})
|
||||
@ -57,7 +57,7 @@ describe('connection timeout', () => {
|
||||
function* () {
|
||||
const errors = []
|
||||
const pool = new Pool({ connectionTimeoutMillis: 1, port: this.port, host: 'localhost' })
|
||||
for (var i = 0; i < 15; i++) {
|
||||
for (let i = 0; i < 15; i++) {
|
||||
try {
|
||||
yield pool.connect()
|
||||
} catch (e) {
|
||||
|
||||
@ -37,4 +37,14 @@ describe('pool ending', () => {
|
||||
expect(res.rows[0].name).to.equal('brianc')
|
||||
})
|
||||
)
|
||||
|
||||
it('pool.end() - finish pending queries', async () => {
|
||||
const pool = new Pool({ max: 20 })
|
||||
let completed = 0
|
||||
for (let x = 1; x <= 20; x++) {
|
||||
pool.query('SELECT $1::text as name', ['brianc']).then(() => completed++)
|
||||
}
|
||||
await pool.end()
|
||||
expect(completed).to.equal(20)
|
||||
})
|
||||
})
|
||||
|
||||
@ -198,7 +198,7 @@ describe('pool error handling', function () {
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 1 })
|
||||
const errors = []
|
||||
for (var i = 0; i < 20; i++) {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
try {
|
||||
yield pool.query('invalid sql')
|
||||
} catch (err) {
|
||||
|
||||
@ -28,11 +28,19 @@ describe('idle timeout', () => {
|
||||
const pool = new Pool({ idleTimeoutMillis: 10 })
|
||||
const clientA = yield pool.connect()
|
||||
const clientB = yield pool.connect()
|
||||
clientA.release()
|
||||
clientB.release(new Error())
|
||||
clientA.release() // this will put clientA in the idle pool
|
||||
clientB.release(new Error()) // an error will cause clientB to be removed immediately
|
||||
|
||||
const removal = new Promise((resolve) => {
|
||||
pool.on('remove', () => {
|
||||
pool.on('remove', (client) => {
|
||||
// clientB's stream may take a while to close, so we may get a remove
|
||||
// event for it
|
||||
// we only want to handle the remove event for clientA when it times out
|
||||
// due to being idle
|
||||
if (client !== clientA) {
|
||||
return
|
||||
}
|
||||
|
||||
expect(pool.idleCount).to.equal(0)
|
||||
expect(pool.totalCount).to.equal(0)
|
||||
resolve()
|
||||
@ -54,8 +62,8 @@ describe('idle timeout', () => {
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ idleTimeoutMillis: 1 })
|
||||
const results = []
|
||||
for (var i = 0; i < 20; i++) {
|
||||
let query = pool.query('SELECT NOW()')
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const query = pool.query('SELECT NOW()')
|
||||
expect(pool.idleCount).to.equal(0)
|
||||
expect(pool.totalCount).to.equal(1)
|
||||
results.push(yield query)
|
||||
@ -72,8 +80,8 @@ describe('idle timeout', () => {
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ idleTimeoutMillis: 1 })
|
||||
const results = []
|
||||
for (var i = 0; i < 20; i++) {
|
||||
let client = yield pool.connect()
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const client = yield pool.connect()
|
||||
expect(pool.totalCount).to.equal(1)
|
||||
expect(pool.idleCount).to.equal(0)
|
||||
yield wait(10)
|
||||
|
||||
@ -32,7 +32,7 @@ describe('lifetime timeout', () => {
|
||||
'can remove expired clients and recreate them',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ maxLifetimeSeconds: 1 })
|
||||
let query = pool.query('SELECT pg_sleep(1.4)')
|
||||
const query = pool.query('SELECT pg_sleep(1.4)')
|
||||
expect(pool.expiredCount).to.equal(0)
|
||||
expect(pool.totalCount).to.equal(1)
|
||||
yield query
|
||||
|
||||
@ -55,4 +55,88 @@ describe('pool size of 1', () => {
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
|
||||
it(
|
||||
'does not remove clients when at or below min',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 1, min: 1, idleTimeoutMillis: 10 })
|
||||
const client = yield pool.connect()
|
||||
client.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(pool.idleCount).to.equal(1)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
|
||||
it(
|
||||
'does remove clients when at or below min if maxUses is reached',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 1, min: 1, idleTimeoutMillis: 10, maxUses: 1 })
|
||||
const client = yield pool.connect()
|
||||
client.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(pool.idleCount).to.equal(0)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
|
||||
it(
|
||||
'does remove clients when at or below min if maxLifetimeSeconds is reached',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 1, min: 1, idleTimeoutMillis: 10, maxLifetimeSeconds: 1 })
|
||||
const client = yield pool.connect()
|
||||
client.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 1020))
|
||||
expect(pool.idleCount).to.equal(0)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
describe('pool size of 2', () => {
|
||||
it(
|
||||
'does not remove clients when at or below min',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 2, min: 2, idleTimeoutMillis: 10 })
|
||||
const client = yield pool.connect()
|
||||
const client2 = yield pool.connect()
|
||||
client.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
client2.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(pool.idleCount).to.equal(2)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
|
||||
it(
|
||||
'does remove clients when above min',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 2, min: 1, idleTimeoutMillis: 10 })
|
||||
const client = yield pool.connect()
|
||||
const client2 = yield pool.connect()
|
||||
client.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
client2.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(pool.idleCount).to.equal(1)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
describe('pool min size', () => {
|
||||
it(
|
||||
'does not drop below min when clients released at same time',
|
||||
co.wrap(function* () {
|
||||
const pool = new Pool({ max: 2, min: 1, idleTimeoutMillis: 10 })
|
||||
const client = yield pool.connect()
|
||||
const client2 = yield pool.connect()
|
||||
client.release()
|
||||
client2.release()
|
||||
yield new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(pool.idleCount).to.equal(1)
|
||||
return yield pool.end()
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pg-protocol",
|
||||
"version": "1.9.5",
|
||||
"version": "1.10.3",
|
||||
"description": "The postgres client/server binary protocol, implemented in TypeScript",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@ -10,11 +10,8 @@
|
||||
"require": "./dist/index.js",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./dist/*": {
|
||||
"import": "./dist/*",
|
||||
"require": "./dist/*",
|
||||
"default": "./dist/*"
|
||||
}
|
||||
"./dist/*": "./dist/*.js",
|
||||
"./dist/*.js": "./dist/*.js"
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
|
||||
@ -4,14 +4,14 @@ import { BufferReader } from './buffer-reader'
|
||||
|
||||
const LOOPS = 1000
|
||||
let count = 0
|
||||
let start = Date.now()
|
||||
const start = performance.now()
|
||||
|
||||
const reader = new BufferReader()
|
||||
const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0])
|
||||
|
||||
const run = () => {
|
||||
if (count > LOOPS) {
|
||||
console.log(Date.now() - start)
|
||||
console.log(performance.now() - start)
|
||||
return
|
||||
}
|
||||
count++
|
||||
|
||||
@ -9,12 +9,12 @@ export class Writer {
|
||||
}
|
||||
|
||||
private ensure(size: number): void {
|
||||
var remaining = this.buffer.length - this.offset
|
||||
const remaining = this.buffer.length - this.offset
|
||||
if (remaining < size) {
|
||||
var oldBuffer = this.buffer
|
||||
const oldBuffer = this.buffer
|
||||
// exponential growth factor of around ~ 1.5
|
||||
// https://stackoverflow.com/questions/2269063/buffer-growth-strategy
|
||||
var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size
|
||||
const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size
|
||||
this.buffer = Buffer.allocUnsafe(newSize)
|
||||
oldBuffer.copy(this.buffer)
|
||||
}
|
||||
@ -40,7 +40,7 @@ export class Writer {
|
||||
if (!string) {
|
||||
this.ensure(1)
|
||||
} else {
|
||||
var len = Buffer.byteLength(string)
|
||||
const len = Buffer.byteLength(string)
|
||||
this.ensure(len + 1) // +1 for null terminator
|
||||
this.buffer.write(string, this.offset, 'utf-8')
|
||||
this.offset += len
|
||||
@ -51,7 +51,7 @@ export class Writer {
|
||||
}
|
||||
|
||||
public addString(string: string = ''): Writer {
|
||||
var len = Buffer.byteLength(string)
|
||||
const len = Buffer.byteLength(string)
|
||||
this.ensure(len)
|
||||
this.buffer.write(string, this.offset)
|
||||
this.offset += len
|
||||
@ -76,7 +76,7 @@ export class Writer {
|
||||
}
|
||||
|
||||
public flush(code?: number): Buffer {
|
||||
var result = this.join(code)
|
||||
const result = this.join(code)
|
||||
this.offset = 5
|
||||
this.headerPosition = 0
|
||||
this.buffer = Buffer.allocUnsafe(this.size)
|
||||
|
||||
@ -5,16 +5,16 @@ import assert from 'assert'
|
||||
import { PassThrough } from 'stream'
|
||||
import { BackendMessage } from './messages'
|
||||
|
||||
var authOkBuffer = buffers.authenticationOk()
|
||||
var paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8')
|
||||
var readyForQueryBuffer = buffers.readyForQuery()
|
||||
var backendKeyDataBuffer = buffers.backendKeyData(1, 2)
|
||||
var commandCompleteBuffer = buffers.commandComplete('SELECT 3')
|
||||
var parseCompleteBuffer = buffers.parseComplete()
|
||||
var bindCompleteBuffer = buffers.bindComplete()
|
||||
var portalSuspendedBuffer = buffers.portalSuspended()
|
||||
const authOkBuffer = buffers.authenticationOk()
|
||||
const paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8')
|
||||
const readyForQueryBuffer = buffers.readyForQuery()
|
||||
const backendKeyDataBuffer = buffers.backendKeyData(1, 2)
|
||||
const commandCompleteBuffer = buffers.commandComplete('SELECT 3')
|
||||
const parseCompleteBuffer = buffers.parseComplete()
|
||||
const bindCompleteBuffer = buffers.bindComplete()
|
||||
const portalSuspendedBuffer = buffers.portalSuspended()
|
||||
|
||||
var row1 = {
|
||||
const row1 = {
|
||||
name: 'id',
|
||||
tableID: 1,
|
||||
attributeNumber: 2,
|
||||
@ -23,10 +23,10 @@ var row1 = {
|
||||
typeModifier: 5,
|
||||
formatCode: 0,
|
||||
}
|
||||
var oneRowDescBuff = buffers.rowDescription([row1])
|
||||
const oneRowDescBuff = buffers.rowDescription([row1])
|
||||
row1.name = 'bang'
|
||||
|
||||
var twoRowBuf = buffers.rowDescription([
|
||||
const twoRowBuf = buffers.rowDescription([
|
||||
row1,
|
||||
{
|
||||
name: 'whoah',
|
||||
@ -39,7 +39,7 @@ var twoRowBuf = buffers.rowDescription([
|
||||
},
|
||||
])
|
||||
|
||||
var rowWithBigOids = {
|
||||
const rowWithBigOids = {
|
||||
name: 'bigoid',
|
||||
tableID: 3000000001,
|
||||
attributeNumber: 2,
|
||||
@ -48,52 +48,52 @@ var rowWithBigOids = {
|
||||
typeModifier: 5,
|
||||
formatCode: 0,
|
||||
}
|
||||
var bigOidDescBuff = buffers.rowDescription([rowWithBigOids])
|
||||
const bigOidDescBuff = buffers.rowDescription([rowWithBigOids])
|
||||
|
||||
var emptyRowFieldBuf = buffers.dataRow([])
|
||||
const emptyRowFieldBuf = buffers.dataRow([])
|
||||
|
||||
var oneFieldBuf = buffers.dataRow(['test'])
|
||||
const oneFieldBuf = buffers.dataRow(['test'])
|
||||
|
||||
var expectedAuthenticationOkayMessage = {
|
||||
const expectedAuthenticationOkayMessage = {
|
||||
name: 'authenticationOk',
|
||||
length: 8,
|
||||
}
|
||||
|
||||
var expectedParameterStatusMessage = {
|
||||
const expectedParameterStatusMessage = {
|
||||
name: 'parameterStatus',
|
||||
parameterName: 'client_encoding',
|
||||
parameterValue: 'UTF8',
|
||||
length: 25,
|
||||
}
|
||||
|
||||
var expectedBackendKeyDataMessage = {
|
||||
const expectedBackendKeyDataMessage = {
|
||||
name: 'backendKeyData',
|
||||
processID: 1,
|
||||
secretKey: 2,
|
||||
}
|
||||
|
||||
var expectedReadyForQueryMessage = {
|
||||
const expectedReadyForQueryMessage = {
|
||||
name: 'readyForQuery',
|
||||
length: 5,
|
||||
status: 'I',
|
||||
}
|
||||
|
||||
var expectedCommandCompleteMessage = {
|
||||
const expectedCommandCompleteMessage = {
|
||||
name: 'commandComplete',
|
||||
length: 13,
|
||||
text: 'SELECT 3',
|
||||
}
|
||||
var emptyRowDescriptionBuffer = new BufferList()
|
||||
const emptyRowDescriptionBuffer = new BufferList()
|
||||
.addInt16(0) // number of fields
|
||||
.join(true, 'T')
|
||||
|
||||
var expectedEmptyRowDescriptionMessage = {
|
||||
const expectedEmptyRowDescriptionMessage = {
|
||||
name: 'rowDescription',
|
||||
length: 6,
|
||||
fieldCount: 0,
|
||||
fields: [],
|
||||
}
|
||||
var expectedOneRowMessage = {
|
||||
const expectedOneRowMessage = {
|
||||
name: 'rowDescription',
|
||||
length: 27,
|
||||
fieldCount: 1,
|
||||
@ -110,7 +110,7 @@ var expectedOneRowMessage = {
|
||||
],
|
||||
}
|
||||
|
||||
var expectedTwoRowMessage = {
|
||||
const expectedTwoRowMessage = {
|
||||
name: 'rowDescription',
|
||||
length: 53,
|
||||
fieldCount: 2,
|
||||
@ -135,7 +135,7 @@ var expectedTwoRowMessage = {
|
||||
},
|
||||
],
|
||||
}
|
||||
var expectedBigOidMessage = {
|
||||
const expectedBigOidMessage = {
|
||||
name: 'rowDescription',
|
||||
length: 31,
|
||||
fieldCount: 1,
|
||||
@ -152,36 +152,36 @@ var expectedBigOidMessage = {
|
||||
],
|
||||
}
|
||||
|
||||
var emptyParameterDescriptionBuffer = new BufferList()
|
||||
const emptyParameterDescriptionBuffer = new BufferList()
|
||||
.addInt16(0) // number of parameters
|
||||
.join(true, 't')
|
||||
|
||||
var oneParameterDescBuf = buffers.parameterDescription([1111])
|
||||
const oneParameterDescBuf = buffers.parameterDescription([1111])
|
||||
|
||||
var twoParameterDescBuf = buffers.parameterDescription([2222, 3333])
|
||||
const twoParameterDescBuf = buffers.parameterDescription([2222, 3333])
|
||||
|
||||
var expectedEmptyParameterDescriptionMessage = {
|
||||
const expectedEmptyParameterDescriptionMessage = {
|
||||
name: 'parameterDescription',
|
||||
length: 6,
|
||||
parameterCount: 0,
|
||||
dataTypeIDs: [],
|
||||
}
|
||||
|
||||
var expectedOneParameterMessage = {
|
||||
const expectedOneParameterMessage = {
|
||||
name: 'parameterDescription',
|
||||
length: 10,
|
||||
parameterCount: 1,
|
||||
dataTypeIDs: [1111],
|
||||
}
|
||||
|
||||
var expectedTwoParameterMessage = {
|
||||
const expectedTwoParameterMessage = {
|
||||
name: 'parameterDescription',
|
||||
length: 14,
|
||||
parameterCount: 2,
|
||||
dataTypeIDs: [2222, 3333],
|
||||
}
|
||||
|
||||
var testForMessage = function (buffer: Buffer, expectedMessage: any) {
|
||||
const testForMessage = function (buffer: Buffer, expectedMessage: any) {
|
||||
it('receives and parses ' + expectedMessage.name, async () => {
|
||||
const messages = await parseBuffers([buffer])
|
||||
const [lastMessage] = messages
|
||||
@ -192,38 +192,38 @@ var testForMessage = function (buffer: Buffer, expectedMessage: any) {
|
||||
})
|
||||
}
|
||||
|
||||
var plainPasswordBuffer = buffers.authenticationCleartextPassword()
|
||||
var md5PasswordBuffer = buffers.authenticationMD5Password()
|
||||
var SASLBuffer = buffers.authenticationSASL()
|
||||
var SASLContinueBuffer = buffers.authenticationSASLContinue()
|
||||
var SASLFinalBuffer = buffers.authenticationSASLFinal()
|
||||
const plainPasswordBuffer = buffers.authenticationCleartextPassword()
|
||||
const md5PasswordBuffer = buffers.authenticationMD5Password()
|
||||
const SASLBuffer = buffers.authenticationSASL()
|
||||
const SASLContinueBuffer = buffers.authenticationSASLContinue()
|
||||
const SASLFinalBuffer = buffers.authenticationSASLFinal()
|
||||
|
||||
var expectedPlainPasswordMessage = {
|
||||
const expectedPlainPasswordMessage = {
|
||||
name: 'authenticationCleartextPassword',
|
||||
}
|
||||
|
||||
var expectedMD5PasswordMessage = {
|
||||
const expectedMD5PasswordMessage = {
|
||||
name: 'authenticationMD5Password',
|
||||
salt: Buffer.from([1, 2, 3, 4]),
|
||||
}
|
||||
|
||||
var expectedSASLMessage = {
|
||||
const expectedSASLMessage = {
|
||||
name: 'authenticationSASL',
|
||||
mechanisms: ['SCRAM-SHA-256'],
|
||||
}
|
||||
|
||||
var expectedSASLContinueMessage = {
|
||||
const expectedSASLContinueMessage = {
|
||||
name: 'authenticationSASLContinue',
|
||||
data: 'data',
|
||||
}
|
||||
|
||||
var expectedSASLFinalMessage = {
|
||||
const expectedSASLFinalMessage = {
|
||||
name: 'authenticationSASLFinal',
|
||||
data: 'data',
|
||||
}
|
||||
|
||||
var notificationResponseBuffer = buffers.notification(4, 'hi', 'boom')
|
||||
var expectedNotificationResponseMessage = {
|
||||
const notificationResponseBuffer = buffers.notification(4, 'hi', 'boom')
|
||||
const expectedNotificationResponseMessage = {
|
||||
name: 'notification',
|
||||
processId: 4,
|
||||
channel: 'hi',
|
||||
@ -308,7 +308,7 @@ describe('PgPacketStream', function () {
|
||||
|
||||
describe('notice message', function () {
|
||||
// this uses the same logic as error message
|
||||
var buff = buffers.notice([{ type: 'C', value: 'code' }])
|
||||
const buff = buffers.notice([{ type: 'C', value: 'code' }])
|
||||
testForMessage(buff, {
|
||||
name: 'notice',
|
||||
code: 'code',
|
||||
@ -320,7 +320,7 @@ describe('PgPacketStream', function () {
|
||||
})
|
||||
|
||||
describe('with all the fields', function () {
|
||||
var buffer = buffers.error([
|
||||
const buffer = buffers.error([
|
||||
{
|
||||
type: 'S',
|
||||
value: 'ERROR',
|
||||
@ -466,7 +466,7 @@ describe('PgPacketStream', function () {
|
||||
// tcp packets anywhere, we need to make sure we can parse every single
|
||||
// split on a tcp message
|
||||
describe('split buffer, single message parsing', function () {
|
||||
var fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!'])
|
||||
const fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!'])
|
||||
|
||||
it('parses when full buffer comes in', async function () {
|
||||
const messages = await parseBuffers([fullBuffer])
|
||||
@ -479,9 +479,9 @@ describe('PgPacketStream', function () {
|
||||
assert.equal(message.fields[4], '!')
|
||||
})
|
||||
|
||||
var testMessageReceivedAfterSplitAt = async function (split: number) {
|
||||
var firstBuffer = Buffer.alloc(fullBuffer.length - split)
|
||||
var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
|
||||
const testMessageReceivedAfterSplitAt = async function (split: number) {
|
||||
const firstBuffer = Buffer.alloc(fullBuffer.length - split)
|
||||
const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
|
||||
fullBuffer.copy(firstBuffer, 0, 0)
|
||||
fullBuffer.copy(secondBuffer, 0, firstBuffer.length)
|
||||
const messages = await parseBuffers([firstBuffer, secondBuffer])
|
||||
@ -512,13 +512,13 @@ describe('PgPacketStream', function () {
|
||||
})
|
||||
|
||||
describe('split buffer, multiple message parsing', function () {
|
||||
var dataRowBuffer = buffers.dataRow(['!'])
|
||||
var readyForQueryBuffer = buffers.readyForQuery()
|
||||
var fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length)
|
||||
const dataRowBuffer = buffers.dataRow(['!'])
|
||||
const readyForQueryBuffer = buffers.readyForQuery()
|
||||
const fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length)
|
||||
dataRowBuffer.copy(fullBuffer, 0, 0)
|
||||
readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0)
|
||||
|
||||
var verifyMessages = function (messages: any[]) {
|
||||
const verifyMessages = function (messages: any[]) {
|
||||
assert.strictEqual(messages.length, 2)
|
||||
assert.deepEqual(messages[0], {
|
||||
name: 'dataRow',
|
||||
@ -539,9 +539,9 @@ describe('PgPacketStream', function () {
|
||||
verifyMessages(messages)
|
||||
})
|
||||
|
||||
var splitAndVerifyTwoMessages = async function (split: number) {
|
||||
var firstBuffer = Buffer.alloc(fullBuffer.length - split)
|
||||
var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
|
||||
const splitAndVerifyTwoMessages = async function (split: number) {
|
||||
const firstBuffer = Buffer.alloc(fullBuffer.length - split)
|
||||
const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
|
||||
fullBuffer.copy(firstBuffer, 0, 0)
|
||||
fullBuffer.copy(secondBuffer, 0, firstBuffer.length)
|
||||
const messages = await parseBuffers([firstBuffer, secondBuffer])
|
||||
|
||||
@ -46,7 +46,7 @@ describe('serializer', () => {
|
||||
})
|
||||
|
||||
it('builds query message', function () {
|
||||
var txt = 'select * from boom'
|
||||
const txt = 'select * from boom'
|
||||
const actual = serialize.query(txt)
|
||||
assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q'))
|
||||
})
|
||||
@ -54,7 +54,7 @@ describe('serializer', () => {
|
||||
describe('parse message', () => {
|
||||
it('builds parse message', function () {
|
||||
const actual = serialize.parse({ text: '!' })
|
||||
var expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P')
|
||||
const expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
@ -64,7 +64,7 @@ describe('serializer', () => {
|
||||
text: 'select * from boom',
|
||||
types: [],
|
||||
})
|
||||
var expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P')
|
||||
const expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
@ -74,7 +74,7 @@ describe('serializer', () => {
|
||||
text: 'select * from bang where name = $1',
|
||||
types: [1, 2, 3, 4],
|
||||
})
|
||||
var expected = new BufferList()
|
||||
const expected = new BufferList()
|
||||
.addCString('force')
|
||||
.addCString('select * from bang where name = $1')
|
||||
.addInt16(4)
|
||||
@ -91,11 +91,12 @@ describe('serializer', () => {
|
||||
it('with no values', function () {
|
||||
const actual = serialize.bind()
|
||||
|
||||
var expectedBuffer = new BufferList()
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('')
|
||||
.addCString('')
|
||||
.addInt16(0)
|
||||
.addInt16(0)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
@ -107,7 +108,7 @@ describe('serializer', () => {
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
})
|
||||
var expectedBuffer = new BufferList()
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
@ -123,6 +124,7 @@ describe('serializer', () => {
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
@ -136,7 +138,7 @@ describe('serializer', () => {
|
||||
values: ['1', 'hi', null, 'zing'],
|
||||
valueMapper: () => null,
|
||||
})
|
||||
var expectedBuffer = new BufferList()
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4)
|
||||
@ -149,6 +151,7 @@ describe('serializer', () => {
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt32(-1)
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
@ -160,7 +163,7 @@ describe('serializer', () => {
|
||||
statement: 'woo',
|
||||
values: ['1', 'hi', null, Buffer.from('zing', 'utf8')],
|
||||
})
|
||||
var expectedBuffer = new BufferList()
|
||||
const expectedBuffer = new BufferList()
|
||||
.addCString('bang') // portal name
|
||||
.addCString('woo') // statement name
|
||||
.addInt16(4) // value count
|
||||
@ -176,6 +179,7 @@ describe('serializer', () => {
|
||||
.addInt32(-1)
|
||||
.addInt32(4)
|
||||
.add(Buffer.from('zing', 'utf-8'))
|
||||
.addInt16(1)
|
||||
.addInt16(0)
|
||||
.join(true, 'B')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
@ -184,7 +188,7 @@ describe('serializer', () => {
|
||||
describe('builds execute message', function () {
|
||||
it('for unamed portal with no row limit', function () {
|
||||
const actual = serialize.execute()
|
||||
var expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E')
|
||||
const expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
|
||||
@ -193,39 +197,39 @@ describe('serializer', () => {
|
||||
portal: 'my favorite portal',
|
||||
rows: 100,
|
||||
})
|
||||
var expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E')
|
||||
const expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E')
|
||||
assert.deepEqual(actual, expectedBuffer)
|
||||
})
|
||||
})
|
||||
|
||||
it('builds flush command', function () {
|
||||
const actual = serialize.flush()
|
||||
var expected = new BufferList().join(true, 'H')
|
||||
const expected = new BufferList().join(true, 'H')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds sync command', function () {
|
||||
const actual = serialize.sync()
|
||||
var expected = new BufferList().join(true, 'S')
|
||||
const expected = new BufferList().join(true, 'S')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('builds end command', function () {
|
||||
const actual = serialize.end()
|
||||
var expected = Buffer.from([0x58, 0, 0, 0, 4])
|
||||
const expected = Buffer.from([0x58, 0, 0, 0, 4])
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
describe('builds describe command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serialize.describe({ type: 'S', name: 'bang' })
|
||||
var expected = new BufferList().addChar('S').addCString('bang').join(true, 'D')
|
||||
const expected = new BufferList().addChar('S').addCString('bang').join(true, 'D')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serialize.describe({ type: 'P' })
|
||||
var expected = new BufferList().addChar('P').addCString('').join(true, 'D')
|
||||
const expected = new BufferList().addChar('P').addCString('').join(true, 'D')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
@ -233,13 +237,13 @@ describe('serializer', () => {
|
||||
describe('builds close command', function () {
|
||||
it('describe statement', function () {
|
||||
const actual = serialize.close({ type: 'S', name: 'bang' })
|
||||
var expected = new BufferList().addChar('S').addCString('bang').join(true, 'C')
|
||||
const expected = new BufferList().addChar('S').addCString('bang').join(true, 'C')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
|
||||
it('describe unnamed portal', function () {
|
||||
const actual = serialize.close({ type: 'P' })
|
||||
var expected = new BufferList().addChar('P').addCString('').join(true, 'C')
|
||||
const expected = new BufferList().addChar('P').addCString('').join(true, 'C')
|
||||
assert.deepEqual(actual, expected)
|
||||
})
|
||||
})
|
||||
|
||||
@ -27,10 +27,10 @@ const startup = (opts: Record<string, string>): Buffer => {
|
||||
|
||||
writer.addCString('client_encoding').addCString('UTF8')
|
||||
|
||||
var bodyBuffer = writer.addCString('').flush()
|
||||
const bodyBuffer = writer.addCString('').flush()
|
||||
// this message is sent without a code
|
||||
|
||||
var length = bodyBuffer.length + 4
|
||||
const length = bodyBuffer.length + 4
|
||||
|
||||
return new Writer().addInt32(length).add(bodyBuffer).flush()
|
||||
}
|
||||
@ -78,23 +78,21 @@ const parse = (query: ParseOpts): Buffer => {
|
||||
// normalize missing query names to allow for null
|
||||
const name = query.name || ''
|
||||
if (name.length > 63) {
|
||||
/* eslint-disable no-console */
|
||||
console.error('Warning! Postgres only supports 63 characters for query names.')
|
||||
console.error('You supplied %s (%s)', name, name.length)
|
||||
console.error('This can cause conflicts and silent errors executing queries')
|
||||
/* eslint-enable no-console */
|
||||
}
|
||||
|
||||
const types = query.types || emptyArray
|
||||
|
||||
var len = types.length
|
||||
const len = types.length
|
||||
|
||||
var buffer = writer
|
||||
const buffer = writer
|
||||
.addCString(name) // name of query
|
||||
.addCString(query.text) // actual query text
|
||||
.addInt16(len)
|
||||
|
||||
for (var i = 0; i < len; i++) {
|
||||
for (let i = 0; i < len; i++) {
|
||||
buffer.addInt32(types[i])
|
||||
}
|
||||
|
||||
@ -159,6 +157,8 @@ const bind = (config: BindOpts = {}): Buffer => {
|
||||
writer.addInt16(len)
|
||||
writer.add(paramWriter.flush())
|
||||
|
||||
// all results use the same format code
|
||||
writer.addInt16(1)
|
||||
// format code
|
||||
writer.addInt16(binary ? ParamType.BINARY : ParamType.STRING)
|
||||
return writer.flush(code.bind)
|
||||
|
||||
@ -24,16 +24,16 @@ export default class BufferList {
|
||||
}
|
||||
|
||||
public addCString(val: string, front?: boolean) {
|
||||
var len = Buffer.byteLength(val)
|
||||
var buffer = Buffer.alloc(len + 1)
|
||||
const len = Buffer.byteLength(val)
|
||||
const buffer = Buffer.alloc(len + 1)
|
||||
buffer.write(val)
|
||||
buffer[len] = 0
|
||||
return this.add(buffer, front)
|
||||
}
|
||||
|
||||
public addString(val: string, front?: boolean) {
|
||||
var len = Buffer.byteLength(val)
|
||||
var buffer = Buffer.alloc(len)
|
||||
const len = Buffer.byteLength(val)
|
||||
const buffer = Buffer.alloc(len)
|
||||
buffer.write(val)
|
||||
return this.add(buffer, front)
|
||||
}
|
||||
@ -47,7 +47,7 @@ export default class BufferList {
|
||||
}
|
||||
|
||||
public join(appendLength?: boolean, char?: string): Buffer {
|
||||
var length = this.getByteLength()
|
||||
let length = this.getByteLength()
|
||||
if (appendLength) {
|
||||
this.addInt32(length + 4, true)
|
||||
return this.join(false, char)
|
||||
@ -56,8 +56,8 @@ export default class BufferList {
|
||||
this.addChar(char, true)
|
||||
length++
|
||||
}
|
||||
var result = Buffer.alloc(length)
|
||||
var index = 0
|
||||
const result = Buffer.alloc(length)
|
||||
let index = 0
|
||||
this.buffers.forEach(function (buffer) {
|
||||
buffer.copy(result, index, 0)
|
||||
index += buffer.length
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user