Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for user lookup function #2682

Open
wants to merge 43 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
197eec6
add support for user lookup function
Jan 7, 2022
ab04c47
Merge remote-tracking branch 'origin/master' into mlo-01-support-user…
Feb 27, 2023
d7aa006
fix: double client.end() hang (#2717)
cody-greene Mar 6, 2023
9550a5b
Fix typo in URL (#2913)
zegerius Mar 6, 2023
eb2dfdf
Emit a 'release' event when a connection is released back to the pool…
nihonjinrxs Mar 6, 2023
bf31d8b
Publish
brianc Mar 6, 2023
513d5c8
Update changelog
brianc Mar 6, 2023
d2b5644
Update path to documentation in readme (#2925)
brianc Mar 7, 2023
4ae37da
Add release event to Pool API docs (#2928)
nihonjinrxs Mar 16, 2023
cf18167
docs(client): improve the Client instance example (#2935)
samueldurantes Mar 30, 2023
46dda41
Update README.md (#2944)
brianc Mar 30, 2023
ef5a13e
fix(theme.config.js): Replace default meta description and social tit…
janpio Apr 20, 2023
898fa0f
Fix race condition in release event test for pool (#2969)
brianc May 1, 2023
1eab647
docs(api/result): clarify that `result.rowCount` can be `null` (#2967)
futile May 1, 2023
7685718
Document client.escapeIdentifier and client.escapeLiteral (#2954)
TheConner May 2, 2023
09b4123
Add local development helper doc
petebacondarwin Apr 18, 2023
1298697
fix invalid connection string test
petebacondarwin May 4, 2023
5423d71
Use `URL` rather than `url.parse()` in pg-connection-string
petebacondarwin May 4, 2023
e1f4f32
avoid accessing Node specific requires when not needed
petebacondarwin May 4, 2023
5389d78
Use WebCrypto APIs where possible
petebacondarwin Apr 19, 2023
1151ac9
Add Cloudflare Worker compatible socket
petebacondarwin Apr 19, 2023
a5c73ec
Add example Cloudflare Worker and test
petebacondarwin May 4, 2023
838e3a4
Clean up pg-native in Makefile better
petebacondarwin May 11, 2023
cbfdc99
Publish
brianc May 15, 2023
6934a69
Update utils.js (#2981)
sudarshanvn May 19, 2023
f317ec9
Revert "Update utils.js (#2981)"
charmander May 23, 2023
ce491c0
Fix typo in types.mdx (#2989)
enahs May 29, 2023
b2953ad
Fix connection string parsing for overriden hosts (#2977)
domdomegg May 31, 2023
a4bc6a4
feat: add connection parameter nativeConnectionString (#2941)
NovikovEvgeny May 31, 2023
e4ae887
Make `async/await` the primary examples in the docs (#2932)
rijkvanzanten May 31, 2023
24874fa
fix: ensure that pg-cloudflare can be used with bundlers that don't k…
petebacondarwin May 31, 2023
1d29d64
fix stack traces of query() to include the async context (#1762) (#2983)
phiresky May 31, 2023
37e87e0
Add note about case sensitivity of result of pg.escapeIdentifier (#2993)
jasonford Jun 1, 2023
bf33696
Fix a typo in README.md (#3002)
rikurauhala Jun 5, 2023
fcdfe5c
Remove await from client release (#3006)
filipecorrea Jun 12, 2023
7804cad
Fix typo in project-structure.md (#3008)
thearian Jun 13, 2023
c04cf9f
Publish
brianc Jun 26, 2023
fb11d76
Bump prettier from 2.7.1 to 2.8.8 (#3024)
dependabot[bot] Jul 7, 2023
41db6bf
Bump workerd from 1.20230419.0 to 1.20230518.0 (#3023)
dependabot[bot] Jul 7, 2023
49f55d3
Update pg-connection-string url in connecting.mdx (#3005)
rikurauhala Jul 7, 2023
f99f385
Remove early return for non commonjs environments (#3033)
benjreinhart Jul 19, 2023
56ee4eb
pg-connection-string: avoid clobbering port from queryparams (#2833)
rafiss Jul 21, 2023
6a378f2
Publish
brianc Aug 1, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

## [email protected]

- Emit `release` event when client is returned to [the pool](https://github.com/brianc/node-postgres/pull/2845).

## [email protected]

- Add support for [stream factory](https://github.com/brianc/node-postgres/pull/2898).
Expand Down
43 changes: 43 additions & 0 deletions LOCAL_DEV.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Local development

Steps to install and configure Postgres on Mac for developing against locally

1. Install homebrew
2. Install postgres
```sh
brew install postgresql
```
3. Create a database
```sh
createdb test
```
4. Create SSL certificates
```sh
cd /opt/homebrew/var/postgresql@14
openssl genrsa -aes128 2048 > server.key
openssl rsa -in server.key -out server.key
chmod 400 server.key
openssl req -new -key server.key -days 365 -out server.crt -x509
cp server.crt root.crt
```
5. Update config in `/opt/homebrew/var/postgresql@14/postgresql.conf`

```conf
listen_addresses = '*'

password_encryption = md5

ssl = on
ssl_ca_file = 'root.crt'
ssl_cert_file = 'server.crt'
ssl_crl_file = ''
ssl_crl_dir = ''
ssl_key_file = 'server.key'
ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
ssl_prefer_server_ciphers = on
```

6. Start Postgres server
```sh
/opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14
```
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Each package in this repo should have its own readme more focused on how to deve

### :star: [Documentation](https://node-postgres.com) :star:

The source repo for the documentation is https://github.com/brianc/node-postgres-docs.
The source repo for the documentation is available for contribution [here](https://github.com/brianc/node-postgres/tree/master/docs).

### Features

Expand Down Expand Up @@ -55,7 +55,7 @@ You can also follow me [@briancarlson](https://twitter.com/briancarlson) if that

## Sponsorship :two_hearts:

node-postgres's continued development has been made possible in part by generous finanical support from [the community](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md).
node-postgres's continued development has been made possible in part by generous financial support from [the community](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md).

If you or your company are benefiting from node-postgres and would like to help keep the project financially sustainable [please consider supporting](https://github.com/sponsors/brianc) its development.

Expand Down
4 changes: 2 additions & 2 deletions docs/pages/announcements.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ _If you find `pg` valuable to you or your business please consider [supporting](

After a _very_ long time on my todo list I've ported the docs from my old hand-rolled webapp running on route53 + elb + ec2 + dokku (I know, I went overboard!) to [gatsby](https://www.gatsbyjs.org/) hosted on [netlify](https://www.netlify.com/) which is _so_ much easier to manage. I've released the code at [https://github.com/brianc/node-postgres-docs](https://github.com/brianc/node-postgres-docs) and invite your contributions! Let's make this documentation better together. Any time changes are merged to master on the documentation repo it will automatically deploy.

If you see an error in the docs, big or small, use the "edit on github" button to edit the page & submit a pull request right there. I'll get a new version out ASAP with your changes! If you want to add new pages of documentation open an issue if you need guidance, and I'll help you get started.
If you see an error in the docs, big or small, use the "edit on GitHub" button to edit the page & submit a pull request right there. I'll get a new version out ASAP with your changes! If you want to add new pages of documentation open an issue if you need guidance, and I'll help you get started.

I want to extend a special **thank you** to all the [supporters](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md) and [contributors](https://github.com/brianc/node-postgres/graphs/contributors) to the project that have helped keep me going through times of burnout or life "getting in the way." ❤️

Expand Down Expand Up @@ -116,7 +116,7 @@ [email protected]
To demonstrate the issue & see if you are vunerable execute the following in node:

```js
const { Client } = require('pg')
import { Client } from 'pg'
const client = new Client()
client.connect()

Expand Down
3 changes: 2 additions & 1 deletion docs/pages/apis/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"pool": "pg.Pool",
"result": "pg.Result",
"types": "pg.Types",
"cursor": "Cursor"
"cursor": "Cursor",
"utilities": "Utilities"
}
148 changes: 29 additions & 119 deletions docs/pages/apis/client.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,45 +29,26 @@ type Config = {
example to create a client with specific connection information:

```js
const { Client } = require('pg')
import { Client } from 'pg'

const client = new Client({
host: 'my.database-server.com',
port: 5334,
database: 'database-name',
user: 'database-user',
password: 'secretpassword!!',
})
```

## client.connect

Calling `client.connect` with a callback:

```js
const { Client } = require('pg')
import { Client } from 'pg'
const client = new Client()
client.connect((err) => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
})
```

Calling `client.connect` without a callback yields a promise:

```js
const { Client } = require('pg')
const client = new Client()
client
.connect()
.then(() => console.log('connected'))
.catch((err) => console.error('connection error', err.stack))
await client.connect()
```

_note: connect returning a promise only available in [email protected] or above_

## client.query

### QueryConfig
Expand All @@ -94,77 +75,43 @@ type QueryConfig {
}
```

### callback API

```ts
client.query(text: string, values?: any[], callback?: (err: Error, result: QueryResult) => void) => void
```

**Plain text query with a callback:**

```js
const { Client } = require('pg')
const client = new Client()
client.connect()
client.query('SELECT NOW()', (err, res) => {
if (err) throw err
console.log(res)
client.end()
})
client.query(text: string, values?: any[]) => Promise<Result>
```

**Parameterized query with a callback:**
**Plain text query**

```js
const { Client } = require('pg')
import { Client } from 'pg'
const client = new Client()
client.connect()
client.query('SELECT $1::text as name', ['brianc'], (err, res) => {
if (err) throw err
console.log(res)
client.end()
})
```

### Promise API
await client.connect()

If you call `client.query` with query text and optional parameters but **don't** pass a callback, then you will receive a `Promise` for a query result.
const result = await client.query('SELECT NOW()')
console.log(result)

```ts
client.query(text: string, values?: any[]) => Promise<Result>
await client.end()
```

**Plain text query with a promise**
**Parameterized query**

```js
const { Client } = require('pg')
import { Client } from 'pg'
const client = new Client()
client.connect()
client
.query('SELECT NOW()')
.then((result) => console.log(result))
.catch((e) => console.error(e.stack))
.then(() => client.end())
```

**Parameterized query with a promise**
await client.connect()

```js
const { Client } = require('pg')
const client = new Client()
client.connect()
client
.query('SELECT $1::text as name', ['brianc'])
.then((result) => console.log(result))
.catch((e) => console.error(e.stack))
.then(() => client.end())
const result = await client.query('SELECT $1::text as name', ['brianc'])
console.log(result)

await client.end()
```

```ts
client.query(config: QueryConfig) => Promise<Result>
```

**client.query with a QueryConfig and a callback**
**client.query with a QueryConfig**

If you pass a `name` parameter to the `client.query` method, the client will create a [prepared statement](/features/queries#prepared-statements).

Expand All @@ -176,42 +123,18 @@ const query = {
rowMode: 'array',
}

client.query(query, (err, res) => {
if (err) {
console.error(err.stack)
} else {
console.log(res.rows) // ['brianc']
}
})
```

**client.query with a QueryConfig and a Promise**
const result = await client.query(query)
console.log(result.rows) // ['brianc']

```js
const query = {
name: 'get-name',
text: 'SELECT $1::text',
values: ['brianc'],
rowMode: 'array',
}

// promise
client
.query(query)
.then((res) => {
console.log(res.rows) // ['brianc']
})
.catch((e) => {
console.error(e.stack)
})
await client.end()
```

**client.query with a `Submittable`**

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
const Query = require('pg').Query
import { Query } from 'pg'
const query = new Query('select $1::text as name', ['brianc'])

const result = client.query(query)
Expand All @@ -221,9 +144,11 @@ assert(query === result) // true
query.on('row', (row) => {
console.log('row!', row) // { name: 'brianc' }
})

query.on('end', () => {
console.log('query done')
})

query.on('error', (err) => {
console.error(err.stack)
})
Expand All @@ -236,25 +161,10 @@ query.on('error', (err) => {
Disconnects the client from the PostgreSQL server.

```js
client.end((err) => {
console.log('client has disconnected')
if (err) {
console.log('error during disconnection', err.stack)
}
})
await client.end()
console.log('client has disconnected')
```

Calling end without a callback yields a promise:

```js
client
.end()
.then(() => console.log('client has disconnected'))
.catch((err) => console.error('error during disconnection', err.stack))
```

_note: end returning a promise is only available in pg7.0 and above_

## events

### error
Expand All @@ -263,7 +173,7 @@ _note: end returning a promise is only available in pg7.0 and above_
client.on('error', (err: Error) => void) => void
```

When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and foward errors from the PostgreSQL server to the respective `client.connect` `client.query` or `client.end` callback/promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period _will_) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:
When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and foward errors from the PostgreSQL server to the respective `client.connect` `client.query` or `client.end` promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period _will_) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:

```js
const client = new pg.Client()
Expand Down Expand Up @@ -300,7 +210,7 @@ type Notification {

```js
const client = new pg.Client()
client.connect()
await client.connect()

client.query('LISTEN foo')

Expand Down
Loading