Initial commit
This commit is contained in:
49
node_modules/@neondatabase/serverless/CHANGELOG.md
generated
vendored
Normal file
49
node_modules/@neondatabase/serverless/CHANGELOG.md
generated
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
## 0.10.1 (2024-10-07)
|
||||
|
||||
Fix `CONFIG.MD` documentation.
|
||||
|
||||
## 0.10.0 (2024-10-07)
|
||||
|
||||
Capture stack traces in `NeonDbError`, if `Error.captureStackTrace` is available.
|
||||
|
||||
Allow authentication through `JWT` by adding a `authToken` property to the `neon` HTTP connection options.
|
||||
|
||||
## 0.9.3 (2024-05-09)
|
||||
|
||||
Expose all error information fields on `NeonDbError` objects thrown when using the http fetch transport.
|
||||
|
||||
## 0.9.2 (2024-05-09)
|
||||
|
||||
JSR README updates only.
|
||||
|
||||
## 0.9.1 (2024-04-15)
|
||||
|
||||
Pass username (and database name) through URL decoder, so all usernames can successfully authorize.
|
||||
|
||||
## 0.9.0 (2024-02-27)
|
||||
|
||||
Deprecate `fetchConnectionCache` option, which is now always enabled. For `neon` http fetch queries, enable setting options on individual queries within a batch `transaction` (but note that the types still do not allow this).
|
||||
|
||||
## 0.8.1 (2024-02-07)
|
||||
|
||||
Revert single per-region domain for WebSockets. Fix treatment of -pooler connection hosts.
|
||||
|
||||
## 0.8.0 (2024-02-06)
|
||||
|
||||
Use a single (per-region) domain name for all connections to Neon databases. Intended to help with connection caching in V8. Passes the endpoint ID inside connection options for WebSocket connections.
|
||||
|
||||
## 0.7.2 (2024-01-10)
|
||||
|
||||
Export a full ESM build to index.mjs -- don't just wrap the CJS code -- since no wrapping method seems reliable across bundlers and platforms. It's now important to only `require` or only `import` the package: if you mix, you'll get two copies of the code that don't share configuration changes.
|
||||
|
||||
## 0.7.1 (2024-01-09)
|
||||
|
||||
Fixed index.d.mts.
|
||||
|
||||
## 0.7.0 (2024-01-08)
|
||||
|
||||
Altered ESM re-export technique (in index.mjs) to work around WebPack issues. Added a re-export of TypeScript types (as index.d.mts) to fix the 'Masquerading as CJS' warning from https://arethetypeswrong.github.io/.
|
||||
|
||||
## 0.6.1 (2023-12-19)
|
||||
|
||||
WebSocket connection errors are now reported properly via `client.on('error', err => { /* ... */ })`.
|
||||
311
node_modules/@neondatabase/serverless/CONFIG.md
generated
vendored
Normal file
311
node_modules/@neondatabase/serverless/CONFIG.md
generated
vendored
Normal file
@ -0,0 +1,311 @@
|
||||
# Options and configuration
|
||||
|
||||
## `neon(...)` function
|
||||
|
||||
The `neon(...)` function returns a query function that can be used both as a tagged-template function and as an ordinary function:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
|
||||
// as a tagged-template function
|
||||
const rowsA = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
|
||||
// as an ordinary function (exactly equivalent)
|
||||
const rowsB = await sql('SELECT * FROM posts WHERE id = $1', [postId]);
|
||||
```
|
||||
|
||||
By default, the query function returned by `neon(...)` returns only the rows resulting from the provided SQL query, and it returns them as an array of objects where the keys are column names. For example:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const rows = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
// -> [{ id: 12, title: "My post", ... }]
|
||||
```
|
||||
|
||||
However, you can customise the return format of the query function using the configuration options `fullResults` and `arrayMode`. These options are available both on the `neon(...)` function and on the query function it returns (but only when the query function is called as an ordinary function, not as a tagged-template function).
|
||||
|
||||
### `arrayMode: boolean`
|
||||
|
||||
When `arrayMode` is true, rows are returned as an array of arrays instead of an array of objects:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL, { arrayMode: true });
|
||||
const rows = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
// -> [[12, "My post", ...]]
|
||||
```
|
||||
|
||||
Or, with the same effect:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const rows = await sql('SELECT * FROM posts WHERE id = $1', [postId], {
|
||||
arrayMode: true,
|
||||
});
|
||||
// -> [[12, "My post", ...]]
|
||||
```
|
||||
|
||||
### `fullResults: boolean`
|
||||
|
||||
When `fullResults` is true, additional metadata is returned alongside the result rows, which are then found in the `rows` property of the return value. The metadata matches what would be returned by node-postgres:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL, { fullResults: true });
|
||||
const results = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
/* -> {
|
||||
rows: [{ id: 12, title: "My post", ... }],
|
||||
fields: [
|
||||
{ name: "id", dataTypeID: 23, ... },
|
||||
{ name: "title", dataTypeID: 25, ... },
|
||||
...
|
||||
],
|
||||
rowCount: 1,
|
||||
rowAsArray: false,
|
||||
command: "SELECT"
|
||||
}
|
||||
*/
|
||||
```
|
||||
|
||||
Or, with the same effect:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const results = await sql('SELECT * FROM posts WHERE id = $1', [postId], {
|
||||
fullResults: true,
|
||||
});
|
||||
// -> { ... same as above ... }
|
||||
```
|
||||
|
||||
### `fetchOptions: Record<string, any>`
|
||||
|
||||
The `fetchOptions` option can be passed to `neon(...)`, the `transaction` function, or the query function (if not within a `transaction` function). This option takes an object that is merged with the options to the `fetch` call.
|
||||
|
||||
For example, to increase the priority of every database `fetch` request:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL, {
|
||||
fetchOptions: { priority: 'high' },
|
||||
});
|
||||
const rows = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
```
|
||||
|
||||
Or to implement a `fetch` timeout:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const abortController = new AbortController();
|
||||
const timeout = setTimeout(() => abortController.abort('timed out'), 10000);
|
||||
const rows = await sql('SELECT * FROM posts WHERE id = $1', [postId], {
|
||||
fetchOptions: { signal: abortController.signal },
|
||||
}); // throws an error if no result received within 10s
|
||||
clearTimeout(timeout);
|
||||
```
|
||||
|
||||
### `authToken: string | (() => Promise<string> | string)`
|
||||
|
||||
The `authToken` option can be passed to `neon(...)` to set the `Authorization` header for the `fetch` request. This allows you to authenticate database requests against third-party authentication providers. So, this mechanism can be used to ensure that access control and authorization are managed effectively across different systems.
|
||||
|
||||
Example of usage:
|
||||
|
||||
```typescript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
// Retrieve the JWT token (implementation depends on your auth system)
|
||||
const authToken = getAuthToken();
|
||||
// Initialize the Neon client with a connection string and auth token
|
||||
const sql = neon(process.env.DATABASE_URL, { authToken });
|
||||
// Run a query
|
||||
const posts = await sql('SELECT * FROM posts');
|
||||
```
|
||||
|
||||
## `transaction(...)` function
|
||||
|
||||
The `transaction(queriesOrFn, options)` function is exposed as a property on the query function. It allows multiple queries to be executed within a single, non-interactive transaction.
|
||||
|
||||
The first argument to `transaction()`, `queriesOrFn`, is either (1) an array of queries or (2) a non-`async` function that receives a query function as its argument and returns an array of queries.
|
||||
|
||||
The array-of-queries case looks like this:
|
||||
|
||||
```javascript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const showLatestN = 10;
|
||||
|
||||
const [posts, tags] = await sql.transaction(
|
||||
[
|
||||
sql`SELECT * FROM posts ORDER BY posted_at DESC LIMIT ${showLatestN}`,
|
||||
sql`SELECT * FROM tags`,
|
||||
],
|
||||
{
|
||||
isolationLevel: 'RepeatableRead',
|
||||
readOnly: true,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
Or as an example of the function case:
|
||||
|
||||
```javascript
|
||||
const [authors, tags] = await neon(process.env.DATABASE_URL).transaction(
|
||||
(txn) => [txn`SELECT * FROM authors`, txn`SELECT * FROM tags`],
|
||||
);
|
||||
```
|
||||
|
||||
The optional second argument to `transaction()`, `options`, has the same keys as the options to the ordinary query function -- `arrayMode`, `fullResults` and `fetchOptions` -- plus three additional keys that concern the transaction configuration. These transaction-related keys are: `isolationMode`, `readOnly` and `deferrable`. They are described below. Defaults for the transaction-related keys can also be set as options to the `neon` function.
|
||||
|
||||
The `fetchOptions` option cannot be supplied for individual queries inside `transaction()`, since only a single `fetch` is performed for the transaction as a whole. The TypeScript types also currently do not allow `arrayMode` or `fullResults` options to be supplied for individual queries within `transaction()` (although this does have the expected effect if the type errors are ignored).
|
||||
|
||||
### `isolationMode`
|
||||
|
||||
This option selects a Postgres [transaction isolation mode](https://www.postgresql.org/docs/current/transaction-iso.html). If present, it must be one of: `'ReadUncommitted'`, `'ReadCommitted'`, `'RepeatableRead'` or `'Serializable'`.
|
||||
|
||||
### `readOnly`
|
||||
|
||||
If `true`, this option ensures that a `READ ONLY` transaction is used to execute the queries passed.
|
||||
|
||||
### `deferrable`
|
||||
|
||||
If `true` (and if `readOnly` is also `true`, and `isolationMode` is `'Serializable'`), this option ensures that a `DEFERRABLE` transaction is used to execute the queries passed.
|
||||
|
||||
## `neonConfig` configuration
|
||||
|
||||
In most cases, there are two ways to set configuration options:
|
||||
|
||||
1. Import `neonConfig` from the package and set global default options on that.
|
||||
2. Set options on individual `Client` instances using their `neonConfig` property.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
import { Client, neonConfig } from '@neondatabase/serverless';
|
||||
import ws from 'ws';
|
||||
|
||||
// set default option for all clients
|
||||
neonConfig.webSocketConstructor = ws;
|
||||
|
||||
// override the default option on an individual client
|
||||
const client = new Client(process.env.DATABASE_URL);
|
||||
client.neonConfig.webSocketConstructor = ws;
|
||||
```
|
||||
|
||||
A few configuration options can only be set globally, and these are noted as such below.
|
||||
|
||||
#### `webSocketConstructor: typeof WebSocket | undefined`
|
||||
|
||||
Set this parameter if you're using the driver in an environment where the `WebSocket` global is not defined, such as Node.js, and you need transaction or session support.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
import { neonConfig } from '@neondatabase/serverless';
|
||||
import ws from 'ws';
|
||||
neonConfig.webSocketConstructor = ws;
|
||||
```
|
||||
|
||||
### Advanced configuration
|
||||
|
||||
If you're using `@neondatabase/serverless` to connect to a Neon database, you usually **won't** need to touch the following configuration options. These options are intended for testing, troubleshooting, and supporting access to non-Neon Postgres instances via self-hosted WebSocket proxies.
|
||||
|
||||
#### `poolQueryViaFetch: boolean`
|
||||
|
||||
**Experimentally**, when `poolQueryViaFetch` is `true` and no listeners for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP `fetch` request.
|
||||
|
||||
Default: currently `false` (but may be `true` in future).
|
||||
|
||||
Note: this option can only be set globally, **not** on an individual `Client` instance.
|
||||
|
||||
#### `fetchEndpoint: string | ((host: string, port: number | string) => string)`
|
||||
|
||||
Set `fetchEndpoint` to set the server endpoint to be sent queries via http fetch.
|
||||
|
||||
This may be useful for local development (e.g. to set a port that's not the default 443).
|
||||
|
||||
Provide either the full endpoint URL, or a function that takes the database host address and port and returns the full endpoint URL (including protocol).
|
||||
|
||||
Default: `host => 'https://' + host + '/sql'`
|
||||
|
||||
Note: this option can only be set globally, **not** on an individual `Client` instance.
|
||||
|
||||
#### `fetchFunction: any`
|
||||
|
||||
The `fetchFunction` option allows you to supply an alternative function for making http requests. The function must accept the same arguments as native `fetch`.
|
||||
|
||||
Default: `undefined`.
|
||||
|
||||
Note: this option can only be set globally, **not** on an individual `Client` instance.
|
||||
|
||||
#### `wsProxy: string | (host: string, port: number | string) => string`
|
||||
|
||||
If connecting to a non-Neon database, the `wsProxy` option should point to [your WebSocket proxy](DEPLOY.md). It can either be a string, which will have `?address=host:port` appended to it, or a function with the signature `(host: string, port: number | string) => string`. Either way, the protocol must _not_ be included, because this depends on other options. For example, when using the `wsproxy` proxy, the `wsProxy` option should look something like this:
|
||||
|
||||
```javascript
|
||||
// either:
|
||||
neonConfig.wsProxy = (host, port) =>
|
||||
`my-wsproxy.example.com/v1?address=${host}:${port}`;
|
||||
// or (with identical effect):
|
||||
neonConfig.wsProxy = 'my-wsproxy.example.com/v1';
|
||||
```
|
||||
|
||||
Default: `host => host + '/v2'`.
|
||||
|
||||
#### `pipelineConnect: "password" | false`
|
||||
|
||||
To speed up connection times, the driver will pipeline the first three messages to the database (startup, authentication and first query) if `pipelineConnect` is set to `"password"`. Note that this will only work if you've configured cleartext password authentication for the relevant user and database.
|
||||
|
||||
If your connection doesn't support password authentication, set `pipelineConnect` to `false` instead.
|
||||
|
||||
Default: `"password"`.
|
||||
|
||||
#### `coalesceWrites: boolean`
|
||||
|
||||
When this option is `true`, multiple network writes generated in a single iteration of the JavaScript run-loop are coalesced into a single WebSocket message. Since node-postgres sends a lot of very short messages, this may reduce TCP/IP overhead.
|
||||
|
||||
Default: `true`.
|
||||
|
||||
#### `forceDisablePgSSL: boolean`
|
||||
|
||||
This option disables TLS encryption in the Postgres protocol (as set via e.g. `?sslmode=require` in the connection string). Security is not compromised if used in conjunction with `useSecureWebSocket = true`.
|
||||
|
||||
Default: `true`.
|
||||
|
||||
#### `useSecureWebSocket: boolean`
|
||||
|
||||
This option switches between secure (the default) and insecure WebSockets.
|
||||
|
||||
To use experimental pure-JS encryption, set `useSecureWebSocket = false` and `forceDisablePgSSL = false`, and append `?sslmode=verify-full` to your database connection string.
|
||||
|
||||
**Remember that pure-JS encryption is currently experimental and not suitable for use in production.**
|
||||
|
||||
Default: `true`.
|
||||
|
||||
#### `subtls: any`
|
||||
|
||||
**Only when using experimental pure-JS TLS encryption**, you must supply the [subtls](https://github.com/jawj/subtls) TLS library to the `subtls` option like so:
|
||||
|
||||
```typescript
|
||||
import { neonConfig } from '@neondatabase/serverless';
|
||||
import * as subtls from 'subtls';
|
||||
neonConfig.subtls = subtls;
|
||||
```
|
||||
|
||||
Default: `undefined`.
|
||||
|
||||
#### `rootCerts: string /* PEM format */`
|
||||
|
||||
**Only when using experimental pure-JS TLS encryption**, the `rootCerts` option determines what root (certificate authority) certificates are trusted.
|
||||
|
||||
Its value is a string containing zero or more certificates in PEM format.
|
||||
|
||||
Default: `""` (the empty string).
|
||||
|
||||
#### `pipelineTLS: boolean`
|
||||
|
||||
**Only when using experimental pure-JS encryption**, the driver will pipeline the SSL request message and TLS Client Hello if `pipelineTLS` is set to `true`. Currently, this is only supported by Neon database hosts, and will fail when communicating with an ordinary Postgres or pgbouncer back-end.
|
||||
|
||||
Default: `false`.
|
||||
132
node_modules/@neondatabase/serverless/DEPLOY.md
generated
vendored
Normal file
132
node_modules/@neondatabase/serverless/DEPLOY.md
generated
vendored
Normal file
@ -0,0 +1,132 @@
|
||||
# Deploying a WebSocket proxy in front of your own Postgres instance
|
||||
|
||||
**This package comes configured to connect to a Neon database over a secure (`wss:`) WebSocket. If you're using a Neon database, you can ignore what follows.**
|
||||
|
||||
But you can also run your own WebSocket proxy, and configure it to allow onward connections to your own Postgres instances.
|
||||
|
||||
First, you'll need to set up the proxy itself somewhere public-facing (or on `localhost` for development). See https://github.com/neondatabase/wsproxy for the Go code and instructions.
|
||||
|
||||
There are then two ways you can secure this:
|
||||
|
||||
1. Set up nginx as a TLS proxy in front of `wsproxy`. Example shell commands to achieve this can be found below. Onward traffic to Postgres is not secured by this method, so Postgres should be running on the same machine or be reached over a private network.
|
||||
|
||||
2. Use experimental pure-JS Postgres connection encryption via [subtls](https://github.com/jawj/subtls). There's no need for nginx in this scenario, and the Postgres connection is encrypted end-to-end. You get this form of encryption if you set both `neonConfig.useSecureWebSocket` and `neonConfig.forceDisablePgSSL` to `false`, and append `?sslmode=verify-full` (or similar) to your connection string. TLS version 1.3 must be supported by the Postgres back-end. **Please note that subtls is experimental software and this configuration is not recommended for production use.**
|
||||
|
||||
Second, you'll need to set some [configuration options](CONFIG.md) on this package: at a minimum the `wsProxy` option and (if using experimental encryption) `subtls` and `rootCerts`.
|
||||
|
||||
## Example shell commands
|
||||
|
||||
To deploy `wsproxy` behind nginx (for TLS) on a host `ws.example.com` running Ubuntu 22.04 (and Postgres locally), you'd do something similar to the following.
|
||||
|
||||
Before you start:
|
||||
|
||||
1. Ensure port 443 is accessible on this machine. You might need to change firewall settings with your platform provider.
|
||||
|
||||
2. Upgrade to Ubuntu 22.04 if on an earlier version (golang is too old on older releases):
|
||||
|
||||
```bash
|
||||
sudo su # do this all as root
|
||||
apt update -y && apt upgrade -y && apt dist-upgrade -y
|
||||
apt autoremove -y && apt autoclean -y
|
||||
apt install -y update-manager-core
|
||||
do-release-upgrade # and answer yes to all defaults
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
sudo su # do this all as root
|
||||
|
||||
export HOSTDOMAIN=ws.example.com # edit the domain name for your case
|
||||
|
||||
# if required: install postgres + create a password-auth user
|
||||
|
||||
apt install -y postgresql
|
||||
|
||||
echo 'create database wstest; create user wsclear; grant all privileges on database wstest to wsclear;' | sudo -u postgres psql
|
||||
|
||||
sudo -u postgres psql # and run: \password wsclear
|
||||
|
||||
perl -pi -e 's/^# IPv4 local connections:\n/# IPv4 local connections:\nhost all wsclear 127.0.0.1\/32 password\n/' /etc/postgresql/14/main/pg_hba.conf
|
||||
|
||||
service postgresql restart
|
||||
|
||||
# install wsproxy
|
||||
|
||||
adduser wsproxy --disabled-login
|
||||
|
||||
sudo su wsproxy
|
||||
cd
|
||||
git clone https://github.com/neondatabase/wsproxy.git
|
||||
cd wsproxy
|
||||
go build
|
||||
exit
|
||||
|
||||
echo "
|
||||
[Unit]
|
||||
Description=wsproxy
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
User=wsproxy
|
||||
Environment=LISTEN_PORT=:6543 ALLOW_ADDR_REGEX='^${HOSTDOMAIN}:5432\$'
|
||||
ExecStart=/home/wsproxy/wsproxy/wsproxy
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
" > /lib/systemd/system/wsproxy.service
|
||||
|
||||
systemctl enable wsproxy
|
||||
service wsproxy start
|
||||
|
||||
# install nginx as tls proxy
|
||||
|
||||
apt install -y golang nginx certbot python3-certbot-nginx
|
||||
|
||||
echo "127.0.0.1 ${HOSTDOMAIN}" >> /etc/hosts
|
||||
|
||||
echo "
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name ${HOSTDOMAIN};
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:6543/;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection Upgrade;
|
||||
proxy_set_header Host \$host;
|
||||
}
|
||||
}
|
||||
" > /etc/nginx/sites-available/wsproxy
|
||||
|
||||
ln -s /etc/nginx/sites-available/wsproxy /etc/nginx/sites-enabled/wsproxy
|
||||
|
||||
certbot --nginx -d ${HOSTDOMAIN}
|
||||
|
||||
echo "
|
||||
server {
|
||||
server_name ${HOSTDOMAIN};
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:6543/;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection Upgrade;
|
||||
proxy_set_header Host \$host;
|
||||
}
|
||||
|
||||
listen [::]:80 ipv6only=on;
|
||||
listen 80;
|
||||
|
||||
listen [::]:443 ssl ipv6only=on; # managed by Certbot
|
||||
listen 443 ssl; # managed by Certbot
|
||||
ssl_certificate /etc/letsencrypt/live/${HOSTDOMAIN}/fullchain.pem; # managed by Certbot
|
||||
ssl_certificate_key /etc/letsencrypt/live/${HOSTDOMAIN}/privkey.pem; # managed by Certbot
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
|
||||
}
|
||||
" > /etc/nginx/sites-available/wsproxy
|
||||
|
||||
service nginx restart
|
||||
```
|
||||
24
node_modules/@neondatabase/serverless/DEVELOP.md
generated
vendored
Normal file
24
node_modules/@neondatabase/serverless/DEVELOP.md
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Development and contributing
|
||||
|
||||
The code is at https://github.com/neondatabase/serverless. Most of the interesting stuff is in `shims/net/index.ts` and the `export/` folder.
|
||||
|
||||
- To update the npm & jsr package:
|
||||
|
||||
```bash
|
||||
npm run export
|
||||
cd dist/npm
|
||||
npm version patch # or minor or major
|
||||
npm publish
|
||||
|
||||
# Copy npm version
|
||||
jq --arg v "$(jq -r .version dist/npm/package.json)" '.version = $v' dist/jsr/jsr.json > dist/jsr/jsr.json.tmp && mv dist/jsr/jsr.json.tmp dist/jsr/jsr.json
|
||||
|
||||
# Publish jsr package
|
||||
npx jsr publish
|
||||
```
|
||||
|
||||
- To run or deploy the simple test app on Cloudflare, create a `.dev.vars` file containing `NEON_DB_URL=postgres://connection_string`, run `npx wrangler dev --local` or `npx wrangler publish`.
|
||||
|
||||
- To run the latencies test app in a browser, create a `.dev.vars` file as above, run `npm run browser` and visit `http://localhost:7070/dist/browser/`. To include debug output and avoid minification, use `npm run browserDebug` instead.
|
||||
|
||||
- To run the latencies test app in node, create a `.dev.vars` file as above and run `npm run node`. To include debug output and avoid minification, use `npm run nodeDebug` instead.
|
||||
21
node_modules/@neondatabase/serverless/LICENSE
generated
vendored
Normal file
21
node_modules/@neondatabase/serverless/LICENSE
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 - 2024 Neon Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
283
node_modules/@neondatabase/serverless/README.md
generated
vendored
Normal file
283
node_modules/@neondatabase/serverless/README.md
generated
vendored
Normal file
@ -0,0 +1,283 @@
|
||||
# @neondatabase/serverless
|
||||
|
||||
`@neondatabase/serverless` is [Neon](https://neon.tech)'s PostgreSQL driver for JavaScript and TypeScript. It's:
|
||||
|
||||
- **Low-latency**, thanks to [message pipelining](https://neon.tech/blog/quicker-serverless-postgres) and other optimizations
|
||||
- **Ideal for serverless/edge** deployment, using https and WebSockets in place of TCP
|
||||
- **A drop-in replacement** for [node-postgres](https://node-postgres.com/), aka [`pg`](https://www.npmjs.com/package/pg) (on which it's based)
|
||||
|
||||
## Get started
|
||||
|
||||
### Install it
|
||||
|
||||
Install it with your preferred JavaScript package manager. It's named `@neondatabase/serverless` on npm and `@neon/serverless` on JSR. So, for example:
|
||||
|
||||
```bash
|
||||
npm install @neondatabase/serverless
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
bunx jsr add @neon/serverless
|
||||
```
|
||||
|
||||
Using TypeScript? No worries: types are included either way.
|
||||
|
||||
### Configure it
|
||||
|
||||
Get your connection string from the [Neon console](https://console.neon.tech/) and set it as an environment variable. Something like:
|
||||
|
||||
```
|
||||
DATABASE_URL=postgres://username:password@host.neon.tech/neondb
|
||||
```
|
||||
|
||||
### Use it
|
||||
|
||||
For one-shot queries, use the `neon` function. For instance:
|
||||
|
||||
```javascript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
|
||||
const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
// `post` is now { id: 12, title: 'My post', ... } (or undefined)
|
||||
```
|
||||
|
||||
Note: interpolating `${postId}` here is [safe from SQL injection](https://neon.tech/blog/sql-template-tags).
|
||||
|
||||
### Deploy it
|
||||
|
||||
Turn this example into a complete API endpoint deployed on [Vercel Edge Functions](https://vercel.com/docs/concepts/functions/edge-functions) at `https://myapp.vercel.dev/api/post?postId=123` by following two simple steps:
|
||||
|
||||
1. Create a new file `api/post.ts`:
|
||||
|
||||
```javascript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
|
||||
export default async (req: Request, ctx: any) => {
|
||||
// get and validate the `postId` query parameter
|
||||
const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10);
|
||||
if (isNaN(postId)) return new Response('Bad request', { status: 400 });
|
||||
|
||||
// query and validate the post
|
||||
const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
||||
if (!post) return new Response('Not found', { status: 404 });
|
||||
|
||||
// return the post as JSON
|
||||
return new Response(JSON.stringify(post), {
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
runtime: 'edge',
|
||||
regions: ['iad1'], // specify the region nearest your Neon DB
|
||||
};
|
||||
```
|
||||
|
||||
2. Test and deploy
|
||||
|
||||
```bash
|
||||
npm install -g vercel # install vercel CLI
|
||||
npx vercel env add DATABASE_URL # paste Neon connection string, select all environments
|
||||
npx vercel dev # check working locally, then ...
|
||||
npx vercel deploy
|
||||
```
|
||||
|
||||
The `neon` query function has a few [additional options](CONFIG.md).
|
||||
|
||||
## Sessions, transactions, and node-postgres compatibility
|
||||
|
||||
A query using the `neon` function, as shown above, is carried by an https [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) request.
|
||||
|
||||
This should work — and work fast — from any modern JavaScript environment. But you can only send one query at a time this way: sessions and transactions are not supported.
|
||||
|
||||
### `transaction()`
|
||||
|
||||
Multiple queries can be issued via fetch request within a single, non-interactive transaction by using the `transaction()` function. This is exposed as a property on the query function.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
import { neon } from '@neondatabase/serverless';
|
||||
const sql = neon(process.env.DATABASE_URL);
|
||||
const showLatestN = 10;
|
||||
|
||||
const [posts, tags] = await sql.transaction([
|
||||
sql`SELECT * FROM posts ORDER BY posted_at DESC LIMIT ${showLatestN}`,
|
||||
sql`SELECT * FROM tags`,
|
||||
]);
|
||||
```
|
||||
|
||||
There are some [additional options](CONFIG.md) when using `transaction()`.
|
||||
|
||||
### `Pool` and `Client`
|
||||
|
||||
Use the `Pool` or `Client` constructors, instead of the functions described above, when you need:
|
||||
|
||||
- **session or interactive transaction support**, and/or
|
||||
|
||||
- **compatibility with node-postgres**, which supports query libraries like [Kysely](https://kysely.dev/) or [Zapatos](https://jawj.github.io/zapatos/).
|
||||
|
||||
Queries using `Pool` and `Client` are carried by WebSockets. There are **two key things** to know about this:
|
||||
|
||||
1. **In Node.js** and some other environments, there's no built-in WebSocket support. In these cases, supply a WebSocket constructor function.
|
||||
|
||||
2. **In serverless environments** such as Vercel Edge Functions or Cloudflare Workers, WebSocket connections can't outlive a single request.
|
||||
|
||||
That means `Pool` or `Client` objects must be connected, used and closed **within a single request handler**. Don't create them outside a request handler; don't create them in one handler and try to reuse them in another; and to avoid exhausting available connections, don't forget to close them.
|
||||
|
||||
These points are demonstrated in the examples below.
|
||||
|
||||
### API
|
||||
|
||||
- **The full API guide** to `Pool` and `Client` can be found in the [node-postgres docs](https://node-postgres.com/).
|
||||
|
||||
- There are a few [additional configuration options](CONFIG.md) that apply to `Pool` and `Client` here.
|
||||
|
||||
## Example: Node.js with `Pool.connect()`
|
||||
|
||||
In Node.js, it takes two lines to configure WebSocket support. For example:
|
||||
|
||||
```javascript
|
||||
import { Pool, neonConfig } from '@neondatabase/serverless';
|
||||
|
||||
import ws from 'ws';
|
||||
neonConfig.webSocketConstructor = ws; // <-- this is the key bit
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
pool.on('error', (err) => console.error(err)); // deal with e.g. re-connect
|
||||
// ...
|
||||
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const {
|
||||
rows: [{ id: postId }],
|
||||
} = await client.query('INSERT INTO posts (title) VALUES ($1) RETURNING id', [
|
||||
'Welcome',
|
||||
]);
|
||||
await client.query('INSERT INTO photos (post_id, url) VALUES ($1, $2)', [
|
||||
postId,
|
||||
's3.bucket/photo/url',
|
||||
]);
|
||||
await client.query('COMMIT');
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
|
||||
// ...
|
||||
await pool.end();
|
||||
```
|
||||
|
||||
Other WebSocket libraries are available. For example, you could replace `ws` in the above example with `undici`:
|
||||
|
||||
```typescript
|
||||
import { WebSocket } from 'undici';
|
||||
neonConfig.webSocketConstructor = WebSocket;
|
||||
```
|
||||
|
||||
## Example: Vercel Edge Function with `Pool.query()`
|
||||
|
||||
We can rewrite the Vercel Edge Function shown above (under the heading 'Deploy it') to use `Pool`, as follows:
|
||||
|
||||
```javascript
|
||||
import { Pool } from '@neondatabase/serverless';
|
||||
|
||||
// *don't* create a `Pool` or `Client` here, outside the request handler
|
||||
|
||||
export default async (req: Request, ctx: any) => {
|
||||
// create a `Pool` inside the request handler
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
|
||||
// get and validate the `postId` query parameter
|
||||
const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10);
|
||||
if (isNaN(postId)) return new Response('Bad request', { status: 400 });
|
||||
|
||||
// query and validate the post
|
||||
const [post] = await pool.query('SELECT * FROM posts WHERE id = $1', [postId]);
|
||||
if (!post) return new Response('Not found', { status: 404 });
|
||||
|
||||
// end the `Pool` inside the same request handler
|
||||
// (unlike `await`, `ctx.waitUntil` won't hold up the response)
|
||||
ctx.waitUntil(pool.end());
|
||||
|
||||
// return the post as JSON
|
||||
return new Response(JSON.stringify(post), {
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
runtime: 'edge',
|
||||
regions: ['iad1'], // specify the region nearest your Neon DB
|
||||
};
|
||||
```
|
||||
|
||||
Note: we don't actually use the pooling capabilities of `Pool` in this example. But it's slightly briefer than using `Client` and, because `Pool.query` is designed for one-shot queries, we may in future automatically route these queries over https for lower latency.
|
||||
|
||||
## Example: Vercel Edge Function with `Client`
|
||||
|
||||
Using `Client` instead, the example looks like this:
|
||||
|
||||
```javascript
|
||||
import { Client } from '@neondatabase/serverless';
|
||||
|
||||
// don't create a `Pool` or `Client` here, outside the request handler
|
||||
|
||||
export default async (req: Request, ctx: any) => {
|
||||
// create a `Client` inside the request handler
|
||||
const client = new Client(process.env.DATABASE_URL);
|
||||
await client.connect();
|
||||
|
||||
// get and validate the `postId` query parameter
|
||||
const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10);
|
||||
if (isNaN(postId)) return new Response('Bad request', { status: 400 });
|
||||
|
||||
// query and validate the post
|
||||
const [post] = await client.query('SELECT * FROM posts WHERE id = $1', [postId]);
|
||||
if (!post) return new Response('Not found', { status: 404 });
|
||||
|
||||
// end the `Client` inside the same request handler
|
||||
// (unlike `await`, `ctx.waitUntil` won't hold up the response)
|
||||
ctx.waitUntil(client.end());
|
||||
|
||||
// return the post as JSON
|
||||
return new Response(JSON.stringify(post), {
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
runtime: 'edge',
|
||||
regions: ['iad1'], // specify the region nearest your Neon DB
|
||||
};
|
||||
```
|
||||
|
||||
## More examples
|
||||
|
||||
These repos show how to use `@neondatabase/serverless` with a variety of environments and tools:
|
||||
|
||||
- [Raw SQL + Vercel Edge Functions](https://github.com/neondatabase/neon-vercel-rawsql)
|
||||
- [Raw SQL via https + Vercel Edge Functions](https://github.com/neondatabase/neon-vercel-http)
|
||||
- [Raw SQL + Cloudflare Workers](https://github.com/neondatabase/serverless-cfworker-demo)
|
||||
- [Kysely + Vercel Edge Functions](https://github.com/neondatabase/neon-vercel-kysely)
|
||||
- [Zapatos + Vercel Edge Functions](https://github.com/neondatabase/neon-vercel-zapatos)
|
||||
|
||||
## Bring your own Postgres database
|
||||
|
||||
This package comes configured to connect to a Neon database. But you can also use it to connect to your own Postgres instances if you [run your own WebSocket proxy](DEPLOY.md).
|
||||
|
||||
## Open-source
|
||||
|
||||
This code is released under the [MIT license](LICENSE).
|
||||
|
||||
## Feedback and support
|
||||
|
||||
Please visit [Neon Community](https://community.neon.tech/) or [Support](https://neon.tech/docs/introduction/support).
|
||||
430
node_modules/@neondatabase/serverless/index.d.mts
generated
vendored
Normal file
430
node_modules/@neondatabase/serverless/index.d.mts
generated
vendored
Normal file
@ -0,0 +1,430 @@
|
||||
|
||||
// DON'T EDIT THIS FILE
|
||||
// It's a simple automatic copy of index.d.ts
|
||||
|
||||
|
||||
// @neondatabase/serverless driver types, mimicking pg
|
||||
|
||||
export {
|
||||
BindConfig, ClientConfig, Connection, ConnectionConfig, CustomTypesConfig, Defaults, defaults, Events, ExecuteConfig, FieldDef, MessageConfig, native, Notification, PoolConfig, Query, QueryArrayConfig, QueryArrayResult, QueryConfig, QueryParse, QueryResult, QueryResultBase,
|
||||
QueryResultRow, ResultBuilder, Submittable, types
|
||||
} from "pg";
|
||||
export { DatabaseError } from "pg-protocol";
|
||||
|
||||
interface FetchEndpointOptions {
|
||||
jwtAuth?: boolean;
|
||||
}
|
||||
|
||||
export interface NeonConfigGlobalOnly {
|
||||
/**
|
||||
* Set `fetchEndpoint` to set the server endpoint to be sent queries via http
|
||||
* fetch. May be useful in local development (e.g. to set a port that's not
|
||||
* the default 443).
|
||||
*
|
||||
* Provide either the full endpoint URL, or a function that takes the
|
||||
* database host address and port and returns the full endpoint URL
|
||||
* (including protocol).
|
||||
*
|
||||
* Default: `host => 'https://' + host + '/sql'`
|
||||
*
|
||||
*/
|
||||
fetchEndpoint: string | ((host: string, port: number | string, options?: FetchEndpointOptions) => string);
|
||||
|
||||
/**
|
||||
* **Experimentally**, when `poolQueryViaFetch` is `true`, and no listeners
|
||||
* for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set
|
||||
* on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP
|
||||
* fetch request.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
poolQueryViaFetch: boolean;
|
||||
|
||||
/**
|
||||
* **DEPRECATED**. Previously, only when `fetchConnectionCache` was `true`
|
||||
* did queries carried via HTTP fetch make use of a connection pool/cache
|
||||
* on the server. All queries now use the connection pool/cache: this setting
|
||||
* is ignored.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
fetchConnectionCache: boolean;
|
||||
|
||||
/**
|
||||
* The `fetchFunction` option allows you to supply an alternative function
|
||||
* for making http requests. The function must accept the same arguments as
|
||||
* native `fetch`.
|
||||
*
|
||||
* Default: `undefined`.
|
||||
*/
|
||||
fetchFunction: any;
|
||||
}
|
||||
|
||||
export interface NeonConfigGlobalAndClient {
|
||||
/**
|
||||
* If no global `WebSocket` object is available, set `webSocketConstructor`
|
||||
* to the constructor for a custom WebSocket implementation, such as those
|
||||
* provided by `ws` or `undici`.
|
||||
*/
|
||||
webSocketConstructor: any;
|
||||
|
||||
/**
|
||||
* Set `wsProxy` to use your own WebSocket proxy server.
|
||||
*
|
||||
* Provide either the proxy server’s domain name, or a function that takes
|
||||
* the database host and port and returns the proxy server address (without
|
||||
* protocol).
|
||||
*
|
||||
* Example: `(host, port) => "myproxy.example.net?address=" + host + ":" + port`
|
||||
*
|
||||
* Default: `host => host + '/v2'`
|
||||
*/
|
||||
wsProxy: string | ((host: string, port: number | string) => string) | undefined;
|
||||
|
||||
/**
|
||||
* Use a secure (`wss:`) connection to the WebSocket proxy.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
useSecureWebSocket: boolean;
|
||||
|
||||
/**
|
||||
* Disable TLS encryption in the Postgres protocol (as set via e.g.
|
||||
* `?sslmode=require` in the connection string). Connection remains secure
|
||||
* if `useSecureWebSocket` is `true`.
|
||||
*
|
||||
* Default: `true`
|
||||
*/
|
||||
forceDisablePgSSL: boolean;
|
||||
|
||||
/**
|
||||
* Pipelines the startup message, cleartext password message and first query
|
||||
* when set to `"password"`. This works only for cleartext password auth.
|
||||
*
|
||||
* Default: `"password"`.
|
||||
*/
|
||||
pipelineConnect: "password" | false;
|
||||
|
||||
/**
|
||||
* If `forceDisablePgSSL` is `false` and the Postgres connection parameters
|
||||
* specify TLS, you must supply the subtls TLS library to this option:
|
||||
*
|
||||
* ```
|
||||
* import { neonConfig } from '@neondatabase/serverless';
|
||||
* import * as subtls from 'subtls';
|
||||
* neonConfig.subtls = subtls;
|
||||
* ```
|
||||
*
|
||||
* Default: `undefined`.
|
||||
*/
|
||||
subtls: any;
|
||||
|
||||
/**
|
||||
* Pipeline the pg SSL request and TLS handshake when `forceDisablePgSSL` is
|
||||
* `false` and the Postgres connection parameters specify TLS. Currently
|
||||
* compatible only with Neon hosts.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
pipelineTLS: boolean;
|
||||
|
||||
/**
|
||||
* Set `rootCerts` to a string comprising one or more PEM files. These are
|
||||
* the trusted root certificates for a TLS connection to Postgres when
|
||||
* `forceDisablePgSSL` is `false` and the Postgres connection parameters
|
||||
* specify TLS.
|
||||
*
|
||||
* Default: `""`.
|
||||
*/
|
||||
rootCerts: string;
|
||||
|
||||
/**
|
||||
* Batch multiple network writes per run-loop into a single outgoing
|
||||
* WebSocket message.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
coalesceWrites: boolean;
|
||||
|
||||
/**
|
||||
* When `disableSNI` is `true`, `forceDisablePgSSL` is `false` and the
|
||||
* Postgres connection parameters specify TLS, we send no SNI data in the
|
||||
* Postgres TLS handshake.
|
||||
*
|
||||
* On Neon, disabling SNI and including the Neon project name in the password
|
||||
* avoids CPU-intensive SCRAM authentication, but this is only relevant for
|
||||
* earlier iterations of Neon's WebSocket support.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
disableSNI: boolean;
|
||||
}
|
||||
|
||||
export interface NeonConfig extends NeonConfigGlobalOnly, NeonConfigGlobalAndClient { }
|
||||
|
||||
import {
|
||||
Client as PgClient,
|
||||
ClientBase as PgClientBase,
|
||||
Pool as PgPool,
|
||||
PoolClient as PgPoolClient,
|
||||
} from "pg";
|
||||
|
||||
export class ClientBase extends PgClientBase {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export class Client extends PgClient {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export interface PoolClient extends PgPoolClient {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export class Pool extends PgPool {
|
||||
connect(): Promise<PoolClient>;
|
||||
connect(callback: (err: Error, client: PoolClient, done: (release?: any) => void) => void): void;
|
||||
on(event: 'error', listener: (err: Error, client: PoolClient) => void): this;
|
||||
on(event: 'connect' | 'acquire' | 'remove', listener: (client: PoolClient) => void): this;
|
||||
}
|
||||
|
||||
export const neonConfig: NeonConfig;
|
||||
|
||||
|
||||
// SQL-over-HTTP
|
||||
|
||||
import { FieldDef } from "pg";
|
||||
|
||||
export type QueryRows<ArrayMode extends boolean> =
|
||||
ArrayMode extends true ? any[][] : Record<string, any>[];
|
||||
|
||||
export interface FullQueryResults<ArrayMode extends boolean> {
|
||||
fields: FieldDef[];
|
||||
command: string;
|
||||
rowCount: number;
|
||||
rows: QueryRows<ArrayMode>;
|
||||
rowAsArray: ArrayMode;
|
||||
}
|
||||
|
||||
export interface ParameterizedQuery {
|
||||
query: string;
|
||||
params: any[];
|
||||
}
|
||||
|
||||
export interface HTTPQueryOptions<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
/**
|
||||
* When `arrayMode` is `false`, which is the default, result rows are
|
||||
* returned as objects whose keys represent column names, such as
|
||||
* `{ id: 1 }`).
|
||||
*
|
||||
* When `arrayMode` is `true`, rows are returned as arrays (and keys are not
|
||||
* provided), e.g. `[1]`.
|
||||
*/
|
||||
arrayMode?: ArrayMode;
|
||||
/**
|
||||
* When `fullResults` is `false`, which is the default, only result rows are
|
||||
* returned, e.g. `[{ id: 1 }]`).
|
||||
*
|
||||
* When `fullResults` is `true`, a result object is returned that matches
|
||||
* what's returned by node-postgres. This has a `rows` property, which is an
|
||||
* array of result rows, plus `fields`, which provides column names and
|
||||
* types, `command` and `rowCount`.
|
||||
*/
|
||||
fullResults?: FullResults; // default false
|
||||
/**
|
||||
* Any options in `fetchOptions` are merged in to the options passed to
|
||||
* `fetch`. In case of conflict with what would otherwise be passed, these
|
||||
* options take precedence.
|
||||
*/
|
||||
fetchOptions?: Record<string, any>;
|
||||
|
||||
/**
|
||||
* JWT auth token to be passed as the Bearer token in the Authorization header
|
||||
*
|
||||
* Default: `undefined`
|
||||
*/
|
||||
authToken?: string | (() => Promise<string> | string);
|
||||
}
|
||||
|
||||
export interface HTTPTransactionOptions<ArrayMode extends boolean, FullResults extends boolean> extends HTTPQueryOptions<ArrayMode, FullResults> {
|
||||
/**
|
||||
* Postgres transaction isolation level: see https://www.postgresql.org/docs/current/transaction-iso.html.
|
||||
* Note that `ReadUncommitted` actually gets you `ReadCommitted` in Postgres.
|
||||
* */
|
||||
isolationLevel?: 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable';
|
||||
/**
|
||||
* When `readOnly` is `false`, which is the default, a `READ WRITE` Postgres
|
||||
* transaction is used.
|
||||
*
|
||||
* When `readOnly` is `true`, a `READ ONLY` Postgres transaction is used.
|
||||
* */
|
||||
readOnly?: boolean;
|
||||
/**
|
||||
* When `deferrable` is `false`, which is the default, a `NOT DEFERRABLE`
|
||||
* Postgres transaction is used.
|
||||
*
|
||||
* When `deferrable` is `true` (and `isolationLevel` is `Serializable` and
|
||||
* `readOnly` is `true`), a `DEFERRABLE` Postgres transaction is used.
|
||||
* */
|
||||
deferrable?: boolean;
|
||||
}
|
||||
|
||||
export interface NeonQueryPromise<ArrayMode extends boolean, FullResults extends boolean, T = any> extends Promise<T> {
|
||||
parameterizedQuery: ParameterizedQuery;
|
||||
opts?: HTTPQueryOptions<ArrayMode, FullResults>;
|
||||
}
|
||||
|
||||
export interface NeonQueryInTransaction {
|
||||
// this is a simplified form of query, which has only a `parameterizedQuery` (no `opts` and not a `Promise`)
|
||||
parameterizedQuery: ParameterizedQuery;
|
||||
}
|
||||
|
||||
export interface NeonQueryFunctionInTransaction<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
// this is a simplified form of NeonQueryFunction (below):
|
||||
// * `opts` cannot be passed
|
||||
// * no `transaction()` method is available
|
||||
|
||||
// tagged-template function usage
|
||||
(strings: TemplateStringsArray, ...params: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
|
||||
// ordinary function usage (*no* options overrides)
|
||||
(string: string, params?: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
}
|
||||
|
||||
export interface NeonQueryFunction<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
// tagged-template function usage
|
||||
(strings: TemplateStringsArray, ...params: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
|
||||
// ordinary function usage, with options overrides
|
||||
<ArrayModeOverride extends boolean = ArrayMode, FullResultsOverride extends boolean = FullResults>(
|
||||
string: string,
|
||||
params?: any[],
|
||||
opts?: HTTPQueryOptions<ArrayModeOverride, FullResultsOverride>
|
||||
): NeonQueryPromise<
|
||||
ArrayModeOverride,
|
||||
FullResultsOverride,
|
||||
FullResultsOverride extends true ? FullQueryResults<ArrayModeOverride> : QueryRows<ArrayModeOverride>
|
||||
>;
|
||||
|
||||
/**
|
||||
* The `transaction()` function allows multiple queries to be submitted (over
|
||||
* HTTP) as a single, non-interactive Postgres transaction.
|
||||
*
|
||||
* For example:
|
||||
* ```
|
||||
* import { neon } from "@neondatabase/serverless";
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
*
|
||||
* const results = await sql.transaction([
|
||||
* sql`SELECT 1 AS num`,
|
||||
* sql`SELECT 'a' AS str`,
|
||||
* ]);
|
||||
* // -> [[{ num: 1 }], [{ str: "a" }]]
|
||||
*
|
||||
* // or equivalently:
|
||||
* const results = await sql.transaction(txn => [
|
||||
* txn`SELECT 1 AS num`,
|
||||
* txn`SELECT 'a' AS str`,
|
||||
* ]);
|
||||
* // -> [[{ num: 1 }], [{ str: "a" }]]
|
||||
* ```
|
||||
* @param queriesOrFn Either an array of queries, or a (non-`async`) function
|
||||
* that receives a query function and returns an array of queries.
|
||||
* @param opts The same options that may be set on individual queries in a
|
||||
* non-transaction setting -- that is, `arrayMode` `fullResults` and
|
||||
* `fetchOptions` -- plus the transaction options `isolationLevel`,
|
||||
* `readOnly` and `deferrable`. Note that none of these options can be set on
|
||||
* individual queries within a transaction.
|
||||
* @returns An array of results. The structure of each result object depends
|
||||
* on the `arrayMode` and `fullResults` options.
|
||||
*/
|
||||
transaction: <ArrayModeOverride extends boolean = ArrayMode, FullResultsOverride extends boolean = FullResults>(
|
||||
queriesOrFn: NeonQueryPromise<ArrayMode, FullResults>[] | // not ArrayModeOverride or FullResultsOverride: clamp these values to the current ones
|
||||
((sql: NeonQueryFunctionInTransaction<ArrayModeOverride, FullResultsOverride>) => NeonQueryInTransaction[]),
|
||||
opts?: HTTPTransactionOptions<ArrayModeOverride, FullResultsOverride>
|
||||
) => Promise<FullResultsOverride extends true ? FullQueryResults<ArrayModeOverride>[] : QueryRows<ArrayModeOverride>[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function returns an async tagged-template function that runs a single
|
||||
* SQL query (no session or transactions) with low latency over https. Support
|
||||
* for multiple queries as a non-interactive transaction is provided by
|
||||
* the `transaction` property of the query function.
|
||||
*
|
||||
* By default, the query function returns database rows directly. Types should
|
||||
* match those returned by this driver (i.e. Pool or Client) over WebSockets.
|
||||
*
|
||||
* The returned function can also be called directly (i.e. not as a template
|
||||
* function). In that case, pass it a query string with embedded `$1`, `$2`
|
||||
* (etc.), followed by an array of query parameters, followed (optionally) by
|
||||
* any of the same options you can pass to this function.
|
||||
*
|
||||
* Some examples:
|
||||
* ```
|
||||
* import { neon } from "@neondatabase/serverless";
|
||||
* const h = "hello", w = "world";
|
||||
*
|
||||
* // example 1: default options, tagged-template usage
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
* const rows = await sql`SELECT ${h} || ' ' || ${w} AS greeting`;
|
||||
* // -> [ { greeting: "hello world" } ]
|
||||
*
|
||||
* // example 2: `arrayMode` and `fullResults` options, ordinary function usage
|
||||
* const options = { arrayMode: true, fullResults: true };
|
||||
* const sql = neon("postgres://user:pass@host/db", options);
|
||||
* const rows = await sql("SELECT $1 || ' ' || $2 AS greeting", [h, w]);
|
||||
* // -> {
|
||||
* // command: "SELECT",
|
||||
* // fields: [ { name: "greeting", dataTypeID: 25 } ],
|
||||
* // rowAsArray: true,
|
||||
* // rowCount: 1,
|
||||
* // rows: [ [ "hello world" ] ]
|
||||
* // }
|
||||
*
|
||||
* // example 3: `fetchOptions` option, ordinary function usage
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
* const rows = await sql(
|
||||
* "SELECT $1 || ' ' || $2 AS greeting", [h, w],
|
||||
* { fetchOptions: { priority: "high" } }
|
||||
* );
|
||||
* // -> [ { greeting: "hello world" } ]
|
||||
* ```
|
||||
*
|
||||
* @param connectionString this has the format `postgres://user:pass@host/db`
|
||||
* @param options pass `arrayMode: true` to receive results as an array of
|
||||
* arrays, instead of the default array of objects; pass `fullResults: true`
|
||||
* to receive a complete result object similar to one returned by node-postgres
|
||||
* (with properties `rows`, `fields`, `command`, `rowCount`, `rowAsArray`);
|
||||
* pass as `fetchOptions` an object which will be merged into the options
|
||||
* passed to `fetch`.
|
||||
*/
|
||||
export function neon<ArrayMode extends boolean = false, FullResults extends boolean = false>(
|
||||
connectionString: string,
|
||||
options?: HTTPTransactionOptions<ArrayMode, FullResults>,
|
||||
): NeonQueryFunction<ArrayMode, FullResults>;
|
||||
|
||||
export class NeonDbError extends Error {
|
||||
name: 'NeonDbError';
|
||||
|
||||
severity: string | undefined;
|
||||
code: string | undefined;
|
||||
detail: string | undefined;
|
||||
hint: string | undefined;
|
||||
position: string | undefined;
|
||||
internalPosition: string | undefined;
|
||||
internalQuery: string | undefined;
|
||||
where: string | undefined;
|
||||
schema: string | undefined;
|
||||
table: string | undefined;
|
||||
column: string | undefined;
|
||||
dataType: string | undefined;
|
||||
constraint: string | undefined;
|
||||
file: string | undefined;
|
||||
line: string | undefined;
|
||||
routine: string | undefined;
|
||||
|
||||
sourceError: Error | undefined;
|
||||
}
|
||||
426
node_modules/@neondatabase/serverless/index.d.ts
generated
vendored
Normal file
426
node_modules/@neondatabase/serverless/index.d.ts
generated
vendored
Normal file
@ -0,0 +1,426 @@
|
||||
|
||||
// @neondatabase/serverless driver types, mimicking pg
|
||||
|
||||
export {
|
||||
BindConfig, ClientConfig, Connection, ConnectionConfig, CustomTypesConfig, Defaults, defaults, Events, ExecuteConfig, FieldDef, MessageConfig, native, Notification, PoolConfig, Query, QueryArrayConfig, QueryArrayResult, QueryConfig, QueryParse, QueryResult, QueryResultBase,
|
||||
QueryResultRow, ResultBuilder, Submittable, types
|
||||
} from "pg";
|
||||
export { DatabaseError } from "pg-protocol";
|
||||
|
||||
interface FetchEndpointOptions {
|
||||
jwtAuth?: boolean;
|
||||
}
|
||||
|
||||
export interface NeonConfigGlobalOnly {
|
||||
/**
|
||||
* Set `fetchEndpoint` to set the server endpoint to be sent queries via http
|
||||
* fetch. May be useful in local development (e.g. to set a port that's not
|
||||
* the default 443).
|
||||
*
|
||||
* Provide either the full endpoint URL, or a function that takes the
|
||||
* database host address and port and returns the full endpoint URL
|
||||
* (including protocol).
|
||||
*
|
||||
* Default: `host => 'https://' + host + '/sql'`
|
||||
*
|
||||
*/
|
||||
fetchEndpoint: string | ((host: string, port: number | string, options?: FetchEndpointOptions) => string);
|
||||
|
||||
/**
|
||||
* **Experimentally**, when `poolQueryViaFetch` is `true`, and no listeners
|
||||
* for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set
|
||||
* on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP
|
||||
* fetch request.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
poolQueryViaFetch: boolean;
|
||||
|
||||
/**
|
||||
* **DEPRECATED**. Previously, only when `fetchConnectionCache` was `true`
|
||||
* did queries carried via HTTP fetch make use of a connection pool/cache
|
||||
* on the server. All queries now use the connection pool/cache: this setting
|
||||
* is ignored.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
fetchConnectionCache: boolean;
|
||||
|
||||
/**
|
||||
* The `fetchFunction` option allows you to supply an alternative function
|
||||
* for making http requests. The function must accept the same arguments as
|
||||
* native `fetch`.
|
||||
*
|
||||
* Default: `undefined`.
|
||||
*/
|
||||
fetchFunction: any;
|
||||
}
|
||||
|
||||
export interface NeonConfigGlobalAndClient {
|
||||
/**
|
||||
* If no global `WebSocket` object is available, set `webSocketConstructor`
|
||||
* to the constructor for a custom WebSocket implementation, such as those
|
||||
* provided by `ws` or `undici`.
|
||||
*/
|
||||
webSocketConstructor: any;
|
||||
|
||||
/**
|
||||
* Set `wsProxy` to use your own WebSocket proxy server.
|
||||
*
|
||||
* Provide either the proxy server’s domain name, or a function that takes
|
||||
* the database host and port and returns the proxy server address (without
|
||||
* protocol).
|
||||
*
|
||||
* Example: `(host, port) => "myproxy.example.net?address=" + host + ":" + port`
|
||||
*
|
||||
* Default: `host => host + '/v2'`
|
||||
*/
|
||||
wsProxy: string | ((host: string, port: number | string) => string) | undefined;
|
||||
|
||||
/**
|
||||
* Use a secure (`wss:`) connection to the WebSocket proxy.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
useSecureWebSocket: boolean;
|
||||
|
||||
/**
|
||||
* Disable TLS encryption in the Postgres protocol (as set via e.g.
|
||||
* `?sslmode=require` in the connection string). Connection remains secure
|
||||
* if `useSecureWebSocket` is `true`.
|
||||
*
|
||||
* Default: `true`
|
||||
*/
|
||||
forceDisablePgSSL: boolean;
|
||||
|
||||
/**
|
||||
* Pipelines the startup message, cleartext password message and first query
|
||||
* when set to `"password"`. This works only for cleartext password auth.
|
||||
*
|
||||
* Default: `"password"`.
|
||||
*/
|
||||
pipelineConnect: "password" | false;
|
||||
|
||||
/**
|
||||
* If `forceDisablePgSSL` is `false` and the Postgres connection parameters
|
||||
* specify TLS, you must supply the subtls TLS library to this option:
|
||||
*
|
||||
* ```
|
||||
* import { neonConfig } from '@neondatabase/serverless';
|
||||
* import * as subtls from 'subtls';
|
||||
* neonConfig.subtls = subtls;
|
||||
* ```
|
||||
*
|
||||
* Default: `undefined`.
|
||||
*/
|
||||
subtls: any;
|
||||
|
||||
/**
|
||||
* Pipeline the pg SSL request and TLS handshake when `forceDisablePgSSL` is
|
||||
* `false` and the Postgres connection parameters specify TLS. Currently
|
||||
* compatible only with Neon hosts.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
pipelineTLS: boolean;
|
||||
|
||||
/**
|
||||
* Set `rootCerts` to a string comprising one or more PEM files. These are
|
||||
* the trusted root certificates for a TLS connection to Postgres when
|
||||
* `forceDisablePgSSL` is `false` and the Postgres connection parameters
|
||||
* specify TLS.
|
||||
*
|
||||
* Default: `""`.
|
||||
*/
|
||||
rootCerts: string;
|
||||
|
||||
/**
|
||||
* Batch multiple network writes per run-loop into a single outgoing
|
||||
* WebSocket message.
|
||||
*
|
||||
* Default: `true`.
|
||||
*/
|
||||
coalesceWrites: boolean;
|
||||
|
||||
/**
|
||||
* When `disableSNI` is `true`, `forceDisablePgSSL` is `false` and the
|
||||
* Postgres connection parameters specify TLS, we send no SNI data in the
|
||||
* Postgres TLS handshake.
|
||||
*
|
||||
* On Neon, disabling SNI and including the Neon project name in the password
|
||||
* avoids CPU-intensive SCRAM authentication, but this is only relevant for
|
||||
* earlier iterations of Neon's WebSocket support.
|
||||
*
|
||||
* Default: `false`.
|
||||
*/
|
||||
disableSNI: boolean;
|
||||
}
|
||||
|
||||
export interface NeonConfig extends NeonConfigGlobalOnly, NeonConfigGlobalAndClient { }
|
||||
|
||||
import {
|
||||
Client as PgClient,
|
||||
ClientBase as PgClientBase,
|
||||
Pool as PgPool,
|
||||
PoolClient as PgPoolClient,
|
||||
} from "pg";
|
||||
|
||||
export class ClientBase extends PgClientBase {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export class Client extends PgClient {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export interface PoolClient extends PgPoolClient {
|
||||
neonConfig: NeonConfigGlobalAndClient;
|
||||
}
|
||||
|
||||
export class Pool extends PgPool {
|
||||
connect(): Promise<PoolClient>;
|
||||
connect(callback: (err: Error, client: PoolClient, done: (release?: any) => void) => void): void;
|
||||
on(event: 'error', listener: (err: Error, client: PoolClient) => void): this;
|
||||
on(event: 'connect' | 'acquire' | 'remove', listener: (client: PoolClient) => void): this;
|
||||
}
|
||||
|
||||
export const neonConfig: NeonConfig;
|
||||
|
||||
|
||||
// SQL-over-HTTP
|
||||
|
||||
import { FieldDef } from "pg";
|
||||
|
||||
export type QueryRows<ArrayMode extends boolean> =
|
||||
ArrayMode extends true ? any[][] : Record<string, any>[];
|
||||
|
||||
export interface FullQueryResults<ArrayMode extends boolean> {
|
||||
fields: FieldDef[];
|
||||
command: string;
|
||||
rowCount: number;
|
||||
rows: QueryRows<ArrayMode>;
|
||||
rowAsArray: ArrayMode;
|
||||
}
|
||||
|
||||
export interface ParameterizedQuery {
|
||||
query: string;
|
||||
params: any[];
|
||||
}
|
||||
|
||||
export interface HTTPQueryOptions<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
/**
|
||||
* When `arrayMode` is `false`, which is the default, result rows are
|
||||
* returned as objects whose keys represent column names, such as
|
||||
* `{ id: 1 }`).
|
||||
*
|
||||
* When `arrayMode` is `true`, rows are returned as arrays (and keys are not
|
||||
* provided), e.g. `[1]`.
|
||||
*/
|
||||
arrayMode?: ArrayMode;
|
||||
/**
|
||||
* When `fullResults` is `false`, which is the default, only result rows are
|
||||
* returned, e.g. `[{ id: 1 }]`).
|
||||
*
|
||||
* When `fullResults` is `true`, a result object is returned that matches
|
||||
* what's returned by node-postgres. This has a `rows` property, which is an
|
||||
* array of result rows, plus `fields`, which provides column names and
|
||||
* types, `command` and `rowCount`.
|
||||
*/
|
||||
fullResults?: FullResults; // default false
|
||||
/**
|
||||
* Any options in `fetchOptions` are merged in to the options passed to
|
||||
* `fetch`. In case of conflict with what would otherwise be passed, these
|
||||
* options take precedence.
|
||||
*/
|
||||
fetchOptions?: Record<string, any>;
|
||||
|
||||
/**
|
||||
* JWT auth token to be passed as the Bearer token in the Authorization header
|
||||
*
|
||||
* Default: `undefined`
|
||||
*/
|
||||
authToken?: string | (() => Promise<string> | string);
|
||||
}
|
||||
|
||||
export interface HTTPTransactionOptions<ArrayMode extends boolean, FullResults extends boolean> extends HTTPQueryOptions<ArrayMode, FullResults> {
|
||||
/**
|
||||
* Postgres transaction isolation level: see https://www.postgresql.org/docs/current/transaction-iso.html.
|
||||
* Note that `ReadUncommitted` actually gets you `ReadCommitted` in Postgres.
|
||||
* */
|
||||
isolationLevel?: 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable';
|
||||
/**
|
||||
* When `readOnly` is `false`, which is the default, a `READ WRITE` Postgres
|
||||
* transaction is used.
|
||||
*
|
||||
* When `readOnly` is `true`, a `READ ONLY` Postgres transaction is used.
|
||||
* */
|
||||
readOnly?: boolean;
|
||||
/**
|
||||
* When `deferrable` is `false`, which is the default, a `NOT DEFERRABLE`
|
||||
* Postgres transaction is used.
|
||||
*
|
||||
* When `deferrable` is `true` (and `isolationLevel` is `Serializable` and
|
||||
* `readOnly` is `true`), a `DEFERRABLE` Postgres transaction is used.
|
||||
* */
|
||||
deferrable?: boolean;
|
||||
}
|
||||
|
||||
export interface NeonQueryPromise<ArrayMode extends boolean, FullResults extends boolean, T = any> extends Promise<T> {
|
||||
parameterizedQuery: ParameterizedQuery;
|
||||
opts?: HTTPQueryOptions<ArrayMode, FullResults>;
|
||||
}
|
||||
|
||||
export interface NeonQueryInTransaction {
|
||||
// this is a simplified form of query, which has only a `parameterizedQuery` (no `opts` and not a `Promise`)
|
||||
parameterizedQuery: ParameterizedQuery;
|
||||
}
|
||||
|
||||
export interface NeonQueryFunctionInTransaction<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
// this is a simplified form of NeonQueryFunction (below):
|
||||
// * `opts` cannot be passed
|
||||
// * no `transaction()` method is available
|
||||
|
||||
// tagged-template function usage
|
||||
(strings: TemplateStringsArray, ...params: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
|
||||
// ordinary function usage (*no* options overrides)
|
||||
(string: string, params?: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
}
|
||||
|
||||
export interface NeonQueryFunction<ArrayMode extends boolean, FullResults extends boolean> {
|
||||
// tagged-template function usage
|
||||
(strings: TemplateStringsArray, ...params: any[]):
|
||||
NeonQueryPromise<ArrayMode, FullResults, FullResults extends true ? FullQueryResults<ArrayMode> : QueryRows<ArrayMode>>;
|
||||
|
||||
// ordinary function usage, with options overrides
|
||||
<ArrayModeOverride extends boolean = ArrayMode, FullResultsOverride extends boolean = FullResults>(
|
||||
string: string,
|
||||
params?: any[],
|
||||
opts?: HTTPQueryOptions<ArrayModeOverride, FullResultsOverride>
|
||||
): NeonQueryPromise<
|
||||
ArrayModeOverride,
|
||||
FullResultsOverride,
|
||||
FullResultsOverride extends true ? FullQueryResults<ArrayModeOverride> : QueryRows<ArrayModeOverride>
|
||||
>;
|
||||
|
||||
/**
|
||||
* The `transaction()` function allows multiple queries to be submitted (over
|
||||
* HTTP) as a single, non-interactive Postgres transaction.
|
||||
*
|
||||
* For example:
|
||||
* ```
|
||||
* import { neon } from "@neondatabase/serverless";
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
*
|
||||
* const results = await sql.transaction([
|
||||
* sql`SELECT 1 AS num`,
|
||||
* sql`SELECT 'a' AS str`,
|
||||
* ]);
|
||||
* // -> [[{ num: 1 }], [{ str: "a" }]]
|
||||
*
|
||||
* // or equivalently:
|
||||
* const results = await sql.transaction(txn => [
|
||||
* txn`SELECT 1 AS num`,
|
||||
* txn`SELECT 'a' AS str`,
|
||||
* ]);
|
||||
* // -> [[{ num: 1 }], [{ str: "a" }]]
|
||||
* ```
|
||||
* @param queriesOrFn Either an array of queries, or a (non-`async`) function
|
||||
* that receives a query function and returns an array of queries.
|
||||
* @param opts The same options that may be set on individual queries in a
|
||||
* non-transaction setting -- that is, `arrayMode` `fullResults` and
|
||||
* `fetchOptions` -- plus the transaction options `isolationLevel`,
|
||||
* `readOnly` and `deferrable`. Note that none of these options can be set on
|
||||
* individual queries within a transaction.
|
||||
* @returns An array of results. The structure of each result object depends
|
||||
* on the `arrayMode` and `fullResults` options.
|
||||
*/
|
||||
transaction: <ArrayModeOverride extends boolean = ArrayMode, FullResultsOverride extends boolean = FullResults>(
|
||||
queriesOrFn: NeonQueryPromise<ArrayMode, FullResults>[] | // not ArrayModeOverride or FullResultsOverride: clamp these values to the current ones
|
||||
((sql: NeonQueryFunctionInTransaction<ArrayModeOverride, FullResultsOverride>) => NeonQueryInTransaction[]),
|
||||
opts?: HTTPTransactionOptions<ArrayModeOverride, FullResultsOverride>
|
||||
) => Promise<FullResultsOverride extends true ? FullQueryResults<ArrayModeOverride>[] : QueryRows<ArrayModeOverride>[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function returns an async tagged-template function that runs a single
|
||||
* SQL query (no session or transactions) with low latency over https. Support
|
||||
* for multiple queries as a non-interactive transaction is provided by
|
||||
* the `transaction` property of the query function.
|
||||
*
|
||||
* By default, the query function returns database rows directly. Types should
|
||||
* match those returned by this driver (i.e. Pool or Client) over WebSockets.
|
||||
*
|
||||
* The returned function can also be called directly (i.e. not as a template
|
||||
* function). In that case, pass it a query string with embedded `$1`, `$2`
|
||||
* (etc.), followed by an array of query parameters, followed (optionally) by
|
||||
* any of the same options you can pass to this function.
|
||||
*
|
||||
* Some examples:
|
||||
* ```
|
||||
* import { neon } from "@neondatabase/serverless";
|
||||
* const h = "hello", w = "world";
|
||||
*
|
||||
* // example 1: default options, tagged-template usage
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
* const rows = await sql`SELECT ${h} || ' ' || ${w} AS greeting`;
|
||||
* // -> [ { greeting: "hello world" } ]
|
||||
*
|
||||
* // example 2: `arrayMode` and `fullResults` options, ordinary function usage
|
||||
* const options = { arrayMode: true, fullResults: true };
|
||||
* const sql = neon("postgres://user:pass@host/db", options);
|
||||
* const rows = await sql("SELECT $1 || ' ' || $2 AS greeting", [h, w]);
|
||||
* // -> {
|
||||
* // command: "SELECT",
|
||||
* // fields: [ { name: "greeting", dataTypeID: 25 } ],
|
||||
* // rowAsArray: true,
|
||||
* // rowCount: 1,
|
||||
* // rows: [ [ "hello world" ] ]
|
||||
* // }
|
||||
*
|
||||
* // example 3: `fetchOptions` option, ordinary function usage
|
||||
* const sql = neon("postgres://user:pass@host/db");
|
||||
* const rows = await sql(
|
||||
* "SELECT $1 || ' ' || $2 AS greeting", [h, w],
|
||||
* { fetchOptions: { priority: "high" } }
|
||||
* );
|
||||
* // -> [ { greeting: "hello world" } ]
|
||||
* ```
|
||||
*
|
||||
* @param connectionString this has the format `postgres://user:pass@host/db`
|
||||
* @param options pass `arrayMode: true` to receive results as an array of
|
||||
* arrays, instead of the default array of objects; pass `fullResults: true`
|
||||
* to receive a complete result object similar to one returned by node-postgres
|
||||
* (with properties `rows`, `fields`, `command`, `rowCount`, `rowAsArray`);
|
||||
* pass as `fetchOptions` an object which will be merged into the options
|
||||
* passed to `fetch`.
|
||||
*/
|
||||
export function neon<ArrayMode extends boolean = false, FullResults extends boolean = false>(
|
||||
connectionString: string,
|
||||
options?: HTTPTransactionOptions<ArrayMode, FullResults>,
|
||||
): NeonQueryFunction<ArrayMode, FullResults>;
|
||||
|
||||
export class NeonDbError extends Error {
|
||||
name: 'NeonDbError';
|
||||
|
||||
severity: string | undefined;
|
||||
code: string | undefined;
|
||||
detail: string | undefined;
|
||||
hint: string | undefined;
|
||||
position: string | undefined;
|
||||
internalPosition: string | undefined;
|
||||
internalQuery: string | undefined;
|
||||
where: string | undefined;
|
||||
schema: string | undefined;
|
||||
table: string | undefined;
|
||||
column: string | undefined;
|
||||
dataType: string | undefined;
|
||||
constraint: string | undefined;
|
||||
file: string | undefined;
|
||||
line: string | undefined;
|
||||
routine: string | undefined;
|
||||
|
||||
sourceError: Error | undefined;
|
||||
}
|
||||
1642
node_modules/@neondatabase/serverless/index.js
generated
vendored
Normal file
1642
node_modules/@neondatabase/serverless/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1643
node_modules/@neondatabase/serverless/index.mjs
generated
vendored
Normal file
1643
node_modules/@neondatabase/serverless/index.mjs
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
35
node_modules/@neondatabase/serverless/package.json
generated
vendored
Normal file
35
node_modules/@neondatabase/serverless/package.json
generated
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@neondatabase/serverless",
|
||||
"version": "0.10.1",
|
||||
"author": "Neon",
|
||||
"description": "node-postgres for serverless environments from neon.tech",
|
||||
"exports": {
|
||||
"require": "./index.js",
|
||||
"import": "./index.mjs"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://neon.tech",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/neondatabase/serverless"
|
||||
},
|
||||
"keywords": [
|
||||
"Neon",
|
||||
"serverless",
|
||||
"Postgres",
|
||||
"PostgreSQL",
|
||||
"pg",
|
||||
"database",
|
||||
"SQL",
|
||||
"edge",
|
||||
"workers",
|
||||
"Cloudflare",
|
||||
"Vercel",
|
||||
"RDBMS",
|
||||
"WebSocket",
|
||||
"https"
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/pg": "8.11.6"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user