Showing preview only (843K chars total). Download the full file or copy to clipboard to get everything.
Repository: brianc/node-postgres
Branch: master
Commit: c78b302666d5
Files: 353
Total size: 759.8 KB
Directory structure:
gitextract_s6gb5la9/
├── .devcontainer/
│ ├── Dockerfile
│ ├── devcontainer.json
│ └── docker-compose.yml
├── .eslintignore
├── .eslintrc
├── .gitattributes
├── .github/
│ ├── CODEOWNERS
│ ├── FUNDING.yml
│ ├── dependabot.yaml
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── .yarnrc
├── CHANGELOG.md
├── LICENSE
├── LOCAL_DEV.md
├── README.md
├── SPONSORS.md
├── docs/
│ ├── .gitignore
│ ├── README.md
│ ├── components/
│ │ ├── alert.tsx
│ │ ├── info.tsx
│ │ └── logo.tsx
│ ├── next.config.js
│ ├── package.json
│ ├── pages/
│ │ ├── _app.js
│ │ ├── _meta.js
│ │ ├── announcements.mdx
│ │ ├── apis/
│ │ │ ├── _meta.js
│ │ │ ├── client.mdx
│ │ │ ├── cursor.mdx
│ │ │ ├── pool.mdx
│ │ │ ├── result.mdx
│ │ │ ├── types.mdx
│ │ │ └── utilities.mdx
│ │ ├── features/
│ │ │ ├── _meta.js
│ │ │ ├── callbacks.mdx
│ │ │ ├── connecting.mdx
│ │ │ ├── esm.mdx
│ │ │ ├── native.mdx
│ │ │ ├── pooling.mdx
│ │ │ ├── queries.mdx
│ │ │ ├── ssl.mdx
│ │ │ ├── transactions.mdx
│ │ │ └── types.mdx
│ │ ├── guides/
│ │ │ ├── _meta.js
│ │ │ ├── async-express.md
│ │ │ ├── pool-sizing.md
│ │ │ ├── project-structure.md
│ │ │ └── upgrading.md
│ │ └── index.mdx
│ └── theme.config.js
├── lerna.json
├── package.json
├── packages/
│ ├── pg/
│ │ ├── Makefile
│ │ ├── README.md
│ │ ├── bench.js
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── lib/
│ │ │ ├── client.js
│ │ │ ├── connection-parameters.js
│ │ │ ├── connection.js
│ │ │ ├── crypto/
│ │ │ │ ├── cert-signatures.js
│ │ │ │ ├── sasl.js
│ │ │ │ ├── utils-legacy.js
│ │ │ │ ├── utils-webcrypto.js
│ │ │ │ └── utils.js
│ │ │ ├── defaults.js
│ │ │ ├── index.js
│ │ │ ├── native/
│ │ │ │ ├── client.js
│ │ │ │ ├── index.js
│ │ │ │ └── query.js
│ │ │ ├── query.js
│ │ │ ├── result.js
│ │ │ ├── stream.js
│ │ │ ├── type-overrides.js
│ │ │ └── utils.js
│ │ ├── package.json
│ │ ├── script/
│ │ │ └── dump-db-types.js
│ │ └── test/
│ │ ├── buffer-list.js
│ │ ├── cloudflare/
│ │ │ └── vitest-cf.test.ts
│ │ ├── integration/
│ │ │ ├── client/
│ │ │ │ ├── api-tests.js
│ │ │ │ ├── appname-tests.js
│ │ │ │ ├── array-tests.js
│ │ │ │ ├── async-stack-trace-tests.js
│ │ │ │ ├── big-simple-query-tests.js
│ │ │ │ ├── configuration-tests.js
│ │ │ │ ├── connection-parameter-tests.js
│ │ │ │ ├── connection-timeout-tests.js
│ │ │ │ ├── custom-types-tests.js
│ │ │ │ ├── empty-query-tests.js
│ │ │ │ ├── error-handling-tests.js
│ │ │ │ ├── field-name-escape-tests.js
│ │ │ │ ├── huge-numeric-tests.js
│ │ │ │ ├── idle_in_transaction_session_timeout-tests.js
│ │ │ │ ├── json-type-parsing-tests.js
│ │ │ │ ├── multiple-results-tests.js
│ │ │ │ ├── network-partition-tests.js
│ │ │ │ ├── no-data-tests.js
│ │ │ │ ├── no-row-result-tests.js
│ │ │ │ ├── notice-tests.js
│ │ │ │ ├── parse-int-8-tests.js
│ │ │ │ ├── prepared-statement-tests.js
│ │ │ │ ├── promise-api-tests.js
│ │ │ │ ├── query-as-promise-tests.js
│ │ │ │ ├── query-column-names-tests.js
│ │ │ │ ├── query-error-handling-prepared-statement-tests.js
│ │ │ │ ├── query-error-handling-tests.js
│ │ │ │ ├── quick-disconnect-tests.js
│ │ │ │ ├── result-metadata-tests.js
│ │ │ │ ├── results-as-array-tests.js
│ │ │ │ ├── row-description-on-results-tests.js
│ │ │ │ ├── sasl-scram-tests.js
│ │ │ │ ├── simple-query-tests.js
│ │ │ │ ├── ssl-tests.js
│ │ │ │ ├── statement_timeout-tests.js
│ │ │ │ ├── test-helper.js
│ │ │ │ ├── timezone-tests.js
│ │ │ │ ├── transaction-tests.js
│ │ │ │ ├── type-coercion-tests.js
│ │ │ │ └── type-parser-override-tests.js
│ │ │ ├── connection-pool/
│ │ │ │ ├── connection-pool-size-tests.js
│ │ │ │ ├── error-tests.js
│ │ │ │ ├── idle-timeout-tests.js
│ │ │ │ ├── native-instance-tests.js
│ │ │ │ ├── test-helper.js
│ │ │ │ ├── tls-tests.js
│ │ │ │ └── yield-support-tests.js
│ │ │ ├── domain-tests.js
│ │ │ ├── gh-issues/
│ │ │ │ ├── 1105-tests.js
│ │ │ │ ├── 130-tests.js
│ │ │ │ ├── 131-tests.js
│ │ │ │ ├── 1382-tests.js
│ │ │ │ ├── 1542-tests.js
│ │ │ │ ├── 1854-tests.js
│ │ │ │ ├── 199-tests.js
│ │ │ │ ├── 1992-tests.js
│ │ │ │ ├── 2056-tests.js
│ │ │ │ ├── 2064-tests.js
│ │ │ │ ├── 2079-tests.js
│ │ │ │ ├── 2085-tests.js
│ │ │ │ ├── 2108-tests.js
│ │ │ │ ├── 2303-tests.js
│ │ │ │ ├── 2307-tests.js
│ │ │ │ ├── 2416-tests.js
│ │ │ │ ├── 2556-tests.js
│ │ │ │ ├── 2627-tests.js
│ │ │ │ ├── 2716-tests.js
│ │ │ │ ├── 2862-tests.js
│ │ │ │ ├── 3062-tests.js
│ │ │ │ ├── 3174-tests.js
│ │ │ │ ├── 3487-tests.js
│ │ │ │ ├── 507-tests.js
│ │ │ │ ├── 600-tests.js
│ │ │ │ ├── 675-tests.js
│ │ │ │ ├── 699-tests.js
│ │ │ │ ├── 787-tests.js
│ │ │ │ ├── 882-tests.js
│ │ │ │ └── 981-tests.js
│ │ │ └── test-helper.js
│ │ ├── native/
│ │ │ ├── callback-api-tests.js
│ │ │ ├── evented-api-tests.js
│ │ │ ├── native-connection-string-tests.js
│ │ │ ├── native-vs-js-error-tests.js
│ │ │ └── stress-tests.js
│ │ ├── suite.js
│ │ ├── test-buffers.js
│ │ ├── test-helper.js
│ │ ├── tls/
│ │ │ ├── GNUmakefile
│ │ │ ├── test-client-ca.crt
│ │ │ ├── test-client-ca.key
│ │ │ ├── test-client.crt
│ │ │ ├── test-client.key
│ │ │ ├── test-server-ca.crt
│ │ │ ├── test-server-ca.key
│ │ │ ├── test-server.crt
│ │ │ └── test-server.key
│ │ ├── unit/
│ │ │ ├── client/
│ │ │ │ ├── cleartext-password-tests.js
│ │ │ │ ├── configuration-tests.js
│ │ │ │ ├── early-disconnect-tests.js
│ │ │ │ ├── escape-tests.js
│ │ │ │ ├── md5-password-tests.js
│ │ │ │ ├── notification-tests.js
│ │ │ │ ├── password-callback-tests.js
│ │ │ │ ├── pgpass.file
│ │ │ │ ├── prepared-statement-tests.js
│ │ │ │ ├── query-queue-tests.js
│ │ │ │ ├── query-timeout-tests.js
│ │ │ │ ├── result-metadata-tests.js
│ │ │ │ ├── sasl-scram-tests.js
│ │ │ │ ├── set-keepalives-tests.js
│ │ │ │ ├── simple-query-tests.js
│ │ │ │ ├── stream-and-query-error-interaction-tests.js
│ │ │ │ ├── test-helper.js
│ │ │ │ └── throw-in-type-parser-tests.js
│ │ │ ├── connection/
│ │ │ │ ├── error-tests.js
│ │ │ │ ├── startup-tests.js
│ │ │ │ └── test-helper.js
│ │ │ ├── connection-parameters/
│ │ │ │ ├── creation-tests.js
│ │ │ │ └── environment-variable-tests.js
│ │ │ ├── connection-pool/
│ │ │ │ └── configuration-tests.js
│ │ │ ├── test-helper.js
│ │ │ └── utils-tests.js
│ │ ├── vitest.config.mts
│ │ └── wrangler.jsonc
│ ├── pg-bundler-test/
│ │ ├── esbuild-cloudflare.config.mjs
│ │ ├── esbuild-empty.config.mjs
│ │ ├── package.json
│ │ ├── rollup-cloudflare.config.mjs
│ │ ├── rollup-empty.config.mjs
│ │ ├── src/
│ │ │ └── index.mjs
│ │ ├── vite-cloudflare.config.mjs
│ │ ├── vite-empty.config.mjs
│ │ ├── webpack-cloudflare.config.mjs
│ │ └── webpack-empty.config.mjs
│ ├── pg-cloudflare/
│ │ ├── README.md
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── empty.ts
│ │ │ ├── index.ts
│ │ │ └── types.d.ts
│ │ └── tsconfig.json
│ ├── pg-connection-string/
│ │ ├── .coveralls.yml
│ │ ├── .gitignore
│ │ ├── .mocharc.json
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── index.d.ts
│ │ ├── index.js
│ │ ├── package.json
│ │ ├── test/
│ │ │ ├── clientConfig.ts
│ │ │ ├── example.ca
│ │ │ ├── example.cert
│ │ │ ├── example.key
│ │ │ └── parse.ts
│ │ └── tsconfig.json
│ ├── pg-cursor/
│ │ ├── README.md
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── index.js
│ │ ├── package.json
│ │ └── test/
│ │ ├── close.js
│ │ ├── error-handling.js
│ │ ├── index.js
│ │ ├── mocha.opts
│ │ ├── no-data-handling.js
│ │ ├── pool.js
│ │ ├── promises.js
│ │ ├── query-config.js
│ │ └── transactions.js
│ ├── pg-esm-test/
│ │ ├── README.md
│ │ ├── common-js-imports.test.cjs
│ │ ├── package.json
│ │ ├── pg-cloudflare.test.js
│ │ ├── pg-connection-string.test.js
│ │ ├── pg-cursor.test.js
│ │ ├── pg-native.test.js
│ │ ├── pg-pool.test.js
│ │ ├── pg-protocol.test.js
│ │ ├── pg-query-stream.test.js
│ │ └── pg.test.js
│ ├── pg-native/
│ │ ├── README.md
│ │ ├── bench/
│ │ │ ├── index.js
│ │ │ └── leaks.js
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── index.js
│ │ ├── lib/
│ │ │ ├── build-result.js
│ │ │ └── copy-stream.js
│ │ ├── package.json
│ │ └── test/
│ │ ├── array-mode.js
│ │ ├── async-workflow.js
│ │ ├── cancel.js
│ │ ├── connection-errors.js
│ │ ├── connection.js
│ │ ├── copy-from.js
│ │ ├── copy-to.js
│ │ ├── custom-types.js
│ │ ├── domains.js
│ │ ├── empty-query.js
│ │ ├── huge-query.js
│ │ ├── index.js
│ │ ├── load.js
│ │ ├── many-connections.js
│ │ ├── many-errors.js
│ │ ├── mocha.opts
│ │ ├── multiple-queries.js
│ │ ├── multiple-statement-results.js
│ │ ├── notify.js
│ │ ├── prepare.js
│ │ ├── query-async.js
│ │ ├── query-sync.js
│ │ └── version.js
│ ├── pg-pool/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── esm/
│ │ │ └── index.mjs
│ │ ├── index.js
│ │ ├── package.json
│ │ └── test/
│ │ ├── connection-strings.js
│ │ ├── connection-timeout.js
│ │ ├── ending.js
│ │ ├── error-handling.js
│ │ ├── events.js
│ │ ├── idle-timeout-exit.js
│ │ ├── idle-timeout.js
│ │ ├── index.js
│ │ ├── lifecycle-hooks.js
│ │ ├── lifetime-timeout.js
│ │ ├── logging.js
│ │ ├── max-uses.js
│ │ ├── releasing-clients.js
│ │ ├── setup.js
│ │ ├── sizing.js
│ │ ├── submittable.js
│ │ └── verify.js
│ ├── pg-protocol/
│ │ ├── README.md
│ │ ├── esm/
│ │ │ └── index.js
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── b.ts
│ │ │ ├── buffer-reader.ts
│ │ │ ├── buffer-writer.ts
│ │ │ ├── inbound-parser.test.ts
│ │ │ ├── index.ts
│ │ │ ├── messages.ts
│ │ │ ├── outbound-serializer.test.ts
│ │ │ ├── parser.ts
│ │ │ ├── serializer.ts
│ │ │ ├── testing/
│ │ │ │ ├── buffer-list.ts
│ │ │ │ └── test-buffers.ts
│ │ │ └── types/
│ │ │ └── chunky.d.ts
│ │ └── tsconfig.json
│ └── pg-query-stream/
│ ├── LICENSE
│ ├── README.md
│ ├── esm/
│ │ └── index.mjs
│ ├── package.json
│ ├── src/
│ │ └── index.ts
│ ├── test/
│ │ ├── async-iterator.ts
│ │ ├── client-options.ts
│ │ ├── close.ts
│ │ ├── concat.ts
│ │ ├── config.ts
│ │ ├── empty-query.ts
│ │ ├── error.ts
│ │ ├── fast-reader.ts
│ │ ├── helper.ts
│ │ ├── instant.ts
│ │ ├── issue-3.ts
│ │ ├── passing-options.ts
│ │ ├── pauses.ts
│ │ ├── pool.ts
│ │ ├── slow-reader.ts
│ │ ├── stream-tester-timestamp.ts
│ │ └── stream-tester.ts
│ └── tsconfig.json
├── tea.yaml
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .devcontainer/Dockerfile
================================================
#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------
FROM node:22
# Avoid warnings by switching to noninteractive
ENV DEBIAN_FRONTEND=noninteractive
# The node image includes a non-root user with sudo access. Use the
# "remoteUser" property in devcontainer.json to use it. On Linux, update
# these values to ensure the container user's UID/GID matches your local values.
# See https://aka.ms/vscode-remote/containers/non-root-user for details.
ARG USERNAME=node
ARG USER_UID=1000
ARG USER_GID=$USER_UID
RUN echo "deb http://archive.debian.org/debian stretch main" > /etc/apt/sources.list
# Configure apt and install packages
RUN apt-get update \
&& apt-get -y install --no-install-recommends dialog 2>&1 \
#
# Verify git and needed tools are installed
&& apt-get -y install git iproute2 procps \
#
# Remove outdated yarn from /opt and install via package
# so it can be easily updated via apt-get upgrade yarn
&& rm -rf /opt/yarn-* \
&& rm -f /usr/local/bin/yarn \
&& rm -f /usr/local/bin/yarnpkg \
&& apt-get install -y curl apt-transport-https lsb-release \
&& curl -sS https://dl.yarnpkg.com/$(lsb_release -is | tr '[:upper:]' '[:lower:]')/pubkey.gpg | apt-key add - 2>/dev/null \
&& echo "deb https://dl.yarnpkg.com/$(lsb_release -is | tr '[:upper:]' '[:lower:]')/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
&& apt-get update \
&& apt-get -y install --no-install-recommends yarn tmux locales postgresql \
&& apt-get install libpq-dev python3 g++ make \
#
# Install eslint globally
&& npm install -g eslint \
#
# [Optional] Update a non-root user to UID/GID if needed.
&& if [ "$USER_GID" != "1000" ] || [ "$USER_UID" != "1000" ]; then \
groupmod --gid $USER_GID $USERNAME \
&& usermod --uid $USER_UID --gid $USER_GID $USERNAME \
&& chown -R $USER_UID:$USER_GID /home/$USERNAME; \
fi \
# [Optional] Add add sudo support for non-root user
&& apt-get install -y sudo \
&& echo node ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
&& chmod 0440 /etc/sudoers.d/$USERNAME \
# Clean up
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
RUN curl https://raw.githubusercontent.com/brianc/dotfiles/master/.tmux.conf > ~/.tmux.conf
# install nvm
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash
# set up a nicer prompt
RUN git clone https://github.com/magicmonty/bash-git-prompt.git ~/.bash-git-prompt --depth=1
RUN echo "source $HOME/.bash-git-prompt/gitprompt.sh" >> ~/.bashrc
# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
# Switch back to dialog for any ad-hoc use of apt-get
ENV DEBIAN_FRONTEND=dialog
================================================
FILE: .devcontainer/devcontainer.json
================================================
// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.
{
"name": "Node.js 20 & Postgres",
"dockerComposeFile": "docker-compose.yml",
"service": "web",
"workspaceFolder": "/workspace",
// Add the IDs of extensions you want installed when the container is created in the array below.
"customizations":{
"vscode": {
"extensions": ["dbaeumer.vscode-eslint"],
"settings": {
"terminal.integrated.shell.linux": "/bin/bash"
}
}
}
}
================================================
FILE: .devcontainer/docker-compose.yml
================================================
#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------
version: '3.9'
services:
web:
# Uncomment the next line to use a non-root user for all processes. You can also
# simply use the "remoteUser" property in devcontainer.json if you just want VS Code
# and its sub-processes (terminals, tasks, debugging) to execute as the user. On Linux,
# you may need to update USER_UID and USER_GID in .devcontainer/Dockerfile to match your
# user if not 1000. See https://aka.ms/vscode-remote/containers/non-root for details.
# user: node
build:
context: .
dockerfile: Dockerfile
volumes:
- ..:/workspace:cached
environment:
PGPASSWORD: pass
PGUSER: user
PGDATABASE: data
PGHOST: db
# set this to true in the development environment until I can get SSL setup on the
# docker postgres instance
PGTESTNOSSL: 'true'
# Overrides default command so things don't shut down after the process ends.
command: sleep infinity
depends_on:
- db
links:
- db:db
db:
image: postgres:14
restart: unless-stopped
ports:
- 5432:5432
command: postgres -c password_encryption=md5
environment:
POSTGRES_HOST_AUTH_METHOD: trust
POSTGRES_INITDB_ARGS: "--auth-local=md5"
POSTGRES_PASSWORD: pass
POSTGRES_USER: user
POSTGRES_DB: data
================================================
FILE: .eslintignore
================================================
/packages/*/dist/
================================================
FILE: .eslintrc
================================================
{
"plugins": ["@typescript-eslint", "prettier"],
"parser": "@typescript-eslint/parser",
"extends": ["eslint:recommended", "plugin:prettier/recommended", "prettier"],
"ignorePatterns": ["node_modules", "coverage", "packages/pg-protocol/dist/**/*", "packages/pg-query-stream/dist/**/*"],
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"env": {
"node": true,
"es6": true,
"mocha": true
},
"rules": {
"@typescript-eslint/no-unused-vars": ["error", {
"args": "none",
"varsIgnorePattern": "^_$"
}],
"no-unused-vars": ["error", {
"args": "none",
"varsIgnorePattern": "^_$"
}],
"no-var": "error",
"prefer-const": "error"
},
"overrides": [
{
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
"rules": {
"no-undef": "off"
}
}
]
}
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
================================================
FILE: .github/CODEOWNERS
================================================
/packages/pg-connection-string @hjr3
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: [brianc]
================================================
FILE: .github/dependabot.yaml
================================================
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "monthly"
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on: [push, pull_request]
permissions:
contents: read
jobs:
lint:
timeout-minutes: 5
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: 18
cache: yarn
- run: yarn install --frozen-lockfile
- run: yarn lint
build:
timeout-minutes: 15
needs: lint
services:
postgres:
image: ghcr.io/railwayapp-templates/postgres-ssl
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_HOST_AUTH_METHOD: 'md5'
POSTGRES_DB: ci_db_test
ports:
- 5432:5432
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
strategy:
fail-fast: false
matrix:
node:
- '16'
- '18'
- '20'
- '22'
- '24'
- '25'
os:
- ubuntu-latest
name: Node.js ${{ matrix.node }}
runs-on: ubuntu-latest
env:
PGUSER: postgres
PGPASSWORD: postgres
PGHOST: localhost
PGDATABASE: ci_db_test
PGTESTNOSSL: 'true'
SCRAM_TEST_PGUSER: scram_test
SCRAM_TEST_PGPASSWORD: test4scram
steps:
- name: Show OS
run: |
uname -a
- run: |
psql \
-c "SET password_encryption = 'scram-sha-256'" \
-c "CREATE ROLE scram_test LOGIN PASSWORD 'test4scram'"
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: yarn
- run: yarn install --frozen-lockfile
- run: yarn test
================================================
FILE: .gitignore
================================================
*~
build/
.lock-wscript
*.log
node_modules/
package-lock.json
*.swp
dist
.DS_Store
/.eslintcache
.vscode/
manually-test-on-heroku.js
================================================
FILE: .yarnrc
================================================
--install.ignore-engines true
================================================
FILE: CHANGELOG.md
================================================
All major and minor releases are briefly explained below.
For richer information consult the commit log on github with referenced pull requests.
We do not include break-fix version release in this file.
## pg@8.20.0
- Add [onConnect](https://github.com/brianc/node-postgres/pull/3620) callback to pg.Pool constructor options allowing for async initialization of newly created & connected pooled clients.
## pg@8.19.0
- [Deprecate interal query queue](https://github.com/brianc/node-postgres/pull/3603).
- Pass connection parameters [to password callback](https://github.com/brianc/node-postgres/pull/3602).
## pg@8.18.0
- [Return the client instance](https://github.com/brianc/node-postgres/pull/3564) as the result of calling `connect` (previously it was `void`).
## pg@8.17.0
- Throw correct error if database URL parsing [fails](https://github.com/brianc/node-postgres/issues/3513).
## 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.
## pg@8.14.0
- Add support from SCRAM-SAH-256-PLUS i.e. [channel binding](https://github.com/brianc/node-postgres/pull/3356).
## pg@8.13.0
- Add ability to specify query timeout on [per-query basis](https://github.com/brianc/node-postgres/pull/3074).
## pg@8.12.0
- Add `queryMode` config option to [force use of the extended query protocol](https://github.com/brianc/node-postgres/pull/3214) on queries without any parameters.
## pg-pool@8.10.0
- Emit `release` event when client is returned to [the pool](https://github.com/brianc/node-postgres/pull/2845).
## pg@8.9.0
- Add support for [stream factory](https://github.com/brianc/node-postgres/pull/2898).
- [Better errors](https://github.com/brianc/node-postgres/pull/2901) for SASL authentication.
- [Use native crypto module](https://github.com/brianc/node-postgres/pull/2815) for SASL authentication.
## pg@8.8.0
- Bump minimum required version of [native bindings](https://github.com/brianc/node-postgres/pull/2787).
- Catch previously uncatchable errors thrown in [`pool.query`](https://github.com/brianc/node-postgres/pull/2569).
- Prevent the pool from blocking the event loop if all clients are [idle](https://github.com/brianc/node-postgres/pull/2721) (and `allowExitOnIdle` is enabled).
- Support `lock_timeout` in [client config](https://github.com/brianc/node-postgres/pull/2779).
- Fix errors thrown in callbacks from [interfering with cleanup](https://github.com/brianc/node-postgres/pull/2753).
### pg-pool@3.5.0
- Add connection [lifetime limit](https://github.com/brianc/node-postgres/pull/2698) config option.
### pg@8.7.0
- Add optional config to [pool](https://github.com/brianc/node-postgres/pull/2568) to allow process to exit if pool is idle.
### pg-cursor@2.7.0
- Convert to [es6 class](https://github.com/brianc/node-postgres/pull/2553)
- Add support for promises [to cursor methods](https://github.com/brianc/node-postgres/pull/2554)
### pg@8.6.0
- Better [SASL](https://github.com/brianc/node-postgres/pull/2436) error messages & more validation on bad configuration.
- Export [DatabaseError](https://github.com/brianc/node-postgres/pull/2445).
- Add [ParameterDescription](https://github.com/brianc/node-postgres/pull/2464) support to protocol parsing.
- Fix typescript [typedefs](https://github.com/brianc/node-postgres/pull/2490) with `--isolatedModules`.
### pg-query-stream@4.0.0
- Library has been [converted](https://github.com/brianc/node-postgres/pull/2376) to Typescript. The behavior is identical, but there could be subtle breaking changes due to class names changing or other small inconsistencies introduced by the conversion.
### pg@8.5.0
- Fix bug forwarding [ssl key](https://github.com/brianc/node-postgres/pull/2394).
- Convert pg-query-stream internals to [typescript](https://github.com/brianc/node-postgres/pull/2376).
- Performance [improvements](https://github.com/brianc/node-postgres/pull/2286).
### pg@8.4.0
- Switch to optional peer dependencies & remove [semver](https://github.com/brianc/node-postgres/commit/a02dfac5ad2e2abf0dc3a9817f953938acdc19b1) package which has been a small thorn in the side of a few users.
- Export `DatabaseError` from [pg-protocol](https://github.com/brianc/node-postgres/commit/58258430d52ee446721cc3e6611e26f8bcaa67f5).
- Add support for `sslmode` in the [connection string](https://github.com/brianc/node-postgres/commit/6be3b9022f83efc721596cc41165afaa07bfceb0).
### pg@8.3.0
- Support passing a [string of command line options flags](https://github.com/brianc/node-postgres/pull/2216) via the `{ options: string }` field on client/pool config.
### pg@8.2.0
- Switch internal protocol parser & serializer to [pg-protocol](https://github.com/brianc/node-postgres/tree/master/packages/pg-protocol). The change is backwards compatible but results in a significant performance improvement across the board, with some queries as much as 50% faster. This is the first work to land in an on-going performance improvement initiative I'm working on. Stay tuned as things are set to get much faster still! :rocket:
### pg-cursor@2.2.0
- Switch internal protocol parser & serializer to [pg-protocol](https://github.com/brianc/node-postgres/tree/master/packages/pg-protocol). The change is backwards compatible but results in a significant performance improvement across the board, with some queries as much as 50% faster.
### pg-query-stream@3.1.0
- Switch internal protocol parser & serializer to [pg-protocol](https://github.com/brianc/node-postgres/tree/master/packages/pg-protocol). The change is backwards compatible but results in a significant performance improvement across the board, with some queries as much as 50% faster.
### pg@8.1.0
- Switch to using [monorepo](https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string) version of `pg-connection-string`. This includes better support for SSL argument parsing from connection strings and ensures continuity of support.
- Add `&ssl=no-verify` option to connection string and `PGSSLMODE=no-verify` environment variable support for the pure JS driver. This is equivalent of passing `{ ssl: { rejectUnauthorized: false } }` to the client/pool constructor. The advantage of having support in connection strings and environment variables is it can be "externally" configured via environment variables and CLI arguments much more easily, and should remove the need to directly edit any application code for [the SSL default changes in 8.0](https://node-postgres.com/announcements#2020-02-25). This should make using `pg@8.x` significantly less difficult on environments like Heroku for example.
### pg-pool@3.2.0
- Same changes to `pg` impact `pg-pool` as they both use the same connection parameter and connection string parsing code for configuring SSL.
### pg-pool@3.1.0
- Add [maxUses](https://github.com/brianc/node-postgres/pull/2157) config option.
### pg@8.0.0
#### note: for detailed release notes please [check here](https://node-postgres.com/announcements#2020-02-25)
- Remove versions of node older than `6 lts` from the test matrix. `pg>=8.0` may still work on older versions but it is no longer officially supported.
- Change default behavior when not specifying `rejectUnauthorized` with the SSL connection parameters. Previously we defaulted to `rejectUnauthorized: false` when it was not specifically included. We now default to `rejectUnauthorized: true.` Manually specify `{ ssl: { rejectUnauthorized: false } }` for old behavior.
- Change [default database](https://github.com/brianc/node-postgres/pull/1679) when not specified to use the `user` config option if available. Previously `process.env.USER` was used.
- Change `pg.Pool` and `pg.Query` to [be](https://github.com/brianc/node-postgres/pull/2126) an [es6 class](https://github.com/brianc/node-postgres/pull/2063).
- Make `pg.native` non enumerable.
- `notice` messages are [no longer instances](https://github.com/brianc/node-postgres/pull/2090) of `Error`.
- Passwords no longer [show up](https://github.com/brianc/node-postgres/pull/2070) when instances of clients or pools are logged.
### pg@7.18.0
- This will likely be the last minor release before pg@8.0.
- This version contains a few bug fixes and adds a deprecation warning for [a pending change in 8.0](https://github.com/brianc/node-postgres/issues/2009#issuecomment-579371651) which will flip the default behavior over SSL from `rejectUnauthorized` from `false` to `true` making things more secure in the general use case.
### pg-query-stream@3.0.0
- [Rewrote stream internals](https://github.com/brianc/node-postgres/pull/2051) to better conform to node stream semantics. This should make pg-query-stream much better at respecting [highWaterMark](https://nodejs.org/api/stream.html#stream_new_stream_readable_options) and getting rid of some edge case bugs when using pg-query-stream as an async iterator. Due to the size and nature of this change (effectively a full re-write) it's safest to bump the semver major here, though almost all tests remain untouched and still passing, which brings us to a breaking change to the API....
- Changed `stream.close` to `stream.destroy` which is the [official](https://nodejs.org/api/stream.html#stream_readable_destroy_error) way to terminate a readable stream. This is a **breaking change** if you rely on the `stream.close` method on pg-query-stream...though should be just a find/replace type operation to upgrade as the semantics remain very similar (not exactly the same, since internals are rewritten, but more in line with how streams are "supposed" to behave).
- Unified the `config.batchSize` and `config.highWaterMark` to both do the same thing: control how many rows are buffered in memory. The `ReadableStream` will manage exactly how many rows are requested from the cursor at a time. This should give better out of the box performance and help with efficient async iteration.
### pg@7.17.0
- Add support for `idle_in_transaction_session_timeout` [option](https://github.com/brianc/node-postgres/pull/2049).
### 7.16.0
- Add optional, opt-in behavior to test new, [faster query pipeline](https://github.com/brianc/node-postgres/pull/2044). This is experimental, and not documented yet. The pipeline changes will grow significantly after the 8.0 release.
### 7.15.0
- Change repository structure to support lerna & future monorepo [development](https://github.com/brianc/node-postgres/pull/2014).
- [Warn about deprecation](https://github.com/brianc/node-postgres/pull/2021) for calling constructors without `new`.
### 7.14.0
- Reverts 7.13.0 as it contained [an accidental breaking change](https://github.com/brianc/node-postgres/pull/2010) for self-signed SSL cert verification. 7.14.0 is identical to 7.12.1.
### 7.13.0
- Add support for [all tls.connect()](https://github.com/brianc/node-postgres/pull/1996) options.
### 7.12.0
- Add support for [async password lookup](https://github.com/brianc/node-postgres/pull/1926).
### 7.11.0
- Add support for [connection_timeout](https://github.com/brianc/node-postgres/pull/1847/files#diff-5391bde944956870128be1136e7bc176R63) and [keepalives_idle](https://github.com/brianc/node-postgres/pull/1847).
### 7.10.0
- Add support for [per-query types](https://github.com/brianc/node-postgres/pull/1825).
### 7.9.0
- Add support for [sasl/scram authentication](https://github.com/brianc/node-postgres/pull/1835).
### 7.8.0
- Add support for passing [secureOptions](https://github.com/brianc/node-postgres/pull/1804) SSL config.
- Upgrade [pg-types](https://github.com/brianc/node-postgres/pull/1806) to 2.0.
### 7.7.0
- Add support for configurable [query timeout](https://github.com/brianc/node-postgres/pull/1760) on a client level.
### 7.6.0
- Add support for ["bring your own promise"](https://github.com/brianc/node-postgres/pull/1518)
### 7.5.0
- Better [error message](https://github.com/brianc/node-postgres/commit/11a4793452d618c53e019416cc886ad38deb1aa7) when passing `null` or `undefined` to `client.query`.
- Better [error handling](https://github.com/brianc/node-postgres/pull/1503) on queued queries.
### 7.4.0
- Add support for [Uint8Array](https://github.com/brianc/node-postgres/pull/1448) values.
### 7.3.0
- Add support for [statement timeout](https://github.com/brianc/node-postgres/pull/1436).
### 7.2.0
- Pinned pg-pool and pg-types to a tighter semver range. This is likely not a noticeable change for you unless you were specifically installing older versions of those libraries for some reason, but making it a minor bump here just in case it could cause any confusion.
### 7.1.0
#### Enhancements
- [You can now supply both a connection string and additional config options to clients.](https://github.com/brianc/node-postgres/pull/1363)
### 7.0.0
#### Breaking Changes
- Drop support for node < `4.x`.
- Remove `pg.connect` `pg.end` and `pg.cancel` singleton methods.
- `Client#connect(callback)` now returns `undefined`. It used to return an event emitter.
- Upgrade [pg-pool](https://github.com/brianc/node-pg-pool) to `2.x`.
- Upgrade [pg-native](https://github.com/brianc/node-pg-native) to `2.x`.
- Standardize error message fields between JS and native driver. The only breaking changes were in the native driver as its field names were brought into alignment with the existing JS driver field names.
- Result from multi-statement text queries such as `SELECT 1; SELECT 2;` are now returned as an array of results instead of a single result with 1 array containing rows from both queries.
[Please see here for a migration guide](https://node-postgres.com/guides/upgrading)
#### Enhancements
- Overhauled documentation: [https://node-postgres.com](https://node-postgres.com).
- Add `Client#connect() => Promise<void>` and `Client#end() => Promise<void>` calls. Promises are now returned from all async methods on clients _if and only if_ no callback was supplied to the method.
- Add `connectionTimeoutMillis` to pg-pool.
### v6.2.0
- Add support for [parsing `replicationStart` messages](https://github.com/brianc/node-postgres/pull/1271/files).
### v6.1.0
- Add optional callback parameter to the pure JavaScript `client.end` method. The native client already supported this.
### v6.0.0
#### Breaking Changes
- Remove `pg.pools`. There is still a reference kept to the pools created & tracked by `pg.connect` but it has been renamed, is considered private, and should not be used. Accessing this API directly was uncommon and was _supposed_ to be private but was incorrectly documented on the wiki. Therefore, it is a breaking change of an (unintentionally) public interface to remove it by renaming it & making it private. Eventually `pg.connect` itself will be deprecated in favor of instantiating pools directly via `new pg.Pool()` so this property should become completely moot at some point. In the mean time...check out the new features...
#### New features
- Replace internal pooling code with [pg-pool](https://github.com/brianc/node-pg-pool). This is the first step in eventually deprecating and removing the singleton `pg.connect`. The pg-pool constructor is exported from node-postgres at `require('pg').Pool`. It provides a backwards compatible interface with `pg.connect` as well as a promise based interface & additional niceties.
You can now create an instance of a pool and don't have to rely on the `pg` singleton for anything:
```
var pg = require('pg')
var pool = new pg.Pool()
// your friendly neighborhood pool interface, without the singleton
pool.connect(function(err, client, done) {
// ...
})
```
Promise support & other goodness lives now in [pg-pool](https://github.com/brianc/node-pg-pool).
**Please** read the readme at [pg-pool](https://github.com/brianc/node-pg-pool) for the full api.
- Included support for tcp keep alive. Enable it as follows:
```js
var client = new Client({ keepAlive: true })
```
This should help with backends incorrectly considering idle clients to be dead and prematurely disconnecting them.
### v5.1.0
- Make the query object returned from `client.query` implement the promise interface. This is the first step towards promisifying more of the node-postgres api.
Example:
```js
var client = new Client()
client.connect()
client.query('SELECT $1::text as name', ['brianc']).then(function (res) {
console.log('hello from', res.rows[0])
client.end()
})
```
### v5.0.0
#### Breaking Changes
- `require('pg').native` now returns null if the native bindings cannot be found; previously, this threw an exception.
#### New Features
- better error message when passing `undefined` as a query parameter
- support for `defaults.connectionString`
- support for `returnToHead` being passed to [generic pool](https://github.com/coopernurse/node-pool)
### v4.5.0
- Add option to parse JS date objects in query parameters as [UTC](https://github.com/brianc/node-postgres/pull/943)
### v4.4.0
- Warn to `stderr` if a named query exceeds 63 characters which is the max length supported by postgres.
### v4.3.0
- Unpin `pg-types` semver. Allow it to float against `pg-types@1.x`.
### v4.2.0
- Support for additional error fields in postgres >= 9.3 if available.
### v4.1.0
- Allow type parser overrides on a [per-client basis](https://github.com/brianc/node-postgres/pull/679)
### v4.0.0
- Make [native bindings](https://github.com/brianc/node-pg-native.git) an optional install with `npm install pg-native`
- No longer surround query result callback with `try/catch` block.
- Remove built in COPY IN / COPY OUT support - better implementations provided by [pg-copy-streams](https://github.com/brianc/node-pg-copy-streams.git) and [pg-native](https://github.com/brianc/node-pg-native.git)
### v3.6.0
- Include support for (parsing JSONB)[https://github.com/brianc/node-pg-types/pull/13] (supported in postgres 9.4)
### v3.5.0
- Include support for parsing boolean arrays
### v3.4.0
- Include port as connection parameter to [unix sockets](https://github.com/brianc/node-postgres/pull/604)
- Better support for odd [date parsing](https://github.com/brianc/node-pg-types/pull/8)
### v3.2.0
- Add support for parsing [date arrays](https://github.com/brianc/node-pg-types/pull/3)
- Expose array parsers on [pg.types](https://github.com/brianc/node-pg-types/pull/2)
- Allow [pool](https://github.com/brianc/node-postgres/pull/591) to be configured
### v3.1.0
- Add [count of the number of times a client has been checked out from the pool](https://github.com/brianc/node-postgres/pull/556)
- Emit `end` from `pg` object [when a pool is drained](https://github.com/brianc/node-postgres/pull/571)
### v3.0.0
#### Breaking changes
- [Parse the DATE PostgreSQL type as local time](https://github.com/brianc/node-postgres/pull/514)
After [some discussion](https://github.com/brianc/node-postgres/issues/510) it was decided node-postgres was non-compliant in how it was handling DATE results. They were being converted to UTC, but the PostgreSQL documentation specifies they should be returned in the client timezone. This is a breaking change, and if you use the `date` type you might want to examine your code and make sure nothing is impacted.
- [Fix possible numeric precision loss on numeric & int8 arrays](https://github.com/brianc/node-postgres/pull/501)
pg@v2.0 included changes to not convert large integers into their JavaScript number representation because of possibility for numeric precision loss. The same types in arrays were not taken into account. This fix applies the same type of type-coercion rules to arrays of those types, so there will be no more possible numeric loss on an array of very large int8s for example. This is a breaking change because now a return type from a query of `int8[]` will contain _string_ representations
of the integers. Use your favorite JavaScript bignum module to represent them without precision loss, or punch over the type converter to return the old style arrays again.
- [Fix to input array of dates being improperly converted to utc](https://github.com/benesch/node-postgres/commit/c41eedc3e01e5527a3d5c242fa1896f02ef0b261#diff-7172adb1fec2457a2700ed29008a8e0aR108)
Single `date` parameters were properly sent to the PostgreSQL server properly in local time, but an input array of dates was being changed into utc dates. This is a violation of what PostgreSQL expects. Small breaking change, but none-the-less something you should check out if you are inserting an array of dates.
- [Query no longer emits `end` event if it ends due to an error](https://github.com/brianc/node-postgres/commit/357b64d70431ec5ca721eb45a63b082c18e6ffa3)
This is a small change to bring the semantics of query more in line with other EventEmitters. The tests all passed after this change, but I suppose it could still be a breaking change in certain use cases. If you are doing clever things with the `end` and `error` events of a query object you might want to check to make sure its still behaving normally, though it is most likely not an issue.
#### New features
- [Supercharge `prepareValue`](https://github.com/brianc/node-postgres/pull/555)
The long & short of it is now any object you supply in the list of query values will be inspected for a `.toPostgres` method. If the method is present it will be called and its result used as the raw text value sent to PostgreSQL for that value. This allows the same type of custom type coercion on query parameters as was previously afforded to query result values.
- [Domain aware connection pool](https://github.com/brianc/node-postgres/pull/531)
If domains are active node-postgres will honor them and do everything it can to ensure all callbacks are properly fired in the active domain. If you have tried to use domains with node-postgres (or many other modules which pool long lived event emitters) you may have run into an issue where the active domain changes before and after a callback. This has been a longstanding footgun within node-postgres and I am happy to get it fixed.
- [Disconnected clients now removed from pool](https://github.com/brianc/node-postgres/pull/543)
Avoids a scenario where your pool could fill up with disconnected & unusable clients.
- [Break type parsing code into separate module](https://github.com/brianc/node-postgres/pull/541)
To provide better documentation and a clearer explanation of how to override the query result parsing system we broke the type converters [into their own module](https://github.com/brianc/node-pg-types). There is still work around removing the 'global-ness' of the type converters so each query or connection can return types differently, but this is a good first step and allow a lot more obvious way to return int8 results as JavaScript numbers, for example
### v2.11.0
- Add support for [application_name](https://github.com/brianc/node-postgres/pull/497)
### v2.10.0
- Add support for [the password file](http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html)
### v2.9.0
- Add better support for [unix domain socket](https://github.com/brianc/node-postgres/pull/487) connections
### v2.8.0
- Add support for parsing JSON[] and UUID[] result types
### v2.7.0
- Use single row mode in native bindings when available [@rpedela]
- reduces memory consumption when handling row values in 'row' event
- Automatically bind buffer type parameters as binary [@eugeneware]
### v2.6.0
- Respect PGSSLMODE environment variable
### v2.5.0
- Ability to opt-in to int8 parsing via `pg.defaults.parseInt8 = true`
### v2.4.0
- Use eval in the result set parser to increase performance
### v2.3.0
- Remove built-in support for binary Int64 parsing.
_Due to the low usage & required compiled dependency this will be pushed into a 3rd party add-on_
### v2.2.0
- [Add support for excapeLiteral and escapeIdentifier in both JavaScript and the native bindings](https://github.com/brianc/node-postgres/pull/396)
### v2.1.0
- Add support for SSL connections in JavaScript driver
- this means you can connect to heroku postgres from your local machine without the native bindings!
- [Add field metadata to result object](https://github.com/brianc/node-postgres/blob/master/test/integration/client/row-description-on-results-tests.js)
- [Add ability for rows to be returned as arrays instead of objects](https://github.com/brianc/node-postgres/blob/master/test/integration/client/results-as-array-tests.js)
### v2.0.0
- Properly handle various PostgreSQL to JavaScript type conversions to avoid data loss:
```
PostgreSQL | pg@v2.0 JavaScript | pg@v1.0 JavaScript
--------------------------------|----------------
float4 | number (float) | string
float8 | number (float) | string
int8 | string | number (int)
numeric | string | number (float)
decimal | string | number (float)
```
For more information see https://github.com/brianc/node-postgres/pull/353
If you are unhappy with these changes you can always [override the built in type parsing fairly easily](https://github.com/brianc/node-pg-parse-float).
### v1.3.0
- Make client_encoding configurable and optional
### v1.2.0
- return field metadata on result object: access via result.fields[i].name/dataTypeID
### v1.1.0
- built in support for `JSON` data type for PostgreSQL Server @ v9.2.0 or greater
### v1.0.0
- remove deprecated functionality
- Callback function passed to `pg.connect` now **requires** 3 arguments
- Client#pauseDrain() / Client#resumeDrain removed
- numeric, decimal, and float data types no longer parsed into float before being returned. Will be returned from query results as `String`
### v0.15.0
- client now emits `end` when disconnected from back-end server
- if client is disconnected in the middle of a query, query receives an error
### v0.14.0
- add deprecation warnings in prep for v1.0
- fix read/write failures in native module under node v0.9.x
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2010 - 2021 Brian Carlson
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.
================================================
FILE: LOCAL_DEV.md
================================================
# 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
```
================================================
FILE: README.md
================================================
# node-postgres

<span class="badge-npmversion"><a href="https://npmjs.org/package/pg" title="View this project on NPM"><img src="https://img.shields.io/npm/v/pg.svg" alt="NPM version" /></a></span>
<span class="badge-npmdownloads"><a href="https://npmjs.org/package/pg" title="View this project on NPM"><img src="https://img.shields.io/npm/dm/pg.svg" alt="NPM downloads" /></a></span>
Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings.
## Monorepo
This repo is a monorepo which contains the core [pg](https://github.com/brianc/node-postgres/tree/master/packages/pg) module as well as a handful of related modules.
- [pg](https://github.com/brianc/node-postgres/tree/master/packages/pg)
- [pg-pool](https://github.com/brianc/node-postgres/tree/master/packages/pg-pool)
- [pg-native](https://github.com/brianc/node-postgres/tree/master/packages/pg-native)
- [pg-cursor](https://github.com/brianc/node-postgres/tree/master/packages/pg-cursor)
- [pg-query-stream](https://github.com/brianc/node-postgres/tree/master/packages/pg-query-stream)
- [pg-connection-string](https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string)
- [pg-protocol](https://github.com/brianc/node-postgres/tree/master/packages/pg-protocol)
## Install
```
npm install pg
```
## Documentation
Each package in this repo should have its own readme more focused on how to develop/contribute. For overall documentation on the project and the related modules managed by this repo please see:
### :star: [Documentation](https://node-postgres.com) :star:
The source repo for the documentation is available for contribution [here](https://github.com/brianc/node-postgres/tree/master/docs).
### Features
- Pure JavaScript client and native libpq bindings share _the same API_
- Connection pooling
- Extensible JS ↔ PostgreSQL data-type coercion
- Supported PostgreSQL features
- Parameterized queries
- Named statements with query plan caching
- Async notifications with `LISTEN/NOTIFY`
- Bulk import & export with `COPY TO/COPY FROM`
### Extras
node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture.
The entire list can be found on our [wiki](https://github.com/brianc/node-postgres/wiki/Extras).
## Support
node-postgres is free software. If you encounter a bug with the library please open an issue on the [GitHub repo](https://github.com/brianc/node-postgres). If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better!
When you open an issue please provide:
- version of Node
- version of Postgres
- smallest possible snippet of code to reproduce the problem
You can also follow me [@brianc](https://bsky.app/profile/brianc.bsky.social) on bluesky if that's your thing for updates on node-postgres with nearly zero non node-postgres content. My old twitter/x account is no longer used.
## Sponsorship :two_hearts:
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.
### Featured sponsor
Special thanks to [medplum](https://medplum.com) for their generous and thoughtful support of node-postgres!

## Contributing
**:heart: contributions!**
I will **happily** accept your pull request if it:
- **has tests**
- looks reasonable
- does not break backwards compatibility
If your change involves breaking backwards compatibility please please point that out in the pull request & we can discuss & plan when and how to release it and what type of documentation or communication it will require.
### Setting up for local development
1. Clone the repo
2. Ensure you have installed libpq-dev in your system (the native bindings are built in the test process)
3. From your workspace root run `yarn` and then `yarn lerna bootstrap`
4. Ensure you have a PostgreSQL instance running with SSL enabled and an empty database for tests. _note: you can skip the tests requring SSL by setting the environment variable `PGTESTNOSSL=1` if you're not changing any SSL related code_.
5. Ensure you have the proper environment variables configured for connecting to your postgres instance. Using the standard `PG*` environment variables like `PGUSER` and `PGPASSWORD` etc...
6. Run `yarn test` to run all the tests.
## Troubleshooting and FAQ
The causes and solutions to common errors can be found among the [Frequently Asked Questions (FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ)
## License
Copyright (c) 2010-2020 Brian Carlson (brian.m.carlson@gmail.com)
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.
================================================
FILE: SPONSORS.md
================================================
node-postgres is made possible by the helpful contributors from the community as well as the following generous supporters on [GitHub Sponsors](https://github.com/sponsors/brianc) and [Patreon](https://www.patreon.com/node_postgres).
# Leaders
- [MadKudu](https://www.madkudu.com) - [@madkudu](https://twitter.com/madkudu)
- [Third Iron](https://thirdiron.com/)
- [Timescale](https://timescale.com)
- [Nafundi](https://nafundi.com)
- [CrateDB](https://crate.io/)
- [BitMEX](https://www.bitmex.com/app/trade/XBTUSD)
- [Dataform](https://dataform.co/)
- [Eaze](https://www.eaze.com/)
- [simpleanalytics](https://simpleanalytics.com/)
- [n8n.io](https://n8n.io/)
- [mpirik](https://github.com/mpirik)
- [@BLUE-DEVIL1134](https://github.com/BLUE-DEVIL1134)
- [bubble.io](https://bubble.io/)
- [GitHub](https://github.com/github)
- [n8n](https://n8n.io/)
- [loveland](https://github.com/loveland)
- [gajus](https://github.com/gajus)
- [thirdiron](https://github.com/thirdiron)
# Supporters
- John Fawcett
- Lalit Kapoor [@lalitkapoor](https://twitter.com/lalitkapoor)
- Paul Frazee [@pfrazee](https://twitter.com/pfrazee)
- Rein Petersen
- Arnaud Benhamdine [@abenhamdine](https://twitter.com/abenhamdine)
- Matthew Welke
- Matthew Weber
- Andrea De Simon
- Todd Kennedy
- Alexander Robson
- Benjie Gillam
- David Hanson
- Franklin Davenport
- [Eventbot](https://geteventbot.com/)
- Chuck T
- Paul Cothenet
- Pelle Wessman
- Raul Murray
- Simple Analytics
- Trevor Linton
- Ian Walter
- @Guido4000
- [Martti Laine](https://github.com/codeclown)
- [Tim Nolet](https://github.com/tnolet)
- [Ideal Postcodes](https://github.com/ideal-postcodes)
- [checkly](https://github.com/checkly)
- [Scout APM](https://github.com/scoutapm-sponsorships)
- [Sideline Sports](https://github.com/SidelineSports)
- [Gadget](https://github.com/gadget-inc)
- [Sentry](https://sentry.io/welcome/)
- [devlikeapro](https://github.com/devlikepro)
================================================
FILE: docs/.gitignore
================================================
.next
out
================================================
FILE: docs/README.md
================================================
# 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.
================================================
FILE: docs/components/alert.tsx
================================================
import { Callout } from 'nextra/components'
export const Alert = ({ children }) => {
return (
<Callout type="warning" emoji="⚠️">
{children}
</Callout>
)
}
================================================
FILE: docs/components/info.tsx
================================================
import { Callout } from 'nextra/components'
export const Info = ({ children }) => {
return <Callout emoji="ℹ️">{children}</Callout>
}
================================================
FILE: docs/components/logo.tsx
================================================
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' }} />
}
================================================
FILE: docs/next.config.js
================================================
import nextra from 'nextra'
const withNextra = nextra({
theme: 'nextra-theme-docs',
themeConfig: './theme.config.js',
})
export default withNextra({
output: 'export',
images: { unoptimized: true },
})
================================================
FILE: docs/package.json
================================================
{
"name": "docs",
"version": "1.0.0",
"description": "",
"main": "next.config.js",
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^13.5.11",
"nextra": "^3.3.1",
"nextra-theme-docs": "^3.3.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"typescript": "^5.0.2"
}
}
================================================
FILE: docs/pages/_app.js
================================================
import 'nextra-theme-docs/style.css'
export default function Nextra({ Component, pageProps }) {
return <Component {...pageProps} />
}
================================================
FILE: docs/pages/_meta.js
================================================
export default {
index: 'Welcome',
announcements: 'Announcements',
apis: 'API',
}
================================================
FILE: docs/pages/announcements.mdx
================================================
import { Alert } from '/components/alert.tsx'
## 2020-02-25
### pg@8.0 release
`pg@8.0` is [being released](https://github.com/brianc/node-postgres/pull/2117) which contains a handful of breaking changes.
I will outline each breaking change here and try to give some historical context on them. Most of them are small and subtle and likely wont impact you; **however**, there is one larger breaking change you will likely run into:
---
- Support all `tls.connect` [options](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) being passed to the client/pool constructor under the `ssl` option.
Previously we white listed the parameters passed here and did slight massaging of some of them. The main **breaking** change here is that now if you do this:
```js
const client = new Client({ ssl: true })
```
<Alert>
Now we will use the default ssl options to tls.connect which includes rejectUnauthorized being enabled. This means
your connection attempt may fail if you are using a self-signed cert. To use the old behavior you should do this:
</Alert>
```js
const client = new Client({ ssl: { rejectUnauthorized: false } })
```
This makes pg a bit more secure "out of the box" while still enabling you to opt in to the old behavior.
---
The rest of the changes are relatively minor & you likely wont need to do anything, but good to be aware none the less!
- change default database name
If a database name is not specified, available in the environment at `PGDATABASE`, or available at `pg.defaults`, we used to use the username of the process user as the name of the database. Now we will use the `user` property supplied to the client as the database name, if it exists. What this means is this:
```jsx
new Client({
user: 'foo',
})
```
`pg@7.x` will default the database name to the _process_ user. `pg@8.x` will use the `user` property supplied to the client. If you have not supplied `user` to the client, and it isn't available through any of its existing lookup mechanisms (environment variables, pg.defaults) then it will still use the process user for the database name.
- drop support for versions of node older than 8.0
Node@6.0 has been out of LTS for quite some time now, and I've removed it from our test matrix. `pg@8.0` _may_ still work on older versions of node, but it isn't a goal of the project anymore. Node@8.0 is actually no longer in the LTS support line, but pg will continue to test against and support 8.0 until there is a compelling reason to drop support for it. Any security vulnerability issues which come up I will back-port fixes to the `pg@7.x` line and do a release, but any other fixes or improvements will not be back ported.
- prevent password from being logged accidentally
`pg@8.0` makes the password field on the pool and client non-enumerable. This means when you do `console.log(client)` you wont have your database password printed out unintentionally. You can still do `console.log(client.password)` if you really want to see it!
- make `pg.native` non-enumerable
You can use `pg.native.Client` to access the native client. The first time you access the `pg.native` getter it imports the native bindings...which must be installed. In some cases (such as webpacking the pg code for lambda deployment) the `.native` property would be traversed and trigger an import of the native bindings as a side-effect. Making this property non-enumerable will fix this issue. An easy fix, but its technically a breaking change in cases where people _are_ relying on this side effect for any reason.
- make `pg.Pool` an es6 class
This makes extending `pg.Pool` possible. Previously it was not a "proper" es6 class and `class MyPool extends pg.Pool` wouldn't work.
- make `Notice` messages _not_ an instance of a JavaScript error
The code path for parsing `notice` and `error` messages from the postgres backend is the same. Previously created a JavaScript `Error` instance for _both_ of these message types. Now, only actual `errors` from the postgres backend will be an instance of an `Error`. The _shape_ and _properties_ of the two messages did not change outside of this.
- monorepo
While not technically a breaking change for the module itself, I have begun the process of [consolidating](https://github.com/brianc/node-pg-query-stream) [separate](https://github.com/brianc/node-pg-cursor/) [repos](https://github.com/brianc/node-pg-pool) into the main [repo](https://github.com/brianc/node-postgres) and converted it into a monorepo managed by lerna. This will help me stay on top of issues better (it was hard to bounce between 3-4 separate repos) and coordinate bug fixes and changes between dependant modules.
Thanks for reading that! pg tries to be super pedantic about not breaking backwards-compatibility in non semver major releases....even for seemingly small things. If you ever notice a breaking change on a semver minor/patch release please stop by the [repo](https://github.com/brianc/node-postgres) and open an issue!
_If you find `pg` valuable to you or your business please consider [supporting](http://github.com/sponsors/brianc) it's continued development! Big performance improvements, typescript, better docs, query pipelining and more are all in the works!_
## 2019-07-18
### New documentation
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.
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." ❤️
It's been quite a journey, and I look forward continuing it for as long as I can provide value to all y'all. 🤠
## 2017-08-12
### code execution vulnerability
Today [@sehrope](https://github.com/sehrope) found and reported a code execution vulnerability in node-postgres. This affects all versions from `pg@2.x` through `pg@7.1.0`.
I have published a fix on the tip of each major version branch of all affected versions as well as a fix on each minor version branch of `pg@6.x` and `pg@7.x`:
### Fixes
The following versions have been published to npm & contain a patch to fix the vulnerability:
```
pg@2.11.2
pg@3.6.4
pg@4.5.7
pg@5.2.1
pg@6.0.5
pg@6.1.6
pg@6.2.5
pg@6.3.3
pg@6.4.2
pg@7.0.3
pg@7.1.2
```
### Example
To demonstrate the issue & see if you are vulnerable execute the following in node:
```js
import pg from 'pg'
const { Client } = pg
const client = new Client()
client.connect()
const sql = `SELECT 1 AS "\\'/*", 2 AS "\\'*/\n + console.log(process.env)] = null;\n//"`
client.query(sql, (err, res) => {
client.end()
})
```
You will see your environment variables printed to your console. An attacker can use this exploit to execute any arbitrary node code within your process.
### Impact
This vulnerability _likely_ does not impact you if you are connecting to a database you control and not executing user-supplied sql. Still, you should **absolutely** upgrade to the most recent patch version as soon as possible to be safe.
Two attack vectors we quickly thought of:
- 1 - executing unsafe, user-supplied sql which contains a malicious column name like the one above.
- 2 - connecting to an untrusted database and executing a query which returns results where any of the column names are malicious.
### Support
I have created [an issue](https://github.com/brianc/node-postgres/issues/1408) you can use to discuss the vulnerability with me or ask questions, and I have reported this issue [on twitter](https://twitter.com/briancarlson) and directly to Heroku and [nodesecurity.io](https://nodesecurity.io/).
I take security very seriously. If you or your company benefit from node-postgres **[please sponsor my work](https://www.patreon.com/node_postgres)**: this type of issue is one of the many things I am responsible for, and I want to be able to continue to tirelessly provide a world-class PostgreSQL experience in node for years to come.
================================================
FILE: docs/pages/apis/_meta.js
================================================
export default {
client: 'pg.Client',
pool: 'pg.Pool',
result: 'pg.Result',
types: 'pg.Types',
cursor: 'Cursor',
utilities: 'Utilities',
}
================================================
FILE: docs/pages/apis/client.mdx
================================================
---
title: pg.Client
---
## new Client
`new Client(config: Config)`
Every field of the `config` object is entirely optional. A `Client` instance will use [environment variables](/features/connecting#environment-variables) for all missing values.
```ts
type Config = {
user?: string, // default process.env.PGUSER || process.env.USER
password?: string or function, //default process.env.PGPASSWORD
host?: string, // default process.env.PGHOST
port?: number, // default process.env.PGPORT
database?: string, // default process.env.PGDATABASE || user
connectionString?: string, // e.g. postgres://user:password@host:5432/database
ssl?: any, // passed directly to node.TLSSocket, supports all tls.connect options
types?: any, // custom type parsers
statement_timeout?: number, // number of milliseconds before a statement in query will time out, default is no timeout
query_timeout?: number, // number of milliseconds before a query call will timeout, default is no timeout
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
keepAlive?: boolean, // if true, enable keepalive on the `net.Socket`
keepAliveInitialDelayMillis?: number, // number of milliseconds between last data packet received and first keepalive probe, default is 0 (keep existing value);
// no effect unless `keepAlive` is true
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
options?: string // command-line options to be sent to the server
}
```
example to create a client with specific connection information:
```js
import { Client } from 'pg'
const client = new Client({
user: 'database-user',
password: 'secretpassword!!',
host: 'my.database-server.com',
port: 5334,
database: 'database-name',
})
```
## client.connect
```js
import { Client } from 'pg'
const client = new Client()
await client.connect()
```
## client.query
### QueryConfig
You can pass an object to `client.query` with the signature of:
```ts
type QueryConfig {
// the raw query text
text: string;
// an array of query parameters
values?: Array<any>;
// name of the query - used for prepared statements
name?: string;
// by default rows come out as a key/value pair for each row
// pass the string 'array' here to receive rows as an array of values
rowMode?: string;
// custom type parsers just for this query result
types?: Types;
// TODO: document
queryMode?: string;
}
```
```ts
client.query(text: string, values?: any[]) => Promise<Result>
```
**Plain text query**
```js
import { Client } from 'pg'
const client = new Client()
await client.connect()
const result = await client.query('SELECT NOW()')
console.log(result)
await client.end()
```
**Parameterized query**
```js
import { Client } from 'pg'
const client = new Client()
await client.connect()
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**
If you pass a `name` parameter to the `client.query` method, the client will create a [prepared statement](/features/queries#prepared-statements).
```js
const query = {
name: 'get-name',
text: 'SELECT $1::text',
values: ['brianc'],
rowMode: 'array',
}
const result = await client.query(query)
console.log(result.rows) // ['brianc']
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
import { Query } from 'pg'
const query = new Query('select $1::text as name', ['brianc'])
const result = client.query(query)
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)
})
```
---
## client.end
Disconnects the client from the PostgreSQL server.
```js
await client.end()
console.log('client has disconnected')
```
## events
### error
```ts
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 forward 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()
client.connect()
client.on('error', (err) => {
console.error('something bad has happened!', err.stack)
})
// walk over to server, unplug network cable
// process output: 'something bad has happened!' followed by stacktrace :P
```
### end
```ts
client.on('end') => void
```
When the client disconnects from the PostgreSQL server it will emit an end event once.
### notification
Used for `listen/notify` events:
```ts
type Notification {
processId: number,
channel: string,
payload?: string
}
```
```js
const client = new pg.Client()
await client.connect()
client.query('LISTEN foo')
client.on('notification', (msg) => {
console.log(msg.channel) // foo
console.log(msg.payload) // bar!
})
client.query(`NOTIFY foo, 'bar!'`)
```
### notice
```ts
client.on('notice', (notice: Error) => void) => void
```
Used to log out [notice messages](https://www.postgresql.org/docs/9.6/static/plpgsql-errors-and-messages.html) from the PostgreSQL server.
```js
client.on('notice', (msg) => console.warn('notice:', msg))
```
================================================
FILE: docs/pages/apis/cursor.mdx
================================================
---
title: pg.Cursor
slug: /apis/cursor
---
A cursor can be used to efficiently read through large result sets without loading the entire result-set into memory ahead of time. It's useful to simulate a 'streaming' style read of data, or exit early from a large result set. The cursor is passed to `client.query` and is dispatched internally in a way very similar to how normal queries are sent, but the API it presents for consuming the result set is different.
## install
```
$ npm install pg pg-cursor
```
## constructor
### `new Cursor(text: String, values: Any[][, config: CursorQueryConfig])`
Instantiates a new Cursor. A cursor is an instance of `Submittable` and should be passed directly to the `client.query` method.
```js
import { Pool } from 'pg'
import Cursor from 'pg-cursor'
const pool = new Pool()
const client = await pool.connect()
const text = 'SELECT * FROM my_large_table WHERE something > $1'
const values = [10]
const cursor = client.query(new Cursor(text, values))
const { rows } = await cursor.read(100)
console.log(rows.length) // 100 (unless the table has fewer than 100 rows)
client.release()
```
```ts
type CursorQueryConfig {
// by default rows come out as a key/value pair for each row
// pass the string 'array' here to receive rows as an array of values
rowMode?: string;
// custom type parsers just for this query result
types?: Types;
}
```
## read
### `cursor.read(rowCount: Number) => Promise<pg.Result>`
Read `rowCount` rows from the cursor instance. The callback will be called when the rows are available, loaded into memory, parsed, and converted to JavaScript types.
If the cursor has read to the end of the result sets all subsequent calls to cursor#read will return a 0 length array of rows. Calling `read` on a cursor that has read to the end.
Here is an example of reading to the end of a cursor:
```js
import { Pool } from 'pg'
import Cursor from 'pg-cursor'
const pool = new Pool()
const client = await pool.connect()
const cursor = client.query(new Cursor('select * from generate_series(0, 5)'))
let rows = await cursor.read(100)
assert(rows.length == 6)
rows = await cursor.read(100)
assert(rows.length == 0)
```
## close
### `cursor.close() => Promise<void>`
Used to close the cursor early. If you want to stop reading from the cursor before you get all of the rows returned, call this.
================================================
FILE: docs/pages/apis/pool.mdx
================================================
---
title: pg.Pool
---
import { Alert } from '/components/alert.tsx'
## new Pool
```ts
new Pool(config: Config)
```
Constructs a new pool instance.
The pool is initially created empty and will create new clients lazily as they are needed. Every field of the `config` object is entirely optional. The config passed to the pool is also passed to every client instance within the pool when the pool creates that client.
```ts
type Config = {
// All valid client config options are also valid here.
// In addition here are the pool specific configuration parameters:
// Number of milliseconds to wait before timing out when connecting a new client.
// By default this is 0 which means no timeout.
connectionTimeoutMillis?: number
// Number of milliseconds a client must sit idle in the pool and not be checked out
// before it is disconnected from the backend and discarded.
// Default is 10000 (10 seconds) - set to 0 to disable auto-disconnection of idle clients.
idleTimeoutMillis?: number
// Maximum number of clients the pool should contain.
// 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: currently 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
// after being idle or the pool is manually shutdown with `pool.end()`.
//
// Setting `allowExitOnIdle: true` in the config will allow the node event loop to exit
// as soon as all clients in the pool are idle, even if their socket is still open
// 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
// Number of times a client can be checked out from the pool before it is
// disconnected and a new client is created in its place.
// The default is Infinity which means a client will never be automatically destroyed
// outside of other lifecycle events like manually removing it, it timing out due to idleness, etc.
maxUses?: number
// 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
// Called once when a new client is created, before it is made available to the pool.
// The client is fully connected and queryable at this point.
// Can be a regular function or an async function.
// If the function throws or returns a promise that rejects, the client is destroyed
// and the error is returned to the caller requesting the connection.
onConnect?: (client: Client) => void | Promise<void>
}
```
example to create a new pool with configuration:
```js
import { Pool } from 'pg'
const pool = new Pool({
host: 'localhost',
user: 'database-user',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
maxLifetimeSeconds: 60,
})
```
example using `onConnect` to run setup commands on each new client:
```js
import { Pool } from 'pg'
const pool = new Pool({
onConnect: async (client) => {
await client.query('SET search_path TO my_schema')
},
})
```
## pool.query
Often we only need to run a single query on the database, so as convenience the pool has a method to run a query on the first available idle client and return its result.
```ts
pool.query(text: string, values?: any[]) => Promise<pg.Result>
```
```js
import { Pool } from 'pg'
const pool = new Pool()
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 in many situations and I use it exclusively unless I need a transaction.
<Alert>
<div>
Do <strong>not</strong> use <code>pool.query</code> if you are using a transaction.
</div>
The pool will dispatch every query passed to pool.query on the first available idle client. Transactions within PostgreSQL
are scoped to a single client and so dispatching individual queries within a single transaction across multiple, random
clients will cause big problems in your app and not work. For more info please read <a href="/features/transactions">
transactions
</a>.
</Alert>
## pool.connect
`pool.connect() => Promise<pg.Client>`
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, requests will wait in a FIFO queue until a client becomes available by being released back to the pool.
```js
import { Pool } from 'pg'
const pool = new Pool()
const client = await pool.connect()
await client.query('SELECT NOW()')
client.release()
```
### releasing clients
`client.release(destroy?: boolean) => void`
Client instances returned from `pool.connect` will have a `release` method which will release them from the pool.
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 { Pool } from 'pg'
const pool = new Pool()
// check out a single client
const client = await pool.connect()
// release the client
client.release()
```
```js
import { Pool } from 'pg'
const pool = new Pool()
assert(pool.totalCount === 0)
assert(pool.idleCount === 0)
const client = await pool.connect()
await client.query('SELECT NOW()')
assert(pool.totalCount === 1)
assert(pool.idleCount === 0)
// tell the pool to destroy this client
await client.release(true)
assert(pool.idleCount === 0)
assert(pool.totalCount === 0)
```
<Alert>
<div>
You <strong>must</strong> release a client when you are finished with it.
</div>
If you forget to release the client then your application will quickly exhaust available, idle clients in the pool and
all further calls to <code>pool.connect</code> will timeout with an error or hang indefinitely if you have <code>
connectionTimeoutMillis
</code> configured to 0.
</Alert>
## pool.end
Calling `pool.end` will drain the pool of all active clients, disconnect them, and shut down any internal timers in the pool. It is common to call this at the end of a script using the pool or when your process is attempting to shut down cleanly.
```js
// again both promises and callbacks are supported:
import { Pool } from 'pg'
const pool = new Pool()
await pool.end()
```
## properties
`pool.totalCount: number`
The total number of clients existing within the pool.
`pool.idleCount: number`
The number of clients which are not checked out but are currently idle in the pool.
`pool.waitingCount: number`
The number of queued requests waiting on a client when all clients are checked out. It can be helpful to monitor this number to see if you need to adjust the size of the pool.
## events
`Pool` instances are also instances of [`EventEmitter`](https://nodejs.org/api/events.html).
### connect
`pool.on('connect', (client: Client) => void) => void`
Whenever the pool establishes a new client connection to the PostgreSQL backend it will emit the `connect` event with the newly connected client.
<Alert>
The event listener does not wait for promises or async functions. If you want to run setup commands on each new client, use the `onConnect` option. (See documentation above.)
</Alert>
### acquire
`pool.on('acquire', (client: Client) => void) => void`
Whenever a client is checked out from the pool the pool will emit the `acquire` event with the client that was acquired.
### error
`pool.on('error', (err: Error, client: Client) => void) => void`
When a client is sitting idly in the pool it can still emit errors because it is connected to a live backend.
If the backend goes down or a network partition is encountered all the idle, connected clients in your application will emit an error _through_ the pool's error event emitter.
The error listener is passed the error as the first argument and the client upon which the error occurred as the 2nd argument. The client will be automatically terminated and removed from the pool, it is only passed to the error handler in case you want to inspect it.
<Alert>
<div>You probably want to add an event listener to the pool to catch background errors!</div>
Just like other event emitters, if a pool emits an <code>error</code> event and no listeners are added node will emit an
uncaught error and potentially crash your node process.
</Alert>
### release
`pool.on('release', (err: Error, client: Client) => void) => void`
Whenever a client is released back into the pool, the pool will emit the `release` event.
### remove
`pool.on('remove', (client: Client) => void) => void`
Whenever a client is closed & removed from the pool the pool will emit the `remove` event.
================================================
FILE: docs/pages/apis/result.mdx
================================================
---
title: pg.Result
slug: /apis/result
---
The `pg.Result` shape is returned for every successful query.
<div className="alert alert-info">note: you cannot instantiate this directly</div>
## properties
### `result.rows: Array<any>`
Every result will have a rows array. If no rows are returned the array will be empty. Otherwise the array will contain one item for each row returned from the query. By default node-postgres creates a map from the name to value of each column, giving you a json-like object back for each row.
### `result.fields: Array<FieldInfo>`
Every result will have a fields array. This array contains the `name` and `dataTypeID` of each field in the result. These fields are ordered in the same order as the columns if you are using `arrayMode` for the query:
```js
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
const client = await pool.connect()
const result = await client.query({
rowMode: 'array',
text: 'SELECT 1 as one, 2 as two;',
})
console.log(result.fields[0].name) // one
console.log(result.fields[1].name) // two
console.log(result.rows) // [ [ 1, 2 ] ]
await client.end()
```
### `result.command: string`
The command type last executed: `INSERT` `UPDATE` `CREATE` `SELECT` etc.
### `result.rowCount: int | null`
The number of rows processed by the last command. Can be `null` for commands that never affect rows, such as the `LOCK`-command. More specifically, some commands, including `LOCK`, only return a command tag of the form `COMMAND`, without any `[ROWS]`-field to parse. For such commands `rowCount` will be `null`.
_note: this does not reflect the number of rows __returned__ from a query. e.g. an update statement could update many rows (so high `result.rowCount` value) but `result.rows.length` would be zero. To check for an empty query response on a `SELECT` query use `result.rows.length === 0`_.
[@sehrope](https://github.com/brianc/node-postgres/issues/2182#issuecomment-620553915) has a good explanation:
The `rowCount` is populated from the command tag supplied by the PostgreSQL server. It's generally of the form: `COMMAND [OID] [ROWS]`
For DML commands (INSERT, UPDATE, etc), it reflects how many rows the server modified to process the command. For SELECT or COPY commands it reflects how many rows were retrieved or copied. More info on the specifics here: https://www.postgresql.org/docs/current/protocol-message-formats.html (search for CommandComplete for the message type)
The note in the docs about the difference is because that value is controlled by the server. It's possible for a non-standard server (ex: PostgreSQL fork) or a server version in the future to provide different information in some situations so it'd be best not to rely on it to assume that the rows array length matches the `rowCount`. It's fine to use it for DML counts though.
================================================
FILE: docs/pages/apis/types.mdx
================================================
---
title: Types
slug: /apis/types
---
These docs are incomplete, for now please reference [pg-types docs](https://github.com/brianc/node-pg-types).
================================================
FILE: docs/pages/apis/utilities.mdx
================================================
---
title: Utilities
---
import { Alert } from '/components/alert.tsx'
## Utility Functions
### pg.escapeIdentifier
Escapes a string as a [SQL identifier](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).
```js
import { escapeIdentifier } from 'pg';
const escapedIdentifier = escapeIdentifier('FooIdentifier')
console.log(escapedIdentifier) // '"FooIdentifier"'
```
<Alert>
**Note**: When using an identifier that is the result of this function in an operation like `CREATE TABLE ${escapedIdentifier(identifier)}`, the table that is created will be CASE SENSITIVE. If you use any capital letters in the escaped identifier, you must always refer to the created table like `SELECT * from "MyCaseSensitiveTable"`; queries like `SELECT * FROM MyCaseSensitiveTable` will result in a "Non-existent table" error since case information is stripped from the query.
</Alert>
### pg.escapeLiteral
<Alert>
**Note**: Instead of manually escaping SQL literals, it is recommended to use parameterized queries. Refer to [parameterized queries](/features/queries#parameterized-query) and the [client.query](/apis/client#clientquery) API for more information.
</Alert>
Escapes a string as a [SQL literal](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS).
```js
import { escapeLiteral } from 'pg';
const escapedLiteral = escapeLiteral("hello 'world'")
console.log(escapedLiteral) // "'hello ''world'''"
```
================================================
FILE: docs/pages/features/_meta.js
================================================
export default {
connecting: 'Connecting',
queries: 'Queries',
pooling: 'Pooling',
transactions: 'Transactions',
types: 'Data Types',
ssl: 'SSL',
native: 'Native',
esm: 'ESM',
callbacks: 'Callbacks',
}
================================================
FILE: docs/pages/features/callbacks.mdx
================================================
---
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()
})
})
```
================================================
FILE: docs/pages/features/connecting.mdx
================================================
---
title: Connecting
---
## Environment variables
node-postgres uses the same [environment variables](https://www.postgresql.org/docs/9.1/static/libpq-envars.html) as libpq and psql to connect to a PostgreSQL server. Both individual clients & pools will use these environment variables. Here's a tiny program connecting node.js to the PostgreSQL server:
```js
import pg from 'pg'
const { Pool, Client } = pg
// pools will use environment variables
// for connection information
const pool = new Pool()
// you can also use async/await
const res = await pool.query('SELECT NOW()')
await pool.end()
// clients will also use environment variables
// for connection information
const client = new Client()
await client.connect()
const res = await client.query('SELECT NOW()')
await client.end()
```
To run the above program and specify which database to connect to we can invoke it like so:
```sh
$ PGUSER=dbuser \
PGPASSWORD=secretpassword \
PGHOST=database.server.com \
PGPORT=3211 \
PGDATABASE=mydb \
node script.js
```
This allows us to write our programs without having to specify connection information in the program and lets us reuse them to connect to different databases without having to modify the code.
The default values for the environment variables used are:
```
PGUSER=process.env.USER
PGPASSWORD=null
PGHOST=localhost
PGPORT=5432
PGDATABASE=process.env.USER
```
## Programmatic
node-postgres also supports configuring a pool or client programmatically with connection information. Here's our same script from above modified to use programmatic (hard-coded in this case) values. This can be useful if your application already has a way to manage config values or you don't want to use environment variables.
```js
import pg from 'pg'
const { Pool, Client } = pg
const pool = new Pool({
user: 'dbuser',
password: 'secretpassword',
host: 'database.server.com',
port: 3211,
database: 'mydb',
})
console.log(await pool.query('SELECT NOW()'))
const client = new Client({
user: 'dbuser',
password: 'secretpassword',
host: 'database.server.com',
port: 3211,
database: 'mydb',
})
await client.connect()
console.log(await client.query('SELECT NOW()'))
await client.end()
```
Many cloud providers include alternative methods for connecting to database instances using short-lived authentication tokens. node-postgres supports dynamic passwords via a callback function, either synchronous or asynchronous. The callback function must resolve to a string.
```js
import pg from 'pg'
const { Pool } = pg
import { RDS } from 'aws-sdk'
const signerOptions = {
credentials: {
accessKeyId: 'YOUR-ACCESS-KEY',
secretAccessKey: 'YOUR-SECRET-ACCESS-KEY',
},
region: 'us-east-1',
hostname: 'example.aslfdewrlk.us-east-1.rds.amazonaws.com',
port: 5432,
username: 'api-user',
}
const signer = new RDS.Signer(signerOptions)
const getPassword = () => signer.getAuthToken()
const pool = new Pool({
user: signerOptions.username,
password: getPassword,
host: signerOptions.hostname,
port: signerOptions.port,
database: 'my-db',
})
```
### Unix Domain Sockets
Connections to unix sockets can also be made. This can be useful on distros like Ubuntu, where authentication is managed via the socket connection instead of a password.
```js
import pg from 'pg'
const { Client } = pg
client = new Client({
user: 'username',
password: 'password',
host: '/cloudsql/myproject:zone:mydb',
database: 'database_name',
})
```
## Connection URI
You can initialize both a pool and a client with a connection string URI as well. This is common in environments like Heroku where the database connection string is supplied to your application dyno through an environment variable. Connection string parsing brought to you by [pg-connection-string](https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string).
```js
import pg from 'pg'
const { Pool, Client } = pg
const connectionString = 'postgresql://dbuser:secretpassword@database.server.com:3211/mydb'
const pool = new Pool({
connectionString,
})
await pool.query('SELECT NOW()')
await pool.end()
const client = new Client({
connectionString,
})
await client.connect()
await client.query('SELECT NOW()')
await client.end()
```
================================================
FILE: docs/pages/features/esm.mdx
================================================
---
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...
```
================================================
FILE: docs/pages/features/native.mdx
================================================
---
title: Native Bindings
slug: /features/native
metaTitle: bar
---
Native bindings between node.js & [libpq](https://www.postgresql.org/docs/9.5/static/libpq.html) are provided by the [node-pg-native](https://github.com/brianc/node-pg-native) package. node-postgres can consume this package & use the native bindings to access the PostgreSQL server while giving you the same interface that is used with the JavaScript version of the library.
You need PostgreSQL client libraries & tools installed. An easy way to check is to type `pg_config`. If `pg_config` is in your path, you should be good to go. If it's not in your path you'll need to consult operating specific instructions on how to go about getting it there.
Some ways I've done it in the past:
- On macOS: `brew install libpq`
- On Ubuntu/Debian and Debian-based Node images: `apt-get install libpq-dev python3 g++ make`
- On RHEL/CentOS: `yum install postgresql-devel`
- On Windows:
1. Install Visual Studio C++ (successfully built with Express 2010). Express is free.
2. Install PostgreSQL (`http://www.postgresql.org/download/windows/`)
3. Add your Postgre Installation's `bin` folder to the system path (i.e. `C:\Program Files\PostgreSQL\9.3\bin`).
4. Make sure that both `libpq.dll` and `pg_config.exe` are in that folder.
Install `pg` and `pg-native` them:
```sh
$ npm install pg pg-native
```
Once `pg-native` is installed instead of requiring a `Client` or `Pool` constructor from `pg` you do the following:
```js
import pg from 'pg'
const { native } = pg
const { Client, Pool } = native
```
When you access the `.native` property on `'pg'` it will automatically require the `pg-native` package and wrap it in the same API.
<div class='alert alert-warning'>
Care has been taken to normalize between the two, but there might still be edge cases where things behave subtly differently due to the nature of using libpq over handling the binary protocol directly in JavaScript, so it's recommended you chose to either use the JavaScript driver or the native bindings both in development and production. For what its worth: I use the pure JavaScript driver because the JavaScript driver is more portable (doesn't need a compiler), and the pure JavaScript driver is <em>plenty</em> fast.
</div>
Some of the modules using advanced features of PostgreSQL such as [pg-query-stream](https://github.com/brianc/node-pg-query-stream), [pg-cursor](https://github.com/brianc/node-pg-cursor),and [pg-copy-streams](https://github.com/brianc/node-pg-copy-streams) need to operate directly on the binary stream and therefore are incompatible with the native bindings.
================================================
FILE: docs/pages/features/pooling.mdx
================================================
---
title: Pooling
---
import { Alert } from '/components/alert.tsx'
import { Info } from '/components/info.tsx'
If you're working on a web application or other software which makes frequent queries you'll want to use a connection pool.
The easiest and by far most common way to use node-postgres is through a connection pool.
## Why?
- Connecting a new client to the PostgreSQL server requires a handshake which can take 20-30 milliseconds. During this time passwords are negotiated, SSL may be established, and configuration information is shared with the client & server. Incurring this cost _every time_ we want to execute a query would substantially slow down our application.
- The PostgreSQL server can only handle a [limited number of clients at a time](https://wiki.postgresql.org/wiki/Number_Of_Database_Connections). Depending on the available memory of your PostgreSQL server you may even crash the server if you connect an unbounded number of clients. _note: I have crashed a large production PostgreSQL server instance in RDS by opening new clients and never disconnecting them in a python application long ago. It was not fun._
- PostgreSQL can only process one query at a time on a single connected client in a first-in first-out manner. If your multi-tenant web application is using only a single connected client all queries among all simultaneous requests will be pipelined and executed serially, one after the other. No good!
### Good news
node-postgres ships with built-in connection pooling via the [pg-pool](/apis/pool) module.
## Examples
The client pool allows you to have a reusable pool of clients you can check out, use, and return. You generally want a limited number of these in your application and usually just 1. Creating an unbounded number of pools defeats the purpose of pooling at all.
### Checkout, use, and return
```js
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
// the pool will emit an error on behalf of any idle clients
// it contains if a backend error or network partition happens
pool.on('error', (err, client) => {
console.error('Unexpected error on idle client', err)
process.exit(-1)
})
const client = await pool.connect()
const res = await client.query('SELECT * FROM users WHERE id = $1', [1])
console.log(res.rows[0])
client.release()
```
<Alert>
<div>
You must <b>always</b> return the client to the pool if you successfully check it out, regardless of whether or not
there was an error with the queries you ran on the client.
</div>
If you don't release the client your application will leak them and eventually your pool will be empty forever and all
future requests to check out a client from the pool will wait forever.
</Alert>
### Single query
If you don't need a transaction or you just need to run a single query, the pool has a convenience method to run a query on any available client in the pool. This is the preferred way to query with node-postgres if you can as it removes the risk of leaking a client.
```js
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
const res = await pool.query('SELECT * FROM users WHERE id = $1', [1])
console.log('user:', res.rows[0])
```
### Shutdown
To shut down a pool call `pool.end()` on the pool. This will wait for all checked-out clients to be returned and then shut down all the clients and the pool timers.
```js
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
console.log('starting async query')
const result = await pool.query('SELECT NOW()')
console.log('async query finished')
console.log('starting callback query')
pool.query('SELECT NOW()', (err, res) => {
console.log('callback query finished')
})
console.log('calling end')
await pool.end()
console.log('pool has drained')
```
The output of the above will be:
```
starting async query
async query finished
starting callback query
calling end
callback query finished
pool has drained
```
<Info>
The pool will return errors when attempting to check out a client after you've called pool.end() on the pool.
</Info>
================================================
FILE: docs/pages/features/queries.mdx
================================================
---
title: Queries
slug: /features/queries
---
For the sake of brevity I am using the `client.query` method instead of the `pool.query` method - both methods support the same API. In fact, `pool.query` delegates directly to `client.query` internally.
## Text only
If your query has no parameters you do not need to include them to the query method:
```js
await client.query('SELECT NOW() as now')
```
## Parameterized query
If you are passing parameters to your queries you will want to avoid string concatenating parameters into the query text directly. This can (and often does) lead to sql injection vulnerabilities. node-postgres supports parameterized queries, passing your query text _unaltered_ as well as your parameters to the PostgreSQL server where the parameters are safely substituted into the query with battle-tested parameter substitution code within the server itself.
```js
const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['brianc', 'brian.m.carlson@gmail.com']
const res = await client.query(text, values)
console.log(res.rows[0])
// { name: 'brianc', email: 'brian.m.carlson@gmail.com' }
```
<div className="alert alert-warning">
PostgreSQL does not support parameters for identifiers. If you need to have dynamic database, schema, table, or column names (e.g. in DDL statements) use [pg-format](https://www.npmjs.com/package/pg-format) package for handling escaping these values to ensure you do not have SQL injection!
</div>
Parameters passed as the second argument to `query()` will be converted to raw data types using the following rules:
**null and undefined**
If parameterizing `null` and `undefined` then both will be converted to `null`.
**Date**
Custom conversion to a UTC date string.
**Buffer**
Buffer instances are unchanged.
**Array**
Converted to a string that describes a Postgres array. Each array item is recursively converted using the rules described here.
**Object**
If a parameterized value has the method `toPostgres` then it will be called and its return value will be used in the query.
The signature of `toPostgres` is the following:
```
toPostgres (prepareValue: (value) => any): any
```
The `prepareValue` function provided can be used to convert nested types to raw data types suitable for the database.
Otherwise if no `toPostgres` method is defined then `JSON.stringify` is called on the parameterized value.
**Everything else**
All other parameterized values will be converted by calling `value.toString` on the value.
## Query config object
`pool.query` and `client.query` both support taking a config object as an argument instead of taking a string and optional array of parameters. The same example above could also be performed like so:
```js
const query = {
text: 'INSERT INTO users(name, email) VALUES($1, $2)',
values: ['brianc', 'brian.m.carlson@gmail.com'],
}
const res = await client.query(query)
console.log(res.rows[0])
```
The query config object allows for a few more advanced scenarios:
### Prepared statements
PostgreSQL has the concept of a [prepared statement](https://www.postgresql.org/docs/9.3/static/sql-prepare.html). node-postgres supports this by supplying a `name` parameter to the query config object. If you supply a `name` parameter the query execution plan will be cached on the PostgreSQL server on a **per connection basis**. This means if you use two different connections each will have to parse & plan the query once. node-postgres handles this transparently for you: a client only requests a query to be parsed the first time that particular client has seen that query name:
```js
const query = {
// give the query a unique name
name: 'fetch-user',
text: 'SELECT * FROM user WHERE id = $1',
values: [1],
}
const res = await client.query(query)
console.log(res.rows[0])
```
In the above example the first time the client sees a query with the name `'fetch-user'` it will send a 'parse' request to the PostgreSQL server & execute the query as normal. The second time, it will skip the 'parse' request and send the _name_ of the query to the PostgreSQL server.
<div className='message is-warning'>
<div className='message-body'>
Be careful not to fall into the trap of premature optimization. Most of your queries will likely not benefit much, if at all, from using prepared statements. This is a somewhat "power user" feature of PostgreSQL that is best used when you know how to use it - namely with very complex queries with lots of joins and advanced operations like union and switch statements. I rarely use this feature in my own apps unless writing complex aggregate queries for reports and I know the reports are going to be executed very frequently.
</div>
</div>
### Row mode
By default node-postgres reads rows and collects them into JavaScript objects with the keys matching the column names and the values matching the corresponding row value for each column. If you do not need or do not want this behavior you can pass `rowMode: 'array'` to a query object. This will inform the result parser to bypass collecting rows into a JavaScript object, and instead will return each row as an array of values.
```js
const query = {
text: 'SELECT $1::text as first_name, $2::text as last_name',
values: ['Brian', 'Carlson'],
rowMode: 'array',
}
const res = await client.query(query)
console.log(res.fields.map(field => field.name)) // ['first_name', 'last_name']
console.log(res.rows[0]) // ['Brian', 'Carlson']
```
### Types
You can pass in a custom set of type parsers to use when parsing the results of a particular query. The `types` property must conform to the [Types](/apis/types) API. Here is an example in which every value is returned as a string:
```js
const query = {
text: 'SELECT * from some_table',
types: {
getTypeParser: () => val => val,
},
}
```
================================================
FILE: docs/pages/features/ssl.mdx
================================================
---
title: SSL
slug: /features/ssl
---
node-postgres supports TLS/SSL connections to your PostgreSQL server as long as the server is configured to support it. When instantiating a pool or a client you can provide an `ssl` property on the config object and it will be passed to the constructor for the [node TLSSocket](https://nodejs.org/api/tls.html#tls_class_tls_tlssocket).
## Self-signed cert
Here's an example of a configuration you can use to connect a client or a pool to a PostgreSQL server.
```js
const config = {
database: 'database-name',
host: 'host-or-ip',
// this object will be passed to the TLSSocket constructor
ssl: {
ca: fs.readFileSync('/path/to/server-certificates/root.crt'),
key: fs.readFileSync('/path/to/client-key/postgresql.key'),
cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt'),
},
}
import { Client, Pool } from 'pg'
const client = new Client(config)
await client.connect()
console.log('connected')
await client.end()
const pool = new Pool(config)
const pooledClient = await pool.connect()
console.log('connected')
pooledClient.release()
await pool.end()
```
## Usage with `connectionString`
If you plan to use a combination of a database connection string from the environment and SSL settings in the config object directly, then you must avoid including any of `sslcert`, `sslkey`, `sslrootcert`, or `sslmode` in the connection string. If any of these options are used then the `ssl` object is replaced and any additional options provided there will be lost.
```js
const config = {
connectionString: 'postgres://user:password@host:port/db?sslmode=require',
// Beware! The ssl object is overwritten when parsing the connectionString
ssl: {
ca: fs.readFileSync('/path/to/server-certificates/root.crt'),
},
}
```
## Channel binding
If the PostgreSQL server offers SCRAM-SHA-256-PLUS (i.e. channel binding) for TLS/SSL connections, you can enable this as follows:
```js
const client = new Client({ ...config, enableChannelBinding: true})
```
or
```js
const pool = new Pool({ ...config, enableChannelBinding: true})
```
================================================
FILE: docs/pages/features/transactions.mdx
================================================
---
title: Transactions
---
import { Alert } from '/components/alert.tsx'
To execute a transaction with node-postgres you simply execute `BEGIN / COMMIT / ROLLBACK` queries yourself through a client. Because node-postgres strives to be low level and un-opinionated, it doesn't provide any higher level abstractions specifically around transactions.
<Alert>
You <strong>must</strong> use the <em>same</em> client instance for all statements within a transaction. PostgreSQL
isolates a transaction to individual clients. This means if you initialize or use transactions with the{' '}
<span className="code">pool.query</span> method you <strong>will</strong> have problems. Do not use transactions with
the <span className="code">pool.query</span> method.
</Alert>
## Examples
```js
import { Pool } from 'pg'
const pool = new Pool()
const client = await pool.connect()
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
```
================================================
FILE: docs/pages/features/types.mdx
================================================
---
title: Data Types
---
import { Alert } from '/components/alert.tsx'
PostgreSQL has a rich system of supported [data types](https://www.postgresql.org/docs/current/datatype.html). node-postgres does its best to support the most common data types out of the box and supplies an extensible type parser to allow for custom type serialization and parsing.
## strings by default
node-postgres will convert a database type to a JavaScript string if it doesn't have a registered type parser for the database type. Furthermore, you can send any type to the PostgreSQL server as a string and node-postgres will pass it through without modifying it in any way. To circumvent the type parsing completely do something like the following.
```js
const queryText = 'SELECT int_col::text, date_col::text, json_col::text FROM my_table'
const result = await client.query(queryText)
console.log(result.rows[0]) // will contain the unparsed string value of each column
```
## type parsing examples
### uuid + json / jsonb
There is no data type in JavaScript for a uuid/guid so node-postgres converts a uuid to a string. JavaScript has great support for JSON and node-postgres converts json/jsonb objects directly into their JavaScript object via [`JSON.parse`](https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js#L193). Likewise sending an object to the PostgreSQL server via a query from node-postgres, node-postgres will call [`JSON.stringify`](https://github.com/brianc/node-postgres/blob/e5f0e5d36a91a72dda93c74388ac890fa42b3be0/lib/utils.js#L47) on your outbound value, automatically converting it to json for the server.
```js
const createTableText = `
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE TEMP TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
data JSONB
);
`
// create our temp table
await client.query(createTableText)
const newUser = { email: 'brian.m.carlson@gmail.com' }
// create a new user
await client.query('INSERT INTO users(data) VALUES($1)', [newUser])
const { rows } = await client.query('SELECT * FROM users')
console.log(rows)
/*
output:
[{
id: 'd70195fd-608e-42dc-b0f5-eee975a621e9',
data: { email: 'brian.m.carlson@gmail.com' }
}]
*/
```
### date / timestamp / timestamptz
node-postgres will convert instances of JavaScript date objects into the expected input value for your PostgreSQL server. Likewise, when reading a `date`, `timestamp`, or `timestamptz` column value back into JavaScript, node-postgres will parse the value into an instance of a JavaScript `Date` object.
```js
const createTableText = `
CREATE TEMP TABLE dates(
date_col DATE,
timestamp_col TIMESTAMP,
timestamptz_col TIMESTAMPTZ
);
`
// create our temp table
await client.query(createTableText)
// insert the current time into it
const now = new Date()
const insertText = 'INSERT INTO dates(date_col, timestamp_col, timestamptz_col) VALUES ($1, $2, $3)'
await client.query(insertText, [now, now, now])
// read the row back out
const result = await client.query('SELECT * FROM dates')
console.log(result.rows)
// {
// date_col: 2017-05-29T05:00:00.000Z,
// timestamp_col: 2017-05-29T23:18:13.263Z,
// timestamptz_col: 2017-05-29T23:18:13.263Z
// }
```
psql output:
```
bmc=# select * from dates;
date_col | timestamp_col | timestamptz_col
------------+-------------------------+----------------------------
2017-05-29 | 2017-05-29 18:18:13.263 | 2017-05-29 18:18:13.263-05
(1 row)
```
node-postgres converts `DATE` and `TIMESTAMP` columns into the **local** time of the node process set at `process.env.TZ`.
_note: I generally use `TIMESTAMPTZ` when storing dates; otherwise, inserting a time from a process in one timezone and reading it out in a process in another timezone can cause unexpected differences in the time._
<Alert>
<div class="message-body">
Although PostgreSQL supports microseconds in dates, JavaScript only supports dates to the millisecond precision.
Keep this in mind when you send dates to and from PostgreSQL from node: your microseconds will be truncated when
converting to a JavaScript date object even if they exist in the database. If you need to preserve them, I recommend
using a custom type parser.
</div>
</Alert>
================================================
FILE: docs/pages/guides/_meta.js
================================================
export default {
'project-structure': 'Suggested Code Structure',
'async-express': 'Express with Async/Await',
'pool-sizing': 'Pool Sizing',
upgrading: 'Upgrading',
}
================================================
FILE: docs/pages/guides/async-express.md
================================================
---
title: Express with async/await
---
My preferred way to use node-postgres (and all async code in node.js) is with `async/await`. I find it makes reasoning about control-flow easier and allows me to write more concise and maintainable code.
This is how I typically structure express web-applications with node-postgres to use `async/await`:
```
- app.js
- index.js
- routes/
- index.js
- photos.js
- user.js
- db/
- index.js <--- this is where I put data access code
```
That's the same structure I used in the [project structure](/guides/project-structure) example.
My `db/index.js` file usually starts out like this:
```js
import { Pool } from 'pg'
const pool = new Pool()
export const query = (text, params) => pool.query(text, params)
```
Then I will install [express-promise-router](https://www.npmjs.com/package/express-promise-router) and use it to define my routes. Here is my `routes/user.js` file:
```js
import Router from 'express-promise-router'
import db from '../db.js'
// create a new express-promise-router
// this has the same API as the normal express router except
// it allows you to use async functions as route handlers
const router = new Router()
// export our router to be mounted by the parent application
export default router
router.get('/:id', async (req, res) => {
const { id } = req.params
const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id])
res.send(rows[0])
})
```
Then in my `routes/index.js` file I'll have something like this which mounts each individual router into the main application:
```js
// ./routes/index.js
import users from './user.js'
import photos from './photos.js'
const mountRoutes = (app) => {
app.use('/users', users)
app.use('/photos', photos)
// etc..
}
export default mountRoutes
```
And finally in my `app.js` file where I bootstrap express I will have my `routes/index.js` file mount all my routes. The routes know they're using async functions but because of express-promise-router the main express app doesn't know and doesn't care!
```js
// ./app.js
import express from 'express'
import mountRoutes from './routes.js'
const app = express()
mountRoutes(app)
// ... more express setup stuff can follow
```
Now you've got `async/await`, node-postgres, and express all working together!
================================================
FILE: docs/pages/guides/pool-sizing.md
================================================
---
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.
### Vercel
If you're running on Vercel with [fluid compute](https://vercel.com/kb/guide/efficiently-manage-database-connection-pools-with-fluid-compute), your serverless functions can handle multiple requests concurrently and stick around between invocations. In this case, you can treat it similarly to a traditional long-lived process and use a default-ish pool size of `10`. The pool will stay warm across requests and you'll get the benefits of connection reuse. You'll probably need to put pgBouncer (or some kind of pooler like what is offered with Supabase, RDS, GCP, etc.) in front of your database, as Vercel worker count can grow quite a bit larger than the number of reasonable max connections Postgres can handle.
### Cloudflare workers
In a fully stateless serverless environment like Cloudflare Workers where your worker is killed, suspended, moved to a new compute node, or shut down at the end of every request, you'll still probably be okay with a pool size `max` of `10`, though you can lower it if you start hitting connection exhaustion limits on your pooler. In Cloudflare the pooler is Hyperdrive, and in my experience it works fantastically with their workers setup. Make sure at the end of your serverless handler, after everything is done, you close and dispose of the pool by calling `pool.end()`. Setting the pool to a size larger than 1 is still recommended, as things like tRPC and other server-side routing & request batching code could result in multiple independent queries executing at the same time. With a pool size of `1` you are turning what is "a few things at once" into all things waiting in line one after another on the one available client in the pool.
## 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!
## Need help?
In my career, this has been the most error-prone thing related to running Postgres & Node, particularly with the differences in various serverless providers (Cloudflare, Vercel, Lambda, etc.) versus more traditional hosting. If you have any questions or need help, please don't hesitate to email me at [brian.m.carlson@gmail.com](mailto:brian.m.carlson@gmail.com) or reach out on GitHub.
================================================
FILE: docs/pages/guides/project-structure.md
================================================
---
title: Suggested Project Structure
---
Whenever I am writing a project & using node-postgres I like to create a file within it and make all interactions with the database go through this file. This serves a few purposes:
- Allows my project to adjust to any changes to the node-postgres API without having to trace down all the places I directly use node-postgres in my application.
- Allows me to have a single place to put logging and diagnostics around my database.
- Allows me to make custom extensions to my database access code & share it throughout the project.
- Allows a single place to bootstrap & configure the database.
## example
The location doesn't really matter - I've found it usually ends up being somewhat app specific and in line with whatever folder structure conventions you're using. For this example I'll use an express app structured like so:
```
- app.js
- index.js
- routes/
- index.js
- photos.js
- user.js
- db/
- index.js <--- this is where I put data access code
```
Typically I'll start out my `db/index.js` file like so:
```js
import { Pool } from 'pg'
const pool = new Pool()
export const query = (text, params) => {
return pool.query(text, params)
}
```
That's it. But now everywhere else in my application instead of requiring `pg` directly, I'll require this file. Here's an example of a route within `routes/user.js`:
```js
// notice here I'm requiring my database adapter file
// and not requiring node-postgres directly
import * as db from '../db/index.js'
app.get('/:id', async (req, res, next) => {
const result = await db.query('SELECT * FROM users WHERE id = $1', [req.params.id])
res.send(result.rows[0])
})
// ... many other routes in this file
```
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 { Pool } from 'pg'
const pool = new Pool()
export const query = async (text, params) => {
const start = Date.now()
const res = await pool.query(text, params)
const duration = Date.now() - start
console.log('executed query', { text, duration, rows: res.rowCount })
return res
}
```
That was pretty quick! And now all of our queries everywhere in our application are being logged.
_note: I didn't log the query parameters. Depending on your application you might be storing encrypted passwords or other sensitive information in your database. If you log your query parameters you might accidentally log sensitive information. Every app is different though so do what suits you best!_
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 { Pool } from 'pg'
const pool = new Pool()
export const query = async (text, params) => {
const start = Date.now()
const res = await pool.query(text, params)
const duration = Date.now() - start
console.log('executed query', { text, duration, rows: res.rowCount })
return res
}
export const getClient = () => {
return pool.connect()
}
```
Okay. Great - the simplest thing that could possibly work. It seems like one of our routes that checks out a client to run a transaction is forgetting to call `release` in some situation! Oh no! We are leaking a client & have hundreds of these routes to go audit. Good thing we have all our client access going through this single file. Lets add some deeper diagnostic information here to help us track down where the client leak is happening.
```js
export const query = async (text, params) => {
const start = Date.now()
const res = await pool.query(text, params)
const duration = Date.now() - start
console.log('executed query', { text, duration, rows: res.rowCount })
return res
}
export const getClient = async () => {
const client = await pool.connect()
const query = client.query
const release = client.release
// set a timeout of 5 seconds, after which we will log this client's last query
const timeout = setTimeout(() => {
console.error('A client has been checked out for more than 5 seconds!')
console.error(`The last executed query on this client was: ${client.lastQuery}`)
}, 5000)
// monkey patch the query method to keep track of the last query executed
client.query = (...args) => {
client.lastQuery = args
return query.apply(client, args)
}
client.release = () => {
// clear our timeout
clearTimeout(timeout)
// set the methods back to their old un-monkey-patched version
client.query = query
client.release = release
return release.apply(client)
}
return client
}
```
That should hopefully give us enough diagnostic information to track down any leaks.
================================================
FILE: docs/pages/guides/upgrading.md
================================================
---
title: Upgrading
slug: /guides/upgrading
---
## node version support
I have maintained legacy apps in production for many years. I get it...upgrading node and your entire dependency tree is rough, but so is missing out on critical fixes. I've taken pride over the years in not introducing breaking changes without a need because I've spent too much of my own time in my own apps upgrading a semver major version of a library with many breaking changes. That being said: node-postgres only _officially_ supports node versions which are still under the [LTS lifetime](https://nodejs.org/en/about/previous-releases). The [CI matrix](https://github.com/brianc/node-postgres/blob/master/.github/workflows/ci.yml#L39) is the most official and enforced compatiblity matrix; however, I may drop support for node versions outside of node's LTS lifetime at any time, with any semver minor release, if it is required to land new features or bug fixes on supported versions of node. I recommend in general to use a lockfile, and, if you're on an older version of node nearing EOL use absolutely pinned versions for as many of your modules as you can, including this one.
# Upgrading to 8.0
node-postgres at 8.0 introduces a breaking change to ssl-verified connections. If you connect with ssl and use
```
const client = new Client({ ssl: true })
```
and the server's SSL certificate is self-signed, connections will fail as of node-postgres 8.0. To keep the existing behavior, modify the invocation to
```
const client = new Client({ ssl: { rejectUnauthorized: false } })
```
The rest of the changes are relatively minor and unlikely to cause issues; see [the announcement](/announcements#2020-02-25) for full details.
# Upgrading to 7.0
node-postgres at 7.0 introduces somewhat significant breaking changes to the public API.
## pg singleton
In the past there was a singleton pool manager attached to the root `pg` object in the package. This singleton could be used to provision connection pools automatically by calling `pg.connect`. This API caused a lot of confusion for users. It also introduced a opaque module-managed singleton which was difficult to reason about, debug, error-prone, and inflexible. Starting in pg@6.0 the methods' documentation was removed, and starting in pg@6.3 the methods were deprecated with a warning message.
If your application still relies on these they will be _gone_ in `pg@7.0`. In order to migrate you can do the following:
```js
// old way, deprecated in 6.3.0:
// connection using global singleton
pg.connect(function (err, client, done) {
client.query(/* etc, etc */)
done()
})
// singleton pool shutdown
pg.end()
// ------------------
// new way, available since 6.0.0:
// create a pool
const pool = new pg.Pool()
// connection using created pool
pool.connect(function (err, client, done) {
client.query(/* etc, etc */)
done()
})
// pool shutdown
pool.end()
```
node-postgres ships with a built-in pool object provided by [pg-pool](https://github.com/brianc/node-pg-pool) which is already used internally by the `pg.connect` and `pg.end` methods. Migrating to a user-managed pool (or set of pools) allows you to more directly control their set up their life-cycle.
## client.query(...).on
Before `pg@7.0` the `client.query` method would _always_ return an instance of a query. The query instance was an event emitter, accepted a callback, and was also a promise. A few problems...
- too many flow control options on a single object was confusing
- event emitter `.on('error')` does not mix well with promise `.catch`
- the `row` event was a common source of errors: it looks like a stream but has no support for back-pressure, misleading users into trying to pipe results or handling them in the event emitter for a desired performance gain.
- error handling with a `.done` and `.error` emitter pair for every query is cumbersome and returning the emitter from `client.query` indicated this sort of pattern may be encouraged: it is not.
Starting with `pg@7.0` the return value `client.query` will be dependent on what you pass to the method: I think this aligns more with how most node libraries handle the callback/promise combo, and I hope it will make the "just works" :tm: feeling better while reducing surface area and surprises around event emitter / callback combos.
### client.query with a callback
```js
const query = client.query('SELECT NOW()', (err, res) => {
/* etc, etc */
})
assert(query === undefined) // true
```
If you pass a callback to the method `client.query` will return `undefined`. This limits flow control to the callback which is in-line with almost all of node's core APIs.
### client.query without a callback
```js
const query = client.query('SELECT NOW()')
assert(query instanceof Promise) // true
assert(query.on === undefined) // true
query.then((res) => /* etc, etc */)
```
If you do **not** pass a callback `client.query` will return an instance of a `Promise`. This will **not** be a query instance and will not be an event emitter. This is in line with how most promise-based APIs work in node.
### client.query(Submittable)
`client.query` has always accepted any object that has a `.submit` method on it. In this scenario the client calls `.submit` on the object, delegating execution responsibility to it. In this situation the client also **returns the instance it was passed**. This is how [pg-cursor](https://github.com/brianc/node-pg-cursor) and [pg-query-stream](https://github.com/brianc/node-pg-query-stream) work. So, if you need the event emitter functionality on your queries for some reason, it is still possible because `Query` is an instance of `Submittable`:
```js
import pg from 'pg'
const { Client, Query } = pg
const query = client.query(new Query('SELECT NOW()'))
query.on('row', (row) => {})
query.on('end', (res) => {})
query.on('error', (res) => {})
```
`Query` is considered a public, documented part of the API of node-postgres and this form will be supported indefinitely.
_note: I have been building apps with node-postgres for almost 7 years. In that time I have never used the event emitter API as the primary way to execute queries. I used to use callbacks and now I use async/await. If you need to stream results I highly recommend you use [pg-cursor](https://github.com/brianc/node-pg-cursor) or [pg-query-stream](https://github.com/brianc/node-pg-query-stream) and **not** the query object as an event emitter._
================================================
FILE: docs/pages/index.mdx
================================================
---
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
```bash
$ npm install pg
```
## Supporters
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/v3/medplum-logo-grape8-277x60.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 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 { Client } from 'pg'
const client = await new Client().connect()
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
await client.end()
```
### Error Handling
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:
```js
import { Client } from 'pg'
const client = await new Client().connect()
try {
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
} catch (err) {
console.error(err);
} finally {
await client.end()
}
```
### Pooling
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 { 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!
================================================
FILE: docs/theme.config.js
================================================
// theme.config.js
export default {
project: {
link: 'https://github.com/brianc/node-postgres',
},
twitter: {
cardType: 'summary_large_image',
site: 'https://node-postgres.com',
},
docsRepositoryBase: 'https://github.com/brianc/node-postgres/blob/master/docs', // base URL for the docs repository
titleSuffix: ' – node-postgres',
darkMode: true,
navigation: {
prev: true,
next: true,
},
footer: {
content: (
<span>
As of 2026-03-01 I am taking a break from the workforce to focus entirely on this project! Please consider{' '}
<a
href="https://github.com/sponsors/brianc"
target="_blank"
rel="noopener noreferrer"
style={{ textDecoration: 'underline' }}
>
sponsoring this work on GitHub
</a>
!
</span>
),
},
editLink: {
text: 'Edit this page on GitHub',
},
logo: (
<>
<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',
},
navbar: {
extraContent: (
<a
href="https://github.com/sponsors/brianc"
target="_blank"
rel="noopener noreferrer"
title="Sponsor this project"
className="_p-2 _text-current"
>
<svg viewBox="0 0 24 24" width="24" height="24" fill="#db61a2">
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</svg>
</a>
),
},
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."
/>
<meta name="og:title" content="node-postgres" />
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-100138145-1"></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-100138145-1');
`,
}}
></script>
</>
),
}
================================================
FILE: lerna.json
================================================
{
"packages": ["packages/*"],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent",
"command": {
"version": {
"allowBranch": "master"
}
},
"ignoreChanges": ["**/*.md", "**/test/**"]
}
================================================
FILE: package.json
================================================
{
"name": "node-postgres",
"description": "node postgres monorepo",
"main": "index.js",
"private": true,
"repository": "git@github.com:brianc/node-postgres.git",
"author": "Brian M. Carlson <brian.m.carlson@gmail.com>",
"license": "MIT",
"workspaces": [
"packages/*"
],
"scripts": {
"test": "yarn lerna exec --concurrency 1 yarn test",
"build": "tsc --build",
"build:watch": "tsc --build --watch",
"docs:build": "cd docs && yarn build",
"docs:start": "cd docs && yarn dev",
"pretest": "yarn build",
"prepublish": "yarn build",
"lint": "eslint --cache 'packages/**/*.{js,ts,tsx}'"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^6.17.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^5.1.2",
"lerna": "^3.19.0",
"prettier": "3.0.3",
"typescript": "^4.0.3"
},
"prettier": {
"semi": false,
"printWidth": 120,
"arrowParens": "always",
"trailingComma": "es5",
"singleQuote": true
}
}
================================================
FILE: packages/pg/Makefile
================================================
SHELL := /bin/sh
connectionString=postgres://
params := $(connectionString)
node-command := xargs -n 1 -I file node file $(params)
.PHONY : test test-integration bench test-native \
publish update-npm
all:
npm install
help:
@echo "make test-all [connectionString=postgres://<your connection string>]"
test: test-unit
test-all: test-unit test-integration test-native test-worker
update-npm:
@npm i npm --global
bench:
@find benchmark -name "*-bench.js" | $(node-command)
test-unit:
@chmod 600 test/unit/client/pgpass.file
@find test/unit -name "*-tests.js" | $(node-command)
test-native:
@echo "***Testing native bindings***"
ifeq ($(TEST_SKIP_NATIVE), true)
@echo "***Skipping tests***"
else
@find test/native -name "*-tests.js" | $(node-command)
@find test/integration -name "*-tests.js" | $(node-command) native
endif
test-integration:
@echo "***Testing Pure Javascript***"
@find test/integration -name "*-tests.js" | $(node-command)
test-binary:
@echo "***Testing Pure Javascript (binary)***"
@find test/integration -name "*-tests.js" | $(node-command) binary
test-pool:
@find test/integration/connection-pool -name "*.js" | $(node-command) binary
test-worker:
# this command only runs in node 18.x and above since there are
# worker specific items missing from the node environment in lower versions
@if [[ $(shell node --version | sed 's/v//' | cut -d'.' -f1) -ge 18 ]]; then \
echo "***Testing Cloudflare Worker support***"; \
yarn vitest run -c test/vitest.config.mts test/cloudflare/ --no-watch -- $(params); \
else \
echo "Skipping test-worker: Node.js version is less than 18."; \
fi
================================================
FILE: packages/pg/README.md
================================================
# node-postgres
[](http://travis-ci.org/brianc/node-postgres)
<span class="badge-npmversion"><a href="https://npmjs.org/package/pg" title="View this project on NPM"><img src="https://img.shields.io/npm/v/pg.svg" alt="NPM version" /></a></span>
<span class="badge-npmdownloads"><a href="https://npmjs.org/package/pg" title="View this project on NPM"><img src="https://img.shields.io/npm/dm/pg.svg" alt="NPM downloads" /></a></span>
Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings.
## Install
```sh
$ npm install pg
```
---
## :star: [Documentation](https://node-postgres.com) :star:
### Features
- Pure JavaScript client and native libpq bindings share _the same API_
- Connection pooling
- Extensible JS ↔ PostgreSQL data-type coercion
- Supported PostgreSQL features
- Parameterized queries
- Named statements with query plan caching
- Async notifications with `LISTEN/NOTIFY`
- Bulk import & export with `COPY TO/COPY FROM`
### Extras
node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture.
The entire list can be found on our [wiki](https://github.com/brianc/node-postgres/wiki/Extras).
## Support
node-postgres is free software. If you encounter a bug with the library please open an issue on the [GitHub repo](https://github.com/brianc/node-postgres). If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better!
When you open an issue please provide:
- version of Node
- version of Postgres
- smallest possible snippet of code to reproduce the problem
You can also follow me [@brianc](https://bsky.app/profile/brianc.bsky.social) on bluesky if that's your thing for updates on node-postgres with nearly zero non node-postgres content. My old twitter/x account is no longer used.
## Sponsorship :two_hearts:
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.
### Featured sponsor
Special thanks to [medplum](https://medplum.com) for their generous and thoughtful support of node-postgres!

## Contributing
**:heart: contributions!**
I will **happily** accept your pull request if it:
- **has tests**
- looks reasonable
- does not break backwards compatibility
If your change involves breaking backwards compatibility please please point that out in the pull request & we can discuss & plan when and how to release it and what type of documentation or communicate it will require.
## Troubleshooting and FAQ
The causes and solutions to common errors can be found among the [Frequently Asked Questions (FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ)
## License
Copyright (c) 2010-2020 Brian Carlson (brian.m.carlson@gmail.com)
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.
================================================
FILE: packages/pg/bench.js
================================================
const pg = require('./lib')
const params = {
text: 'select typname, typnamespace, typowner, typlen, typbyval, typcategory, typispreferred, typisdefined, typdelim, typrelid, typelem, typarray from pg_type where typtypmod = $1 and typisdefined = $2',
values: [-1, true],
}
const insert = {
text: 'INSERT INTO foobar(name, age) VALUES ($1, $2)',
values: ['brian', 100],
}
const seq = {
text: 'SELECT * FROM generate_series(1, 1000)',
}
const exec = async (client, q) => {
await client.query({
text: q.text,
values: q.values,
rowMode: 'array',
})
}
const bench = async (client, q, time) => {
const start = performance.now()
let count = 0
// eslint-disable-next-line no-constant-condition
while (true) {
await exec(client, q)
count++
if (performance.now() - start > time) {
return count
}
}
}
const run = async () => {
const client = new pg.Client()
await client.connect()
console.log('start')
await client.query('CREATE TEMP TABLE foobar(name TEXT, age NUMERIC)')
await client.query('CREATE TEMP TABLE buf(name TEXT, data BYTEA)')
await bench(client, params, 1000)
console.log('warmup done')
const seconds = 5
for (let i = 0; i < 4; i++) {
let queries = await bench(client, params, seconds * 1000)
console.log('')
console.log('param queries:', queries)
console.log('qps', queries / seconds)
console.log('on my laptop best so far seen 987 qps')
queries = await bench(client, { ...params, name: 'params' }, seconds * 1000)
console.log('')
console.log('named queries:', queries)
console.log('qps', queries / seconds)
console.log('on my laptop best so far seen 937 qps')
console.log('')
queries = await bench(client, seq, seconds * 1000)
console.log('sequence queries:', queries)
console.log('qps', queries / seconds)
console.log('on my laptop best so far seen 2725 qps')
console.log('')
queries = await bench(client, insert, seconds * 1000)
console.log('insert queries:', queries)
console.log('qps', queries / seconds)
console.log('on my laptop best so far seen 27383 qps')
console.log('')
console.log('Warming up bytea test')
await client.query({
text: 'INSERT INTO buf(name, data) VALUES ($1, $2)',
values: ['test', Buffer.allocUnsafe(104857600)],
})
console.log('bytea warmup done')
const start = performance.now()
const results = await client.query('SELECT * FROM buf')
const time = performance.now() - start
console.log('bytea time:', time, 'ms')
console.log('bytea length:', results.rows[0].data.byteLength, 'bytes')
console.log('on my laptop best so far seen 1407ms and 104857600 bytes')
await new Promise((resolve) => setTimeout(resolve, 250))
}
await client.end()
await client.end()
}
run().catch((e) => console.error(e) || process.exit(-1))
================================================
FILE: packages/pg/esm/index.mjs
================================================
// ESM wrapper for pg
import pg from '../lib/index.js'
// Re-export all the properties
export const Client = pg.Client
export const Pool = pg.Pool
export const Connection = pg.Connection
export const types = pg.types
export const Query = pg.Query
export const DatabaseError = pg.DatabaseError
export const escapeIdentifier = pg.escapeIdentifier
export const escapeLiteral = pg.escapeLiteral
export const Result = pg.Result
export const TypeOverrides = pg.TypeOverrides
// Also export the defaults
export const defaults = pg.defaults
// Re-export the default
export default pg
================================================
FILE: packages/pg/lib/client.js
================================================
const EventEmitter = require('events').EventEmitter
const utils = require('./utils')
const nodeUtils = require('util')
const sasl = require('./crypto/sasl')
const TypeOverrides = require('./type-overrides')
const ConnectionParameters = require('./connection-parameters')
const Query = require('./query')
const defaults = require('./defaults')
const Connection = require('./connection')
const crypto = require('./crypto/utils')
const activeQueryDeprecationNotice = nodeUtils.deprecate(
() => {},
'Client.activeQuery is deprecated and will be removed in pg@9.0'
)
const queryQueueDeprecationNotice = nodeUtils.deprecate(
() => {},
'Client.queryQueue is deprecated and will be removed in pg@9.0.'
)
const pgPassDeprecationNotice = nodeUtils.deprecate(
() => {},
'pgpass support is deprecated and will be removed in pg@9.0. ' +
'You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code.'
)
const byoPromiseDeprecationNotice = nodeUtils.deprecate(
() => {},
'Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0.'
)
const queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
() => {},
'Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.'
)
class Client extends EventEmitter {
constructor(config) {
super()
this.connectionParameters = new ConnectionParameters(config)
this.user = this.connectionParameters.user
this.database = this.connectionParameters.database
this.port = this.connectionParameters.port
this.host = this.connectionParameters.host
// "hiding" the password so it doesn't show up in stack traces
// or if the client is console.logged
Object.defineProperty(this, 'password', {
configurable: true,
enumerable: false,
writable: true,
value: this.connectionParameters.password,
})
this.replication = this.connectionParameters.replication
const c = config || {}
if (c.Promise) {
byoPromiseDeprecationNotice()
}
this._Promise = c.Promise || global.Promise
this._types = new TypeOverrides(c.types)
this._ending = false
this._ended = false
this._connecting = false
this._connected = false
this._connectionError = false
this._queryable = true
this._activeQuery = null
this.enableChannelBinding = Boolean(c.enableChannelBinding) // set true to use SCRAM-SHA-256-PLUS when offered
this.connection =
c.connection ||
new Connection({
stream: c.stream,
ssl: this.connectionParameters.ssl,
keepAlive: c.keepAlive || false,
keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0,
encoding: this.connectionParameters.client_encoding || 'utf8',
})
this._queryQueue = []
this.binary = c.binary || defaults.binary
this.processID = null
this.secretKey = null
this.ssl = this.connectionParameters.ssl || false
// As with Password, make SSL->Key (the private key) non-enumerable.
// It won't show up in stack traces
// or if the client is console.logged
if (this.ssl && this.ssl.key) {
Object.defineProperty(this.ssl, 'key', {
enumerable: false,
})
}
this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0
}
get activeQuery() {
activeQueryDeprecationNotice()
return this._activeQuery
}
set activeQuery(val) {
activeQueryDeprecationNotice()
this._activeQuery = val
}
_getActiveQuery() {
return this._activeQuery
}
_errorAllQueries(err) {
const enqueueError = (query) => {
process.nextTick(() => {
query.handleError(err, this.connection)
})
}
const activeQuery = this._getActiveQuery()
if (activeQuery) {
enqueueError(activeQuery)
this._activeQuery = null
}
this._queryQueue.forEach(enqueueError)
this._queryQueue.length = 0
}
_connect(callback) {
const self = this
const con = this.connection
this._connectionCallback = callback
if (this._connecting || this._connected) {
const err = new Error('Client has already been connected. You cannot reuse a client.')
process.nextTick(() => {
callback(err)
})
return
}
this._connecting = true
if (this._connectionTimeoutMillis > 0) {
this.connectionTimeoutHandle = setTimeout(() => {
con._ending = true
con.stream.destroy(new Error('timeout expired'))
}, this._connectionTimeoutMillis)
if (this.connectionTimeoutHandle.unref) {
this.connectionTimeoutHandle.unref()
}
}
if (this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port)
} else {
con.connect(this.port, this.host)
}
// once connection is established send startup message
con.on('connect', function () {
if (self.ssl) {
con.requestSsl()
} else {
con.startup(self.getStartupConf())
}
})
con.on('sslconnect', function () {
con.startup(self.getStartupConf())
})
this._attachListeners(con)
con.once('end', () => {
const error = this._ending ? new Error('Connection terminated') : new Error('Connection terminated unexpectedly')
clearTimeout(this.connectionTimeoutHandle)
this._errorAllQueries(error)
this._ended = true
if (!this._ending) {
// if the connection is ended without us calling .end()
// on this client then we have an unexpected disconnection
// treat this as an error unless we've already emitted an error
// during connection.
if (this._connecting && !this._connectionError) {
if (this._connectionCallback) {
this._connectionCallback(error)
} else {
this._handleErrorEvent(error)
}
} else if (!this._connectionError) {
this._handleErrorEvent(error)
}
}
process.nextTick(() => {
this.emit('end')
})
})
}
connect(callback) {
if (callback) {
this._connect(callback)
return
}
return new this._Promise((resolve, reject) => {
this._connect((error) => {
if (error) {
reject(error)
} else {
resolve(this)
}
})
})
}
_attachListeners(con) {
// password request handling
con.on('authenticationCleartextPassword', this._handleAuthCleartextPassword.bind(this))
// password request handling
con.on('authenticationMD5Password', this._handleAuthMD5Password.bind(this))
// password request handling (SASL)
con.on('authenticationSASL', this._handleAuthSASL.bind(this))
con.on('authenticationSASLContinue', this._handleAuthSASLContinue.bind(this))
con.on('authenticationSASLFinal', this._handleAuthSASLFinal.bind(this))
con.on('backendKeyData', this._handleBackendKeyData.bind(this))
con.on('error', this._handleErrorEvent.bind(this))
con.on('errorMessage', this._handleErrorMessage.bind(this))
con.on('readyForQuery', this._handleReadyForQuery.bind(this))
con.on('notice', this._handleNotice.bind(this))
con.on('rowDescription', this._handleRowDescription.bind(this))
con.on('dataRow', this._handleDataRow.bind(this))
con.on('portalSuspended', this._handlePortalSuspended.bind(this))
con.on('emptyQuery', this._handleEmptyQuery.bind(this))
con.on('commandComplete', this._handleCommandComplete.bind(this))
con.on('parseComplete', this._handleParseComplete.bind(this))
con.on('copyInResponse', this._handleCopyInResponse.bind(this))
con.on('copyData', this._handleCopyData.bind(this))
con.on('notification', this._handleNotification.bind(this))
}
_getPassword(cb) {
const con = this.connection
if (typeof this.password === 'function') {
this._Promise
.resolve()
.then(() => this.password(this.connectionParameters))
.then((pass) => {
if (pass !== undefined) {
if (typeof pass !== 'string') {
con.emit('error', new TypeError('Password must be a string'))
return
}
this.connectionParameters.password = this.password = pass
} else {
this.connectionParameters.password = this.password = null
}
cb()
})
.catch((err) => {
con.emit('error', err)
})
} else if (this.password !== null) {
cb()
} else {
try {
const pgPass = require('pgpass')
pgPass(this.connectionParameters, (pass) => {
if (undefined !== pass) {
pgPassDeprecationNotice()
this.connectionParameters.password = this.password = pass
}
cb()
})
} catch (e) {
this.emit('error', e)
}
}
}
_handleAuthCleartextPassword(msg) {
this._getPassword(() => {
this.connection.password(this.password)
})
}
_handleAuthMD5Password(msg) {
this._getPassword(async () => {
try {
const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt)
this.connection.password(hashedPassword)
} catch (e) {
this.emit('error', e)
}
})
}
_handleAuthSASL(msg) {
this._getPassword(() => {
try {
this.saslSession = sasl.startSession(msg.mechanisms, this.enableChannelBinding && this.connection.stream)
this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response)
} catch (err) {
this.connection.emit('error', err)
}
})
}
async _handleAuthSASLContinue(msg) {
try {
await sasl.continueSession(
this.saslSession,
this.password,
msg.data,
this.enableChannelBinding && this.connection.stream
)
this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)
} catch (err) {
this.connection.emit('error', err)
}
}
_handleAuthSASLFinal(msg) {
try {
sasl.finalizeSession(this.saslSession, msg.data)
this.saslSession = null
} catch (err) {
this.connection.emit('error', err)
}
}
_handleBackendKeyData(msg) {
this.processID = msg.processID
this.secretKey = msg.secretKey
}
_handleReadyForQuery(msg) {
if (this._connecting) {
this._connecting = false
this._connected = true
clearTimeout(this.connectionTimeoutHandle)
// process possible callback argument to Client#connect
if (this._connectionCallback) {
this._connectionCallback(null, this)
// remove callback for proper error handling
// after the connect event
this._connectionCallback = null
}
this.emit('connect')
}
const activeQuery = this._getActiveQuery()
this._activeQuery = null
this.readyForQuery = true
if (activeQuery) {
activeQuery.handleReadyForQuery(this.connection)
}
this._pulseQueryQueue()
}
// if we receive an error event or error message
// during the connection process we handle it here
_handleErrorWhileConnecting(err) {
if (this._connectionError) {
// TODO(bmc): this is swallowing errors - we shouldn't do this
return
}
this._connectionError = true
clearTimeout(this.connectionTimeoutHandle)
if (this._connectionCallback) {
return this._connectionCallback(err)
}
this.emit('error', err)
}
// if we're connected and we receive an error event from the connection
// this means the socket is dead - do a hard abort of all queries and emit
// the socket error on the client as well
_handleErrorEvent(err) {
if (this._connecting) {
return this._handleErrorWhileConnecting(err)
}
this._queryable = false
this._errorAllQueries(err)
this.emit('error', err)
}
// handle error messages from the postgres backend
_handleErrorMessage(msg) {
if (this._connecting) {
return this._handleErrorWhileConnecting(msg)
}
const activeQuery = this._getActiveQuery()
if (!activeQuery) {
this._handleErrorEvent(msg)
return
}
this._activeQuery = null
activeQuery.handleError(msg, this.connection)
}
_handleRowDescription(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected rowDescription message from backend.')
this._handleErrorEvent(error)
return
}
// delegate rowDescription to active query
activeQuery.handleRowDescription(msg)
}
_handleDataRow(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected dataRow message from backend.')
this._handleErrorEvent(error)
return
}
// delegate dataRow to active query
activeQuery.handleDataRow(msg)
}
_handlePortalSuspended(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected portalSuspended message from backend.')
this._handleErrorEvent(error)
return
}
// delegate portalSuspended to active query
activeQuery.handlePortalSuspended(this.connection)
}
_handleEmptyQuery(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected emptyQuery message from backend.')
this._handleErrorEvent(error)
return
}
// delegate emptyQuery to active query
activeQuery.handleEmptyQuery(this.connection)
}
_handleCommandComplete(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected commandComplete message from backend.')
this._handleErrorEvent(error)
return
}
// delegate commandComplete to active query
activeQuery.handleCommandComplete(msg, this.connection)
}
_handleParseComplete() {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected parseComplete message from backend.')
this._handleErrorEvent(error)
return
}
// if a prepared statement has a name and properly parses
// we track that its already been executed so we don't parse
// it again on the same client
if (activeQuery.name) {
this.connection.parsedStatements[activeQuery.name] = activeQuery.text
}
}
_handleCopyInResponse(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected copyInResponse message from backend.')
this._handleErrorEvent(error)
return
}
activeQuery.handleCopyInResponse(this.connection)
}
_handleCopyData(msg) {
const activeQuery = this._getActiveQuery()
if (activeQuery == null) {
const error = new Error('Received unexpected copyData message from backend.')
this._handleErrorEvent(error)
return
}
activeQuery.handleCopyData(msg, this.connection)
}
_handleNotification(msg) {
this.emit('notification', msg)
}
_handleNotice(msg) {
this.emit('notice', msg)
}
getStartupConf() {
const params = this.connectionParameters
const data = {
user: params.user,
database: params.database,
}
const appName = params.application_name || params.fallback_application_name
if (appName) {
data.application_name = appName
}
if (params.replication) {
data.replication = '' + params.replication
}
if (params.statement_timeout) {
data.statement_timeout = String(parseInt(params.statement_timeout, 10))
}
if (params.lock_timeout) {
data.lock_timeout = String(parseInt(params.lock_timeout, 10))
}
if (params.idle_in_transaction_session_timeout) {
data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10))
}
if (params.options) {
data.options = params.options
}
return data
}
cancel(client, query) {
if (client.activeQuery === query) {
const con = this.connection
if (this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port)
} else {
con.connect(this.port, this.host)
}
// once connection is established send cancel message
con.on('connect', function () {
con.cancel(client.processID, client.secretKey)
})
} else if (client._queryQueue.indexOf(query) !== -1) {
client._queryQueue.splice(client._queryQueue.indexOf(query), 1)
}
}
setTypeParser(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn)
}
getTypeParser(oid, format) {
return this._types.getTypeParser(oid, format)
}
// escapeIdentifier and escapeLiteral moved to utility functions & exported
// on PG
// re-exported here for backwards compatibility
escapeIdentifier(str) {
return utils.escapeIdentifier(str)
}
escapeLiteral(str) {
return utils.escapeLiteral(str)
}
_pulseQueryQueue() {
if (this.readyForQuery === true) {
this._activeQuery = this._queryQueue.shift()
const activeQuery = this._getActiveQuery()
if (activeQuery) {
this.readyForQuery = false
this.hasExecuted = true
const queryError = activeQuery.submit(this.connection)
if (queryError) {
process.nextTick(() => {
activeQuery.handleError(queryError, this.connection)
this.readyForQuery = true
this._pulseQueryQueue()
})
}
} else if (this.hasExecuted) {
this._activeQuery = null
this.emit('drain')
}
}
}
query(config, values, callback) {
// can take in strings, config object or query object
let query
let result
let readTimeout
let readTimeoutTimer
let queryCallback
if (config === null || config === undefined) {
throw new TypeError('Client was passed a null or undefined query')
} else if (typeof config.submit === 'function') {
readTimeout = config.query_timeout || this.connectionParameters.query_timeout
result = query = config
if (!query.callback) {
if (typeof values === 'function') {
query.callback = values
} else if (callback) {
query.callback = callback
}
}
} else {
readTimeout = config.query_timeout || this.connectionParameters.query_timeout
query = new Query(config, values, callback)
if (!query.callback) {
result = new this._Promise((resolve, reject) => {
query.callback = (err, res) => (err ? reject(err) : resolve(res))
}).catch((err) => {
// replace the stack trace that leads to `TCP.onStreamRead` with one that leads back to the
// application that created the query
Error.captureStackTrace(err)
throw err
})
}
}
if (readTimeout) {
queryCallback = query.callback || (() => {})
readTimeoutTimer = setTimeout(() => {
const error = new Error('Query read timeout')
process.nextTick(() => {
query.handleError(error, this.connection)
})
queryCallback(error)
// we already returned an error,
// just do nothing if query completes
query.callback = () => {}
// Remove from queue
const index = this._queryQueue.indexOf(query)
if (index > -1) {
this._queryQueue.splice(index, 1)
}
this._pulseQueryQueue()
}, readTimeout)
query.callback = (err, res) => {
clearTimeout(readTimeoutTimer)
queryCallback(err, res)
}
}
if (this.binary && !query.binary) {
query.binary = true
}
if (query._result && !query._result._types) {
query._result._types = this._types
}
if (!this._queryable) {
process.nextTick(() => {
query.handleError(new Error('Client has encountered a connection error and is not queryable'), this.connection)
})
return result
}
if (this._ending) {
process.nextTick(() => {
query.handleError(new Error('Client was closed and is not queryable'), this.connection)
})
return result
}
if (this._queryQueue.length > 0) {
queryQueueLengthDeprecationNotice()
}
this._queryQueue.push(query)
this._pulseQueryQueue()
return result
}
ref() {
this.connection.ref()
}
unref() {
this.connection.unref()
}
end(cb) {
this._ending = true
// if we have never connected, then end is a noop, callback immediately
if (!this.connection._connecting || this._ended) {
if (cb) {
cb()
} else {
return this._Promise.resolve()
}
}
if (this._getActiveQuery() || !this._queryable) {
// if we have an active query we need to force a disconnect
// on the socket - otherwise a hung query could block end forever
this.connection.stream.destroy()
} else {
this.connection.end()
}
if (cb) {
this.connection.once('end', cb)
} else {
return new this._Promise((resolve) => {
this.connection.once('end', resolve)
})
}
}
get queryQueue() {
queryQueueDeprecationNotice()
return this._queryQueue
}
}
// expose a Query constructor
Client.Query = Query
module.exports = Client
================================================
FILE: packages/pg/lib/connection-parameters.js
================================================
'use strict'
const dns = require('dns')
const defaults = require('./defaults')
const parse = require('pg-connection-string').parse // parses a connection string
const val = function (key, config, envVar) {
if (config[key]) {
return config[key]
}
if (envVar === undefined) {
envVar = process.env['PG' + key.toUpperCase()]
} else if (envVar === false) {
// do nothing ... use false
} else {
envVar = process.env[envVar]
}
return envVar || defaults[key]
}
const readSSLConfigFromEnvironment = function () {
switch (process.env.PGSSLMODE) {
case 'disable':
return false
case 'prefer':
case 'require':
case 'verify-ca':
case 'verify-full':
return true
case 'no-verify':
return { rejectUnauthorized: false }
}
return defaults.ssl
}
// Convert arg to a string, surround in single quotes, and escape single quotes and backslashes
const quoteParamValue = function (value) {
return "'" + ('' + value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"
}
const add = function (params, config, paramName) {
const value = config[paramName]
if (value !== undefined && value !== null) {
params.push(paramName + '=' + quoteParamValue(value))
}
}
class ConnectionParameters {
constructor(config) {
// if a string is passed, it is a raw connection string so we parse it into a config
config = typeof config === 'string' ? parse(config) : config || {}
// if the config has a connectionString defined, parse IT into the config we use
// this will override other default values with what is stored in connectionString
if (config.connectionString) {
config = Object.assign({}, config, parse(config.connectionString))
}
this.user = val('user', config)
this.database = val('database', config)
if (this.database === undefined) {
this.database = this.user
}
this.port = parseInt(val('port', config), 10)
this.host = val('host', config)
// "hiding" the password so it doesn't show up in stack traces
// or if the client is console.logged
Object.defineProperty(this, 'password', {
configurable: true,
enumerable: false,
writable: true,
value: val('password', config),
})
this.binary = val('binary', config)
this.options = val('options', config)
this.ssl = typeof config.ssl === 'undefined' ? readSSLConfigFromEnvironment() : config.ssl
if (typeof this.ssl === 'string') {
if (this.ssl === 'true') {
this.ssl = true
}
}
// support passing in ssl=no-verify via connection string
if (this.ssl === 'no-verify') {
this.ssl = { rejectUnauthorized: false }
}
if (this.ssl && this.ssl.key) {
Object.defineProperty(this.ssl, 'key', {
enumerable: false,
})
}
this.client_encoding = val('client_encoding', config)
this.replication = val('replication', config)
// a domain socket begins with '/'
this.isDomainSocket = !(this.host || '').indexOf('/')
this.application_name = val('application_name', config, 'PGAPPNAME')
this.fallback_application_name = val('fallback_application_name', config, false)
this.statement_timeout = val('statement_timeout', config, false)
this.lock_timeout = val('lock_timeout', config, false)
this.idle_in_transaction_session_timeout = val('idle_in_transaction_session_timeout', config, false)
this.query_timeout = val('query_timeout', config, false)
if (config.connectionTimeoutMillis === undefined) {
this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0
} else {
this.connect_timeout = Math.floor(config.connectionTimeoutMillis / 1000)
}
if (config.keepAlive === false) {
this.keepalives = 0
} else if (config.keepAlive === true) {
this.keepalives = 1
}
if (typeof config.keepAliveInitialDelayMillis === 'number') {
this.keepalives_idle = Math.floor(config.keepAliveInitialDelayMillis / 1000)
}
}
getLibpqConnectionString(cb) {
const params = []
add(params, this, 'user')
add(params, this, 'password')
add(params, this, 'port')
add(params, this, 'application_name')
add(params, this, 'fallback_application_name')
add(params, this, 'connect_timeout')
add(params, this, 'options')
const ssl = typeof this.ssl === 'object' ? this.ssl : this.ssl ? { sslmode: this.ssl } : {}
add(params, ssl, 'sslmode')
add(params, ssl, 'sslca')
add(params, ssl, 'sslkey')
add(params, ssl, 'sslcert')
add(params, ssl, 'sslrootcert')
if (this.database) {
params.push('dbname=' + quoteParamValue(this.database))
}
if (this.replication) {
params.push('replication=' + quoteParamValue(this.replication))
}
if (this.host) {
params.push('host=' + quoteParamValue(this.host))
}
if (this.isDomainSocket) {
return cb(null, params.join(' '))
}
if (this.client_encoding) {
params.push('client_encoding=' + quoteParamValue(this.client_encoding))
}
dns.lookup(this.host, function (err, address) {
if (err) return cb(err, null)
params.push('hostaddr=' + quoteParamValue(address))
return cb(null, params.join(' '))
})
}
}
module.exports = ConnectionParameters
================================================
FILE: packages/pg/lib/connection.js
================================================
'use strict'
const EventEmitter = require('events').EventEmitter
const { parse, serialize } = require('pg-protocol')
const { getStream, getSecureStream } = require('./stream')
const flushBuffer = serialize.flush()
const syncBuffer = serialize.sync()
const endBuffer = serialize.end()
// TODO(bmc) support binary mode at some point
class Connection extends EventEmitter {
constructor(config) {
super()
config = config || {}
this.stream = config.stream || getStream(config.ssl)
if (typeof this.stream === 'function') {
this.stream = this.stream(config)
}
this._keepAlive = config.keepAlive
this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis
this.parsedStatements = {}
this.ssl = config.ssl || false
this._ending = false
this._emitMessage = false
const self = this
this.on('newListener', function (eventName) {
if (eventName === 'message') {
self._emitMessage = true
}
})
}
connect(port, host) {
const self = this
this._connecting = true
this.stream.setNoDelay(true)
this.stream.connect(port, host)
this.stream.once('connect', function () {
if (self._keepAlive) {
self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis)
}
self.emit('connect')
})
const reportStreamError = function (error) {
// errors about disconnections should be ignored during disconnect
if (self._ending && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
return
}
self.emit('error', error)
}
this.stream.on('error', reportStreamError)
this.stream.on('close', function () {
self.emit('end')
})
if (!this.ssl) {
return this.attachListeners(this.stream)
}
this.stream.once('data', function (buffer) {
const responseCode = buffer.toString('utf8')
switch (responseCode) {
case 'S': // Server supports SSL connections, continue with a secure connection
break
case 'N': // Server does not support SSL connections
self.stream.end()
return self.emit('error', new Error('The server does not support SSL connections'))
default:
// Any other response byte, including 'E' (ErrorResponse) indicating a server error
self.stream.end()
return self.emit('error', new Error('There was an error establishing an SSL connection'))
}
const options = {
socket: self.stream,
}
if (self.ssl !== true) {
Object.assign(options, self.ssl)
if ('key' in self.ssl) {
options.key = self.ssl.key
}
}
const net = require('net')
if (net.isIP && net.isIP(host) === 0) {
options.servername = host
}
try {
self.stream = getSecureStream(options)
} catch (err) {
return self.emit('error', err)
}
self.attachListeners(self.stream)
self.stream.on('error', reportStreamError)
self.emit('sslconnect')
})
}
attachListeners(stream) {
parse(stream, (msg) => {
const eventName = msg.name === 'error' ? 'errorMessage' : msg.name
if (this._emitMessage) {
this.emit('message', msg)
}
this.emit(eventName, msg)
})
}
requestSsl() {
this.stream.write(serialize.requestSsl())
}
startup(config) {
this.stream.write(serialize.startup(config))
}
cancel(processID, secretKey) {
this._send(serialize.cancel(processID, secretKey))
}
password(password) {
this._send(serialize.password(password))
}
sendSASLInitialResponseMessage(mechanism, initialResponse) {
this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse))
}
sendSCRAMClientFinalMessage(additionalData) {
this._send(serialize.sendSCRAMClientFinalMessage(additionalData))
}
_send(buffer) {
if (!this.stream.writable) {
return false
}
return this.stream.write(buffer)
}
query(text) {
this._send(serialize.query(text))
}
// send parse message
parse(query) {
this._send(serialize.parse(query))
}
// send bind message
bind(config) {
this._send(serialize.bind(config))
}
// send execute message
execute(config) {
this._send(serialize.execute(config))
}
flush() {
if (this.stream.writable) {
this.stream.write(flushBuffer)
}
}
sync() {
this._ending = true
this._send(syncBuffer)
}
ref() {
this.stream.ref()
}
unref() {
this.stream.unref()
}
end() {
// 0x58 = 'X'
this._ending = true
if (!this._connecting || !this.stream.writable) {
this.stream.end()
return
}
return this.stream.write(endBuffer, () => {
this.stream.end()
})
}
close(msg) {
this._send(serialize.close(msg))
}
describe(msg) {
this._send(serialize.describe(msg))
}
sendCopyFromChunk(chunk) {
this._send(serialize.copyData(chunk))
}
endCopyFrom() {
this._send(serialize.copyDone())
}
sendCopyFail(msg) {
this._send(serialize.copyFail(msg))
}
}
module.exports = Connection
================================================
FILE: packages/pg/lib/crypto/cert-signatures.js
================================================
function x509Error(msg, cert) {
return new Error('SASL channel binding: ' + msg + ' when parsing public certificate ' + cert.toString('base64'))
}
function readASN1Length(data, index) {
let length = data[index++]
if (length < 0x80) return { length, index }
const lengthBytes = length & 0x7f
if (lengthBytes > 4) throw x509Error('bad length', data)
length = 0
for (let i = 0; i < lengthBytes; i++) {
length = (length << 8) | data[index++]
}
return { length, index }
}
function readASN1OID(data, index) {
if (data[index++] !== 0x6) throw x509Error('non-OID data', data) // 6 = OID
const { length: OIDLength, index: indexAfterOIDLength } = readASN1Length(data, index)
index = indexAfterOIDLength
const lastIndex = index + OIDLength
const byte1 = data[index++]
let oid = ((byte1 / 40) >> 0) + '.' + (byte1 % 40)
while (index < lastIndex) {
// loop over numbers in OID
let value = 0
while (index < lastIndex) {
// loop over bytes in number
const nextByte = data[index++]
value = (value << 7) | (nextByte & 0x7f)
if (nextByte < 0x80) break
}
oid += '.' + value
}
return { oid, index }
}
function expectASN1Seq(data, index) {
if (data[index++] !== 0x30) throw x509Error('non-sequence data', data) // 30 = Sequence
return readASN1Length(data, index)
}
function signatureAlgorithmHashFromCertificate(data, index) {
// read this thread: https://www.postgresql.org/message-id/17760-b6c61e752ec07060%40postgresql.org
if (index === undefined) index = 0
index = expectASN1Seq(data, index).index
const { length: certInfoLength, index: indexAfterCertInfoLength } = expectASN1Seq(data, index)
index = indexAfterCertInfoLength + certInfoLength // skip over certificate info
index = expectASN1Seq(data, index).index // skip over signature length field
const { oid, index: indexAfterOID } = readASN1OID(data, index)
switch (oid) {
// RSA
case '1.2.840.113549.1.1.4':
return 'MD5'
case '1.2.840.113549.1.1.5':
return 'SHA-1'
case '1.2.840.113549.1.1.11':
return 'SHA-256'
case '1.2.840.113549.1.1.12':
return 'SHA-384'
case '1.2.840.113549.1.1.13':
return 'SHA-512'
case '1.2.840.113549.1.1.14':
return 'SHA-224'
case '1.2.840.113549.1.1.15':
return 'SHA512-224'
case '1.2.840.113549.1.1.16':
return 'SHA512-256'
// ECDSA
case '1.2.840.10045.4.1':
return 'SHA-1'
case '1.2.840.10045.4.3.1':
return 'SHA-224'
case '1.2.840.10045.4.3.2':
return 'SHA-256'
case '1.2.840.10045.4.3.3':
return 'SHA-384'
case '1.2.840.10045.4.3.4':
return 'SHA-512'
// RSASSA-PSS: hash is indicated separately
case '1.2.840.113549.1.1.10': {
index = indexAfterOID
index = expectASN1Seq(data, index).index
if (data[index++] !== 0xa0) throw x509Error('non-tag data', data) // a0 = constructed tag 0
index = readASN1Length(data, index).index // skip over tag length field
index = expectASN1Seq(data, index).index // skip over sequence length field
const { oid: hashOID } = readASN1OID(data, index)
switch (hashOID) {
// standalone hash OIDs
case '1.2.840.113549.2.5':
return 'MD5'
case '1.3.14.3.2.26':
return 'SHA-1'
case '2.16.840.1.101.3.4.2.1':
return 'SHA-256'
case '2.16.840.1.101.3.4.2.2':
return 'SHA-384'
case '2.16.840.1.101.3.4.2.3':
return 'SHA-512'
}
throw x509Error('unknown hash OID ' + hashOID, data)
}
// Ed25519 -- see https: return//github.com/openssl/openssl/issues/15477
case '1.3.101.110':
case '1.3.101.112': // ph
return 'SHA-512'
// Ed448 -- still not in pg 17.2 (if supported, digest would be SHAKE256 x 64 bytes)
case '1.3.101.111':
case '1.3.101.113': // ph
throw x509Error('Ed448 certificate channel binding is not currently supported by Postgres')
}
throw x509Error('unknown OID ' + oid, data)
}
module.exports = { signatureAlgorithmHashFromCertificate }
================================================
FILE: packages/pg/lib/crypto/sasl.js
================================================
'use strict'
const crypto = require('./utils')
const { signatureAlgorithmHashFromCertificate } = require('./cert-signatures')
function startSession(mechanisms, stream) {
const candidates = ['SCRAM-SHA-256']
if (stream) candidates.unshift('SCRAM-SHA-256-PLUS') // higher-priority, so placed first
const mechanism = candidates.find((candidate) => mechanisms.includes(candidate))
if (!mechanism) {
throw new Error('SASL: Only mechanism(s) ' + candidates.join(' and ') + ' are supported')
}
if (mechanism === 'SCRAM-SHA-256-PLUS' && typeof stream.getPeerCertificate !== 'function') {
// this should never happen if we are really talking to a Postgres server
throw new Error('SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate')
}
const clientNonce = crypto.randomBytes(18).toString('base64')
const gs2Header = mechanism === 'SCRAM-SHA-256-PLUS' ? 'p=tls-server-end-point' : stream ? 'y' : 'n'
return {
mechanism,
clientNonce,
response: gs2Header + ',,n=*,r=' + clientNonce,
message: 'SASLInitialResponse',
}
}
async function continueSession(session, password, serverData, stream) {
if (session.message !== 'SASLInitialResponse') {
throw new Error('SASL: Last message was not SASLInitialResponse')
}
if (typeof password !== 'string') {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')
}
if (password === '') {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string')
}
if (typeof serverData !== 'string') {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string')
}
const sv = parseServerFirstMessage(serverData)
if (!sv.nonce.startsWith(session.clientNonce)) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce')
} else if (sv.nonce.length === session.clientNonce.length) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short')
}
const clientFirstMessageBare = 'n=*,r=' + session.clientNonce
const serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration
// without channel binding:
let channelBinding = stream ? 'eSws' : 'biws' // 'y,,' or 'n,,', base64-encoded
// override if channel binding is in use:
if (session.mechanism === 'SCRAM-SHA-256-PLUS') {
const peerCert = stream.getPeerCertificate().raw
let hashName = signatureAlgorithmHashFromCertificate(peerCert)
if (hashName === 'MD5' || hashName === 'SHA-1') hashName = 'SHA-256'
const certHash = await crypto.hashByName(hashName, peerCert)
const bindingData = Buffer.concat([Buffer.from('p=tls-server-end-point,,'), Buffer.from(certHash)])
channelBinding = bindingData.toString('base64')
}
const clientFinalMessageWithoutProof = 'c=' + channelBinding + ',r=' + sv.nonce
const authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof
const saltBytes = Buffer.from(sv.salt, 'base64')
const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration)
const clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key')
const storedKey = await crypto.sha256(clientKey)
const clientSignature = await crypto.hmacSha256(storedKey, authMessage)
const clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString('base64')
const serverKey = await crypto.hmacSha256(saltedPassword, 'Server Key')
const serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage)
session.message = 'SASLResponse'
session.serverSignature = Buffer.from(serverSignatureBytes).toString('base64')
session.response = clientFinalMessageWithoutProof + ',p=' + clientProof
}
function finalizeSession(session, serverData) {
if (session.message !== 'SASLResponse') {
throw new Error('SASL: Last message was not SASLResponse')
}
if (typeof serverData !== 'string') {
throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string')
}
const { serverSignature } = parseServerFinalMessage(serverData)
if (serverSignature !== session.serverSignature) {
throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match')
}
}
/**
* printable = %x21-2B / %x2D-7E
* ;; Printable ASCII except ",".
* ;; Note that any "printable" is also
* ;; a valid "value".
*/
function isPrintableChars(text) {
if (typeof text !== 'string') {
throw new TypeError('SASL: text must be a string')
}
return text
.split('')
.map((_, i) => text.charCodeAt(i))
.every((c) => (c >= 0x21 && c <= 0x2b) || (c >= 0x2d && c <= 0x7e))
}
/**
* base64-char = ALPHA / DIGIT / "/" / "+"
*
* base64-4 = 4base64-char
*
* base64-3 = 3base64-char "="
*
* base64-2 = 2base64-char "=="
*
* base64 = *base64-4 [base64-3 / base64-2]
*/
function isBase64(text) {
return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text)
}
function parseAttributePairs(text) {
if (typeof text !== 'string') {
throw new TypeError('SASL: attribute pairs text must be a string')
}
return new Map(
text.split(',').map((attrValue) => {
if (!/^.=/.test(attrValue)) {
throw new Error('SASL: Invalid attribute pair entry')
}
const name = attrValue[0]
const value = attrValue.substring(2)
return [name, value]
})
)
}
function parseServerFirstMessage(data) {
const attrPairs = parseAttributePairs(data)
const nonce = attrPairs.get('r')
if (!nonce) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing')
} else if (!isPrintableChars(nonce)) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters')
}
const salt = attrPairs.get('s')
if (!salt) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing')
} else if (!isBase64(salt)) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64')
}
const iterationText = attrPairs.get('i')
if (!iterationText) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing')
} else if (!/^[1-9][0-9]*$/.test(iterationText)) {
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count')
}
const iteration = parseInt(iterationText, 10)
return {
nonce,
salt,
iteration,
}
}
function parseServerFinalMessage(serverData) {
const attrPairs = parseAttributePairs(serverData)
const serverSignature = attrPairs.get('v')
if (!serverSignature) {
throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing')
} else if (!isBase64(serverSignature)) {
throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64')
}
return {
serverSignature,
}
}
function xorBuffers(a, b) {
if (!Buffer.isBuffer(a)) {
throw new TypeError('first argument must be a Buffer')
}
if (!Buffer.isBuffer(b)) {
throw new TypeError('second argument must be a Buffer')
}
if (a.length !== b.length) {
throw new Error('Buffer lengths must match')
}
if (a.length === 0) {
throw new Error('Buffers cannot be empty')
}
return Buffer.from(a.map((_, i) => a[i] ^ b[i]))
}
module.exports = {
startSession,
continueSession,
finalizeSession,
}
================================================
FILE: packages/pg/lib/crypto/utils-legacy.js
================================================
'use strict'
// This file contains crypto utility functions for versions of Node.js < 15.0.0,
// which does not support the WebCrypto.subtle API.
const nodeCrypto = require('crypto')
function md5(string) {
return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
}
// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
function postgresMd5PasswordHash(user, password, salt) {
const inner = md5(password + user)
const outer = md5(Buffer.concat([Buffer.from(inner), salt]))
return 'md5' + outer
}
function sha256(text) {
return nodeCrypto.createHash('sha256').update(text).digest()
}
function hashByName(hashName, text) {
hashName = hashName.replace(/(\D)-/, '$1') // e.g. SHA-256 -> SHA256
return nodeCrypto.createHash(hashName).update(text).digest()
}
function hmacSha256(key, msg) {
return nodeCrypto.createHmac('sha256', key).update(msg).digest()
}
async function deriveKey(password, salt, iterations) {
return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, 'sha256')
}
module.exports = {
postgresMd5PasswordHash,
randomBytes: nodeCrypto.randomBytes,
deriveKey,
sha256,
hashByName,
hmacSha256,
md5,
}
================================================
FILE: packages/pg/lib/crypto/utils-webcrypto.js
================================================
const nodeCrypto = require('crypto')
module.exports = {
postgresMd5PasswordHash,
randomBytes,
deriveKey,
sha256,
hashByName,
hmacSha256,
md5,
}
/**
* The Web Crypto API - grabbed from the Node.js library or the global
* @type Crypto
*/
// eslint-disable-next-line no-undef
const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
/**
* The SubtleCrypto API for low level crypto operations.
* @type SubtleCrypto
*/
const subtleCrypto = webCrypto.subtle
const textEncoder = new TextEncoder()
/**
*
* @param {*} length
* @returns
*/
function randomBytes(length) {
return webCrypto.getRandomValues(Buffer.alloc(length))
}
async function md5(string) {
try {
return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
} catch (e) {
// `createHash()` failed so we are probably not in Node.js, use the WebCrypto API instead.
// Note that the MD5 algorithm on WebCrypto is not available in Node.js.
// This is why we cannot just use WebCrypto in all environments.
const data = typeof string === 'string' ? textEncoder.encode(string) : string
const hash = await subtleCrypto.digest('MD5', data)
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
}
// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
async function postgresMd5PasswordHash(user, password, salt) {
const inner = await md5(password + user)
const outer = await md5(Buffer.concat([Buffer.from(inner), salt]))
return 'md5' + outer
}
/**
* Create a SHA-256 digest of the given data
* @param {Buffer} data
*/
async function sha256(text) {
return await subtleCrypto.digest('SHA-256', text)
}
async function hashByName(hashName, text) {
return await subtleCrypto.digest(hashName, text)
}
/**
* Sign the message with the given key
* @param {ArrayBuffer} keyBuffer
* @param {string} msg
*/
async function hmacSha256(keyBuffer, msg) {
const key = await subtleCrypto.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
return await subtleCrypto.sign('HMAC', key, textEncoder.encode(msg))
}
/**
* Derive a key from the password and salt
* @param {string} password
* @param {Uint8Array} salt
* @param {number} iterations
*/
async function deriveKey(password, salt, iterations) {
const key = await subtleCrypto.importKey('raw', textEncoder.encode(password), 'PBKDF2', false, ['deriveBits'])
gitextract_s6gb5la9/ ├── .devcontainer/ │ ├── Dockerfile │ ├── devcontainer.json │ └── docker-compose.yml ├── .eslintignore ├── .eslintrc ├── .gitattributes ├── .github/ │ ├── CODEOWNERS │ ├── FUNDING.yml │ ├── dependabot.yaml │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .yarnrc ├── CHANGELOG.md ├── LICENSE ├── LOCAL_DEV.md ├── README.md ├── SPONSORS.md ├── docs/ │ ├── .gitignore │ ├── README.md │ ├── components/ │ │ ├── alert.tsx │ │ ├── info.tsx │ │ └── logo.tsx │ ├── next.config.js │ ├── package.json │ ├── pages/ │ │ ├── _app.js │ │ ├── _meta.js │ │ ├── announcements.mdx │ │ ├── apis/ │ │ │ ├── _meta.js │ │ │ ├── client.mdx │ │ │ ├── cursor.mdx │ │ │ ├── pool.mdx │ │ │ ├── result.mdx │ │ │ ├── types.mdx │ │ │ └── utilities.mdx │ │ ├── features/ │ │ │ ├── _meta.js │ │ │ ├── callbacks.mdx │ │ │ ├── connecting.mdx │ │ │ ├── esm.mdx │ │ │ ├── native.mdx │ │ │ ├── pooling.mdx │ │ │ ├── queries.mdx │ │ │ ├── ssl.mdx │ │ │ ├── transactions.mdx │ │ │ └── types.mdx │ │ ├── guides/ │ │ │ ├── _meta.js │ │ │ ├── async-express.md │ │ │ ├── pool-sizing.md │ │ │ ├── project-structure.md │ │ │ └── upgrading.md │ │ └── index.mdx │ └── theme.config.js ├── lerna.json ├── package.json ├── packages/ │ ├── pg/ │ │ ├── Makefile │ │ ├── README.md │ │ ├── bench.js │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── lib/ │ │ │ ├── client.js │ │ │ ├── connection-parameters.js │ │ │ ├── connection.js │ │ │ ├── crypto/ │ │ │ │ ├── cert-signatures.js │ │ │ │ ├── sasl.js │ │ │ │ ├── utils-legacy.js │ │ │ │ ├── utils-webcrypto.js │ │ │ │ └── utils.js │ │ │ ├── defaults.js │ │ │ ├── index.js │ │ │ ├── native/ │ │ │ │ ├── client.js │ │ │ │ ├── index.js │ │ │ │ └── query.js │ │ │ ├── query.js │ │ │ ├── result.js │ │ │ ├── stream.js │ │ │ ├── type-overrides.js │ │ │ └── utils.js │ │ ├── package.json │ │ ├── script/ │ │ │ └── dump-db-types.js │ │ └── test/ │ │ ├── buffer-list.js │ │ ├── cloudflare/ │ │ │ └── vitest-cf.test.ts │ │ ├── integration/ │ │ │ ├── client/ │ │ │ │ ├── api-tests.js │ │ │ │ ├── appname-tests.js │ │ │ │ ├── array-tests.js │ │ │ │ ├── async-stack-trace-tests.js │ │ │ │ ├── big-simple-query-tests.js │ │ │ │ ├── configuration-tests.js │ │ │ │ ├── connection-parameter-tests.js │ │ │ │ ├── connection-timeout-tests.js │ │ │ │ ├── custom-types-tests.js │ │ │ │ ├── empty-query-tests.js │ │ │ │ ├── error-handling-tests.js │ │ │ │ ├── field-name-escape-tests.js │ │ │ │ ├── huge-numeric-tests.js │ │ │ │ ├── idle_in_transaction_session_timeout-tests.js │ │ │ │ ├── json-type-parsing-tests.js │ │ │ │ ├── multiple-results-tests.js │ │ │ │ ├── network-partition-tests.js │ │ │ │ ├── no-data-tests.js │ │ │ │ ├── no-row-result-tests.js │ │ │ │ ├── notice-tests.js │ │ │ │ ├── parse-int-8-tests.js │ │ │ │ ├── prepared-statement-tests.js │ │ │ │ ├── promise-api-tests.js │ │ │ │ ├── query-as-promise-tests.js │ │ │ │ ├── query-column-names-tests.js │ │ │ │ ├── query-error-handling-prepared-statement-tests.js │ │ │ │ ├── query-error-handling-tests.js │ │ │ │ ├── quick-disconnect-tests.js │ │ │ │ ├── result-metadata-tests.js │ │ │ │ ├── results-as-array-tests.js │ │ │ │ ├── row-description-on-results-tests.js │ │ │ │ ├── sasl-scram-tests.js │ │ │ │ ├── simple-query-tests.js │ │ │ │ ├── ssl-tests.js │ │ │ │ ├── statement_timeout-tests.js │ │ │ │ ├── test-helper.js │ │ │ │ ├── timezone-tests.js │ │ │ │ ├── transaction-tests.js │ │ │ │ ├── type-coercion-tests.js │ │ │ │ └── type-parser-override-tests.js │ │ │ ├── connection-pool/ │ │ │ │ ├── connection-pool-size-tests.js │ │ │ │ ├── error-tests.js │ │ │ │ ├── idle-timeout-tests.js │ │ │ │ ├── native-instance-tests.js │ │ │ │ ├── test-helper.js │ │ │ │ ├── tls-tests.js │ │ │ │ └── yield-support-tests.js │ │ │ ├── domain-tests.js │ │ │ ├── gh-issues/ │ │ │ │ ├── 1105-tests.js │ │ │ │ ├── 130-tests.js │ │ │ │ ├── 131-tests.js │ │ │ │ ├── 1382-tests.js │ │ │ │ ├── 1542-tests.js │ │ │ │ ├── 1854-tests.js │ │ │ │ ├── 199-tests.js │ │ │ │ ├── 1992-tests.js │ │ │ │ ├── 2056-tests.js │ │ │ │ ├── 2064-tests.js │ │ │ │ ├── 2079-tests.js │ │ │ │ ├── 2085-tests.js │ │ │ │ ├── 2108-tests.js │ │ │ │ ├── 2303-tests.js │ │ │ │ ├── 2307-tests.js │ │ │ │ ├── 2416-tests.js │ │ │ │ ├── 2556-tests.js │ │ │ │ ├── 2627-tests.js │ │ │ │ ├── 2716-tests.js │ │ │ │ ├── 2862-tests.js │ │ │ │ ├── 3062-tests.js │ │ │ │ ├── 3174-tests.js │ │ │ │ ├── 3487-tests.js │ │ │ │ ├── 507-tests.js │ │ │ │ ├── 600-tests.js │ │ │ │ ├── 675-tests.js │ │ │ │ ├── 699-tests.js │ │ │ │ ├── 787-tests.js │ │ │ │ ├── 882-tests.js │ │ │ │ └── 981-tests.js │ │ │ └── test-helper.js │ │ ├── native/ │ │ │ ├── callback-api-tests.js │ │ │ ├── evented-api-tests.js │ │ │ ├── native-connection-string-tests.js │ │ │ ├── native-vs-js-error-tests.js │ │ │ └── stress-tests.js │ │ ├── suite.js │ │ ├── test-buffers.js │ │ ├── test-helper.js │ │ ├── tls/ │ │ │ ├── GNUmakefile │ │ │ ├── test-client-ca.crt │ │ │ ├── test-client-ca.key │ │ │ ├── test-client.crt │ │ │ ├── test-client.key │ │ │ ├── test-server-ca.crt │ │ │ ├── test-server-ca.key │ │ │ ├── test-server.crt │ │ │ └── test-server.key │ │ ├── unit/ │ │ │ ├── client/ │ │ │ │ ├── cleartext-password-tests.js │ │ │ │ ├── configuration-tests.js │ │ │ │ ├── early-disconnect-tests.js │ │ │ │ ├── escape-tests.js │ │ │ │ ├── md5-password-tests.js │ │ │ │ ├── notification-tests.js │ │ │ │ ├── password-callback-tests.js │ │ │ │ ├── pgpass.file │ │ │ │ ├── prepared-statement-tests.js │ │ │ │ ├── query-queue-tests.js │ │ │ │ ├── query-timeout-tests.js │ │ │ │ ├── result-metadata-tests.js │ │ │ │ ├── sasl-scram-tests.js │ │ │ │ ├── set-keepalives-tests.js │ │ │ │ ├── simple-query-tests.js │ │ │ │ ├── stream-and-query-error-interaction-tests.js │ │ │ │ ├── test-helper.js │ │ │ │ └── throw-in-type-parser-tests.js │ │ │ ├── connection/ │ │ │ │ ├── error-tests.js │ │ │ │ ├── startup-tests.js │ │ │ │ └── test-helper.js │ │ │ ├── connection-parameters/ │ │ │ │ ├── creation-tests.js │ │ │ │ └── environment-variable-tests.js │ │ │ ├── connection-pool/ │ │ │ │ └── configuration-tests.js │ │ │ ├── test-helper.js │ │ │ └── utils-tests.js │ │ ├── vitest.config.mts │ │ └── wrangler.jsonc │ ├── pg-bundler-test/ │ │ ├── esbuild-cloudflare.config.mjs │ │ ├── esbuild-empty.config.mjs │ │ ├── package.json │ │ ├── rollup-cloudflare.config.mjs │ │ ├── rollup-empty.config.mjs │ │ ├── src/ │ │ │ └── index.mjs │ │ ├── vite-cloudflare.config.mjs │ │ ├── vite-empty.config.mjs │ │ ├── webpack-cloudflare.config.mjs │ │ └── webpack-empty.config.mjs │ ├── pg-cloudflare/ │ │ ├── README.md │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── package.json │ │ ├── src/ │ │ │ ├── empty.ts │ │ │ ├── index.ts │ │ │ └── types.d.ts │ │ └── tsconfig.json │ ├── pg-connection-string/ │ │ ├── .coveralls.yml │ │ ├── .gitignore │ │ ├── .mocharc.json │ │ ├── LICENSE │ │ ├── README.md │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── index.d.ts │ │ ├── index.js │ │ ├── package.json │ │ ├── test/ │ │ │ ├── clientConfig.ts │ │ │ ├── example.ca │ │ │ ├── example.cert │ │ │ ├── example.key │ │ │ └── parse.ts │ │ └── tsconfig.json │ ├── pg-cursor/ │ │ ├── README.md │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── index.js │ │ ├── package.json │ │ └── test/ │ │ ├── close.js │ │ ├── error-handling.js │ │ ├── index.js │ │ ├── mocha.opts │ │ ├── no-data-handling.js │ │ ├── pool.js │ │ ├── promises.js │ │ ├── query-config.js │ │ └── transactions.js │ ├── pg-esm-test/ │ │ ├── README.md │ │ ├── common-js-imports.test.cjs │ │ ├── package.json │ │ ├── pg-cloudflare.test.js │ │ ├── pg-connection-string.test.js │ │ ├── pg-cursor.test.js │ │ ├── pg-native.test.js │ │ ├── pg-pool.test.js │ │ ├── pg-protocol.test.js │ │ ├── pg-query-stream.test.js │ │ └── pg.test.js │ ├── pg-native/ │ │ ├── README.md │ │ ├── bench/ │ │ │ ├── index.js │ │ │ └── leaks.js │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── index.js │ │ ├── lib/ │ │ │ ├── build-result.js │ │ │ └── copy-stream.js │ │ ├── package.json │ │ └── test/ │ │ ├── array-mode.js │ │ ├── async-workflow.js │ │ ├── cancel.js │ │ ├── connection-errors.js │ │ ├── connection.js │ │ ├── copy-from.js │ │ ├── copy-to.js │ │ ├── custom-types.js │ │ ├── domains.js │ │ ├── empty-query.js │ │ ├── huge-query.js │ │ ├── index.js │ │ ├── load.js │ │ ├── many-connections.js │ │ ├── many-errors.js │ │ ├── mocha.opts │ │ ├── multiple-queries.js │ │ ├── multiple-statement-results.js │ │ ├── notify.js │ │ ├── prepare.js │ │ ├── query-async.js │ │ ├── query-sync.js │ │ └── version.js │ ├── pg-pool/ │ │ ├── LICENSE │ │ ├── README.md │ │ ├── esm/ │ │ │ └── index.mjs │ │ ├── index.js │ │ ├── package.json │ │ └── test/ │ │ ├── connection-strings.js │ │ ├── connection-timeout.js │ │ ├── ending.js │ │ ├── error-handling.js │ │ ├── events.js │ │ ├── idle-timeout-exit.js │ │ ├── idle-timeout.js │ │ ├── index.js │ │ ├── lifecycle-hooks.js │ │ ├── lifetime-timeout.js │ │ ├── logging.js │ │ ├── max-uses.js │ │ ├── releasing-clients.js │ │ ├── setup.js │ │ ├── sizing.js │ │ ├── submittable.js │ │ └── verify.js │ ├── pg-protocol/ │ │ ├── README.md │ │ ├── esm/ │ │ │ └── index.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── b.ts │ │ │ ├── buffer-reader.ts │ │ │ ├── buffer-writer.ts │ │ │ ├── inbound-parser.test.ts │ │ │ ├── index.ts │ │ │ ├── messages.ts │ │ │ ├── outbound-serializer.test.ts │ │ │ ├── parser.ts │ │ │ ├── serializer.ts │ │ │ ├── testing/ │ │ │ │ ├── buffer-list.ts │ │ │ │ └── test-buffers.ts │ │ │ └── types/ │ │ │ └── chunky.d.ts │ │ └── tsconfig.json │ └── pg-query-stream/ │ ├── LICENSE │ ├── README.md │ ├── esm/ │ │ └── index.mjs │ ├── package.json │ ├── src/ │ │ └── index.ts │ ├── test/ │ │ ├── async-iterator.ts │ │ ├── client-options.ts │ │ ├── close.ts │ │ ├── concat.ts │ │ ├── config.ts │ │ ├── empty-query.ts │ │ ├── error.ts │ │ ├── fast-reader.ts │ │ ├── helper.ts │ │ ├── instant.ts │ │ ├── issue-3.ts │ │ ├── passing-options.ts │ │ ├── pauses.ts │ │ ├── pool.ts │ │ ├── slow-reader.ts │ │ ├── stream-tester-timestamp.ts │ │ └── stream-tester.ts │ └── tsconfig.json ├── tea.yaml └── tsconfig.json
SYMBOL INDEX (356 symbols across 49 files)
FILE: docs/components/logo.tsx
type Props (line 1) | type Props = {
function Logo (line 6) | function Logo(props: Props) {
FILE: docs/pages/_app.js
function Nextra (line 3) | function Nextra({ Component, pageProps }) {
FILE: packages/pg-cloudflare/src/index.ts
class CloudflareSocket (line 7) | class CloudflareSocket extends EventEmitter {
method constructor (line 17) | constructor(readonly ssl: boolean) {
method setNoDelay (line 21) | setNoDelay() {
method setKeepAlive (line 24) | setKeepAlive() {
method ref (line 27) | ref() {
method unref (line 30) | unref() {
method connect (line 34) | async connect(port: number, host: string, connectListener?: (...args: ...
method _listen (line 64) | async _listen() {
method _listenOnce (line 78) | async _listenOnce() {
method write (line 85) | write(
method end (line 107) | end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callbac...
method destroy (line 116) | destroy(reason: string) {
method startTls (line 122) | startTls(options: TlsOptions) {
method _addClosedHandler (line 138) | _addClosedHandler() {
function dump (line 154) | function dump(data: unknown) {
function log (line 164) | function log(...args: unknown[]) {
FILE: packages/pg-cloudflare/src/types.d.ts
class Socket (line 2) | class Socket {
type TlsOptions (line 10) | type TlsOptions = {
type SocketAddress (line 14) | type SocketAddress = {
type SocketOptions (line 19) | type SocketOptions = {
FILE: packages/pg-connection-string/index.d.ts
type Options (line 5) | interface Options {
type SSLConfig (line 10) | interface SSLConfig {
type ConnectionOptions (line 17) | interface ConnectionOptions {
FILE: packages/pg-connection-string/index.js
function parse (line 8) | function parse(str, options = {}) {
function toConnectionOptions (line 158) | function toConnectionOptions(sslConfig) {
function toClientConfig (line 173) | function toClientConfig(config) {
function parseIntoClientConfig (line 209) | function parseIntoClientConfig(str) {
function deprecatedSslModeWarning (line 213) | function deprecatedSslModeWarning(sslmode) {
FILE: packages/pg-cursor/index.js
class Cursor (line 10) | class Cursor extends EventEmitter {
method constructor (line 11) | constructor(text, values, config) {
method _ifNoData (line 29) | _ifNoData() {
method _rowDescription (line 37) | _rowDescription() {
method submit (line 43) | submit(connection) {
method _shiftQueue (line 83) | _shiftQueue() {
method _closePortal (line 89) | _closePortal() {
method handleRowDescription (line 107) | handleRowDescription(msg) {
method handleDataRow (line 113) | handleDataRow(msg) {
method _sendRows (line 119) | _sendRows() {
method handleCommandComplete (line 135) | handleCommandComplete(msg) {
method handlePortalSuspended (line 140) | handlePortalSuspended() {
method handleReadyForQuery (line 144) | handleReadyForQuery() {
method handleEmptyQuery (line 150) | handleEmptyQuery() {
method handleError (line 154) | handleError(msg) {
method _getRows (line 189) | _getRows(rows, cb) {
method end (line 203) | end(cb) {
method close (line 211) | close(cb) {
method read (line 234) | read(rows, cb) {
FILE: packages/pg-cursor/test/pool.js
function poolQueryPromise (line 8) | function poolQueryPromise(pool, readRowCount) {
FILE: packages/pg-native/lib/build-result.js
class Result (line 3) | class Result {
method constructor (line 4) | constructor(types, arrayMode) {
method consumeCommand (line 16) | consumeCommand(pq) {
method consumeFields (line 21) | consumeFields(pq) {
method consumeRows (line 39) | consumeRows(pq) {
method consumeRowAsObject (line 47) | consumeRowAsObject(pq, rowIndex) {
method consumeRowAsArray (line 55) | consumeRowAsArray(pq, rowIndex) {
method readValue (line 63) | readValue(pq, rowIndex, colIndex) {
function buildResult (line 72) | function buildResult(pq, types, arrayMode) {
FILE: packages/pg-pool/index.js
class IdleItem (line 12) | class IdleItem {
method constructor (line 13) | constructor(client, idleListener, timeoutId) {
class PendingItem (line 20) | class PendingItem {
method constructor (line 21) | constructor(callback) {
function throwOnDoubleRelease (line 26) | function throwOnDoubleRelease() {
function promisify (line 30) | function promisify(Promise, callback) {
function makeIdleListener (line 51) | function makeIdleListener(pool, client) {
class Pool (line 66) | class Pool extends EventEmitter {
method constructor (line 67) | constructor(options, Client) {
method _promiseTry (line 111) | _promiseTry(f) {
method _isFull (line 119) | _isFull() {
method _isAboveMin (line 123) | _isAboveMin() {
method _pulseQueue (line 127) | _pulseQueue() {
method _remove (line 172) | _remove(client, callback) {
method connect (line 190) | connect(cb) {
method newClient (line 240) | newClient(pendingItem) {
method _afterConnect (line 311) | _afterConnect(client, pendingItem, idleListener) {
method _acquireClient (line 335) | _acquireClient(client, pendingItem, idleListener, isNew) {
method _releaseOnce (line 369) | _releaseOnce(client, idleListener) {
method _release (line 384) | _release(client, idleListener, err) {
method query (line 431) | query(text, values, cb) {
method end (line 488) | end(cb) {
method waitingCount (line 501) | get waitingCount() {
method idleCount (line 505) | get idleCount() {
method expiredCount (line 509) | get expiredCount() {
method totalCount (line 513) | get totalCount() {
FILE: packages/pg-pool/test/error-handling.js
function runErrorQuery (line 16) | function runErrorQuery() {
FILE: packages/pg-pool/test/events.js
function mockClient (line 118) | function mockClient(methods) {
FILE: packages/pg-protocol/esm/index.js
constant SASL (line 6) | const SASL = protocol.SASL
FILE: packages/pg-protocol/src/b.ts
constant LOOPS (line 5) | const LOOPS = 1000
FILE: packages/pg-protocol/src/buffer-reader.ts
class BufferReader (line 1) | class BufferReader {
method constructor (line 7) | constructor(private offset: number = 0) {}
method setBuffer (line 9) | public setBuffer(offset: number, buffer: Buffer): void {
method int16 (line 14) | public int16(): number {
method byte (line 20) | public byte(): number {
method int32 (line 26) | public int32(): number {
method uint32 (line 32) | public uint32(): number {
method string (line 38) | public string(length: number): string {
method cstring (line 44) | public cstring(): string {
method bytes (line 53) | public bytes(length: number): Buffer {
FILE: packages/pg-protocol/src/buffer-writer.ts
class Writer (line 3) | class Writer {
method constructor (line 7) | constructor(private size = 256) {
method ensure (line 11) | private ensure(size: number): void {
method addInt32 (line 23) | public addInt32(num: number): Writer {
method addInt16 (line 32) | public addInt16(num: number): Writer {
method addCString (line 39) | public addCString(string: string): Writer {
method addString (line 53) | public addString(string: string = ''): Writer {
method add (line 61) | public add(otherBuffer: Buffer): Writer {
method join (line 68) | private join(code?: number): Buffer {
method flush (line 78) | public flush(code?: number): Buffer {
FILE: packages/pg-protocol/src/index.ts
function parse (line 5) | function parse(stream: NodeJS.ReadableStream, callback: MessageCallback)...
FILE: packages/pg-protocol/src/messages.ts
type Mode (line 1) | type Mode = 'text' | 'binary'
type MessageName (line 3) | type MessageName =
type BackendMessage (line 32) | interface BackendMessage {
type NoticeOrError (line 77) | interface NoticeOrError {
class DatabaseError (line 97) | class DatabaseError extends Error implements NoticeOrError {
method constructor (line 114) | constructor(
class CopyDataMessage (line 123) | class CopyDataMessage {
method constructor (line 125) | constructor(
class CopyResponse (line 131) | class CopyResponse {
method constructor (line 133) | constructor(
class Field (line 143) | class Field {
method constructor (line 144) | constructor(
class RowDescriptionMessage (line 155) | class RowDescriptionMessage {
method constructor (line 158) | constructor(
class ParameterDescriptionMessage (line 166) | class ParameterDescriptionMessage {
method constructor (line 169) | constructor(
class ParameterStatusMessage (line 177) | class ParameterStatusMessage {
method constructor (line 179) | constructor(
class AuthenticationMD5Password (line 186) | class AuthenticationMD5Password implements BackendMessage {
method constructor (line 188) | constructor(
class BackendKeyDataMessage (line 194) | class BackendKeyDataMessage {
method constructor (line 196) | constructor(
class NotificationResponseMessage (line 203) | class NotificationResponseMessage {
method constructor (line 205) | constructor(
class ReadyForQueryMessage (line 213) | class ReadyForQueryMessage {
method constructor (line 215) | constructor(
class CommandCompleteMessage (line 221) | class CommandCompleteMessage {
method constructor (line 223) | constructor(
class DataRowMessage (line 229) | class DataRowMessage {
method constructor (line 232) | constructor(
class NoticeMessage (line 240) | class NoticeMessage implements BackendMessage, NoticeOrError {
method constructor (line 241) | constructor(
FILE: packages/pg-protocol/src/parser.ts
constant CODE_LENGTH (line 32) | const CODE_LENGTH = 1
constant LEN_LENGTH (line 35) | const LEN_LENGTH = 4
constant HEADER_LENGTH (line 37) | const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH
constant LATEINIT_LENGTH (line 40) | const LATEINIT_LENGTH = -1
type Packet (line 42) | type Packet = {
type StreamOptions (line 49) | type StreamOptions = TransformOptions & {
type MessageCodes (line 53) | const enum MessageCodes {
type MessageCallback (line 78) | type MessageCallback = (msg: BackendMessage) => void
class Parser (line 80) | class Parser {
method constructor (line 87) | constructor(opts?: StreamOptions) {
method parse (line 94) | public parse(buffer: Buffer, callback: MessageCallback) {
method mergeBuffer (line 124) | private mergeBuffer(buffer: Buffer): void {
method handlePacket (line 157) | private handlePacket(offset: number, code: number, length: number, byt...
FILE: packages/pg-protocol/src/serializer.ts
type code (line 3) | const enum code {
type ParseOpts (line 64) | type ParseOpts = {
type ValueMapper (line 102) | type ValueMapper = (param: any, index: number) => any
type BindOpts (line 104) | type BindOpts = {
type ParamType (line 116) | const enum ParamType {
type ExecOpts (line 167) | type ExecOpts = {
type PortalOpts (line 205) | type PortalOpts = {
FILE: packages/pg-protocol/src/testing/buffer-list.ts
class BufferList (line 1) | class BufferList {
method constructor (line 2) | constructor(public buffers: Buffer[] = []) {}
method add (line 4) | public add(buffer: Buffer, front?: boolean) {
method addInt16 (line 9) | public addInt16(val: number, front?: boolean) {
method getByteLength (line 13) | public getByteLength() {
method addInt32 (line 19) | public addInt32(val: number, first?: boolean) {
method addCString (line 26) | public addCString(val: string, front?: boolean) {
method addString (line 34) | public addString(val: string, front?: boolean) {
method addChar (line 41) | public addChar(char: string, first?: boolean) {
method addByte (line 45) | public addByte(byte: number) {
method join (line 49) | public join(appendLength?: boolean, char?: string): Buffer {
FILE: packages/pg-query-stream/src/index.ts
type QueryStreamConfig (line 5) | interface QueryStreamConfig {
class QueryStream (line 12) | class QueryStream extends Readable implements Submittable {
method constructor (line 25) | public constructor(text: string, values?: any[], config: QueryStreamCo...
method submit (line 51) | public submit(connection: Connection): void {
method _destroy (line 55) | public _destroy(_err: Error, cb: Function) {
method _read (line 62) | public _read(size: number) {
FILE: packages/pg-query-stream/test/concat.ts
method transform (line 14) | transform(chunk, _, callback) {
FILE: packages/pg-query-stream/test/pauses.ts
class PauseStream (line 7) | class PauseStream extends Transform {
method constructor (line 8) | constructor() {
method _transform (line 12) | _transform(chunk, encoding, callback): void {
FILE: packages/pg/lib/client.js
class Client (line 39) | class Client extends EventEmitter {
method constructor (line 40) | constructor(config) {
method activeQuery (line 102) | get activeQuery() {
method activeQuery (line 107) | set activeQuery(val) {
method _getActiveQuery (line 112) | _getActiveQuery() {
method _errorAllQueries (line 116) | _errorAllQueries(err) {
method _connect (line 133) | _connect(callback) {
method connect (line 208) | connect(callback) {
method _attachListeners (line 225) | _attachListeners(con) {
method _getPassword (line 250) | _getPassword(cb) {
method _handleAuthCleartextPassword (line 289) | _handleAuthCleartextPassword(msg) {
method _handleAuthMD5Password (line 295) | _handleAuthMD5Password(msg) {
method _handleAuthSASL (line 306) | _handleAuthSASL(msg) {
method _handleAuthSASLContinue (line 317) | async _handleAuthSASLContinue(msg) {
method _handleAuthSASLFinal (line 331) | _handleAuthSASLFinal(msg) {
method _handleBackendKeyData (line 340) | _handleBackendKeyData(msg) {
method _handleReadyForQuery (line 345) | _handleReadyForQuery(msg) {
method _handleErrorWhileConnecting (line 371) | _handleErrorWhileConnecting(err) {
method _handleErrorEvent (line 387) | _handleErrorEvent(err) {
method _handleErrorMessage (line 397) | _handleErrorMessage(msg) {
method _handleRowDescription (line 412) | _handleRowDescription(msg) {
method _handleDataRow (line 423) | _handleDataRow(msg) {
method _handlePortalSuspended (line 434) | _handlePortalSuspended(msg) {
method _handleEmptyQuery (line 445) | _handleEmptyQuery(msg) {
method _handleCommandComplete (line 456) | _handleCommandComplete(msg) {
method _handleParseComplete (line 467) | _handleParseComplete() {
method _handleCopyInResponse (line 482) | _handleCopyInResponse(msg) {
method _handleCopyData (line 492) | _handleCopyData(msg) {
method _handleNotification (line 502) | _handleNotification(msg) {
method _handleNotice (line 506) | _handleNotice(msg) {
method getStartupConf (line 510) | getStartupConf() {
method cancel (line 541) | cancel(client, query) {
method setTypeParser (line 560) | setTypeParser(oid, format, parseFn) {
method getTypeParser (line 564) | getTypeParser(oid, format) {
method escapeIdentifier (line 571) | escapeIdentifier(str) {
method escapeLiteral (line 575) | escapeLiteral(str) {
method _pulseQueryQueue (line 579) | _pulseQueryQueue() {
method query (line 602) | query(config, values, callback) {
method ref (line 698) | ref() {
method unref (line 702) | unref() {
method end (line 706) | end(cb) {
method queryQueue (line 734) | get queryQueue() {
FILE: packages/pg/lib/connection-parameters.js
class ConnectionParameters (line 52) | class ConnectionParameters {
method constructor (line 53) | constructor(config) {
method getLibpqConnectionString (line 131) | getLibpqConnectionString(cb) {
FILE: packages/pg/lib/connection.js
class Connection (line 13) | class Connection extends EventEmitter {
method constructor (line 14) | constructor(config) {
method connect (line 37) | connect(port, host) {
method attachListeners (line 109) | attachListeners(stream) {
method requestSsl (line 119) | requestSsl() {
method startup (line 123) | startup(config) {
method cancel (line 127) | cancel(processID, secretKey) {
method password (line 131) | password(password) {
method sendSASLInitialResponseMessage (line 135) | sendSASLInitialResponseMessage(mechanism, initialResponse) {
method sendSCRAMClientFinalMessage (line 139) | sendSCRAMClientFinalMessage(additionalData) {
method _send (line 143) | _send(buffer) {
method query (line 150) | query(text) {
method parse (line 155) | parse(query) {
method bind (line 160) | bind(config) {
method execute (line 165) | execute(config) {
method flush (line 169) | flush() {
method sync (line 175) | sync() {
method ref (line 180) | ref() {
method unref (line 184) | unref() {
method end (line 188) | end() {
method close (line 200) | close(msg) {
method describe (line 204) | describe(msg) {
method sendCopyFromChunk (line 208) | sendCopyFromChunk(chunk) {
method endCopyFrom (line 212) | endCopyFrom() {
method sendCopyFail (line 216) | sendCopyFail(msg) {
FILE: packages/pg/lib/crypto/cert-signatures.js
function x509Error (line 1) | function x509Error(msg, cert) {
function readASN1Length (line 5) | function readASN1Length(data, index) {
function readASN1OID (line 20) | function readASN1OID(data, index) {
function expectASN1Seq (line 45) | function expectASN1Seq(data, index) {
function signatureAlgorithmHashFromCertificate (line 50) | function signatureAlgorithmHashFromCertificate(data, index) {
FILE: packages/pg/lib/crypto/sasl.js
function startSession (line 5) | function startSession(mechanisms, stream) {
function continueSession (line 31) | async function continueSession(session, password, serverData, stream) {
function finalizeSession (line 86) | function finalizeSession(session, serverData) {
function isPrintableChars (line 107) | function isPrintableChars(text) {
function isBase64 (line 128) | function isBase64(text) {
function parseAttributePairs (line 132) | function parseAttributePairs(text) {
function parseServerFirstMessage (line 149) | function parseServerFirstMessage(data) {
function parseServerFinalMessage (line 179) | function parseServerFinalMessage(serverData) {
function xorBuffers (line 192) | function xorBuffers(a, b) {
FILE: packages/pg/lib/crypto/utils-legacy.js
function md5 (line 7) | function md5(string) {
function postgresMd5PasswordHash (line 12) | function postgresMd5PasswordHash(user, password, salt) {
function sha256 (line 18) | function sha256(text) {
function hashByName (line 22) | function hashByName(hashName, text) {
function hmacSha256 (line 27) | function hmacSha256(key, msg) {
function deriveKey (line 31) | async function deriveKey(password, salt, iterations) {
FILE: packages/pg/lib/crypto/utils-webcrypto.js
function randomBytes (line 31) | function randomBytes(length) {
function md5 (line 35) | async function md5(string) {
function postgresMd5PasswordHash (line 51) | async function postgresMd5PasswordHash(user, password, salt) {
function sha256 (line 61) | async function sha256(text) {
function hashByName (line 65) | async function hashByName(hashName, text) {
function hmacSha256 (line 74) | async function hmacSha256(keyBuffer, msg) {
function deriveKey (line 85) | async function deriveKey(password, salt, iterations) {
FILE: packages/pg/lib/index.js
method constructor (line 15) | constructor(options) {
method get (line 56) | get() {
FILE: packages/pg/lib/query.js
class Query (line 8) | class Query extends EventEmitter {
method constructor (line 9) | constructor(config, values, callback) {
method requiresPreparation (line 35) | requiresPreparation() {
method _checkForMultirow (line 60) | _checkForMultirow() {
method handleRowDescription (line 76) | handleRowDescription(msg) {
method handleDataRow (line 82) | handleDataRow(msg) {
method handleCommandComplete (line 102) | handleCommandComplete(msg, connection) {
method handleEmptyQuery (line 116) | handleEmptyQuery(connection) {
method handleError (line 122) | handleError(err, connection) {
method handleReadyForQuery (line 136) | handleReadyForQuery(con) {
method submit (line 152) | submit(connection) {
method hasBeenParsed (line 185) | hasBeenParsed(connection) {
method handlePortalSuspended (line 189) | handlePortalSuspended(connection) {
method _getRows (line 193) | _getRows(connection, rows) {
method prepare (line 209) | prepare(connection) {
method handleCopyInResponse (line 243) | handleCopyInResponse(connection) {
method handleCopyData (line 247) | handleCopyData(msg, connection) {
FILE: packages/pg/lib/result.js
class Result (line 10) | class Result {
method constructor (line 11) | constructor(rowMode, types) {
method addCommandComplete (line 28) | addCommandComplete(msg) {
method _parseRowAsArray (line 50) | _parseRowAsArray(rowData) {
method parseRow (line 63) | parseRow(rowData) {
method addRow (line 78) | addRow(row) {
method addFields (line 82) | addFields(fieldDescriptions) {
FILE: packages/pg/lib/stream.js
function getNodejsStreamFuncs (line 20) | function getNodejsStreamFuncs() {
function getCloudflareStreamFuncs (line 39) | function getCloudflareStreamFuncs() {
function isCloudflareRuntime (line 60) | function isCloudflareRuntime() {
function getStreamFuncs (line 78) | function getStreamFuncs() {
FILE: packages/pg/lib/type-overrides.js
function TypeOverrides (line 5) | function TypeOverrides(userTypes) {
FILE: packages/pg/lib/utils.js
function escapeElement (line 8) | function escapeElement(elementRepresentation) {
function arrayString (line 17) | function arrayString(val) {
function prepareObject (line 82) | function prepareObject(val, seen) {
function dateToString (line 95) | function dateToString(date) {
function dateToStringUTC (line 129) | function dateToStringUTC(date) {
function normalizeQueryConfig (line 154) | function normalizeQueryConfig(config, values, callback) {
FILE: packages/pg/test/integration/client/appname-tests.js
function getConInfo (line 10) | function getConInfo(override) {
function getAppName (line 14) | function getAppName(conf, cb) {
FILE: packages/pg/test/integration/client/async-stack-trace-tests.js
constant NODE_MAJOR_VERSION (line 13) | const NODE_MAJOR_VERSION = +process.versions.node.split('.')[0]
function innerFunction (line 16) | async function innerFunction() {
function innerFunction (line 32) | async function innerFunction() {
FILE: packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js
function getConInfo (line 10) | function getConInfo(override) {
function testClientVersion (line 14) | function testClientVersion(cb) {
function getIdleTransactionSessionTimeout (line 39) | function getIdleTransactionSessionTimeout(conf, cb) {
FILE: packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js
function killIdleQuery (line 48) | function killIdleQuery(targetQuery, cb) {
FILE: packages/pg/test/integration/client/statement_timeout-tests.js
function getConInfo (line 10) | function getConInfo(override) {
function getStatementTimeout (line 14) | function getStatementTimeout(conf, cb) {
FILE: packages/pg/test/integration/client/type-parser-override-tests.js
function testTypeParser (line 5) | function testTypeParser(client, expectedResult, done) {
FILE: packages/pg/test/integration/gh-issues/1542-tests.js
class SubPool (line 9) | class SubPool extends Pool {}
FILE: packages/pg/test/integration/gh-issues/2556-tests.js
function reuseClient (line 28) | function reuseClient() {
FILE: packages/pg/test/integration/gh-issues/600-tests.js
function createTableFoo (line 9) | function createTableFoo(callback) {
function createTableBar (line 13) | function createTableBar(callback) {
function insertDataFoo (line 17) | function insertDataFoo(callback) {
function insertDataBar (line 28) | function insertDataBar(callback) {
function startTransaction (line 39) | function startTransaction(callback) {
function endTransaction (line 42) | function endTransaction(callback) {
function doTransaction (line 46) | function doTransaction(callback) {
FILE: packages/pg/test/suite.js
class Test (line 10) | class Test {
method constructor (line 11) | constructor(name, cb) {
method run (line 17) | run(cb) {
method _run (line 25) | _run(cb) {
class Suite (line 42) | class Suite {
method constructor (line 43) | constructor(name) {
method run (line 49) | run(test, cb) {
method test (line 74) | test(name, cb) {
method testAsync (line 79) | testAsync(name, cb) {
FILE: packages/pg/test/unit/client/password-callback-tests.js
class Wait (line 6) | class Wait {
method constructor (line 7) | constructor() {
method until (line 13) | until() {
method done (line 17) | done(time) {
FILE: packages/pg/test/unit/client/sasl-scram-tests.js
method getPeerCertificate (line 33) | getPeerCertificate() {}
method getPeerCertificate (line 43) | getPeerCertificate() {}
method getPeerCertificate (line 199) | getPeerCertificate() {}
method getPeerCertificate (line 215) | getPeerCertificate() {
Condensed preview — 353 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (831K chars).
[
{
"path": ".devcontainer/Dockerfile",
"chars": 3206,
"preview": "#-------------------------------------------------------------------------------------------------------------\n# Copyrig"
},
{
"path": ".devcontainer/devcontainer.json",
"chars": 490,
"preview": "// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.\n{\n\t\"name\": \"Node.js 20 "
},
{
"path": ".devcontainer/docker-compose.yml",
"chars": 1738,
"preview": "#-------------------------------------------------------------------------------------------------------------\n# Copyrig"
},
{
"path": ".eslintignore",
"chars": 18,
"preview": "/packages/*/dist/\n"
},
{
"path": ".eslintrc",
"chars": 861,
"preview": "{\n \"plugins\": [\"@typescript-eslint\", \"prettier\"],\n \"parser\": \"@typescript-eslint/parser\",\n \"extends\": [\"eslint:recomm"
},
{
"path": ".gitattributes",
"chars": 18,
"preview": "* text=auto eol=lf"
},
{
"path": ".github/CODEOWNERS",
"chars": 37,
"preview": "/packages/pg-connection-string @hjr3\n"
},
{
"path": ".github/FUNDING.yml",
"chars": 64,
"preview": "# These are supported funding model platforms\n\ngithub: [brianc]\n"
},
{
"path": ".github/dependabot.yaml",
"chars": 108,
"preview": "\nversion: 2\nupdates:\n - package-ecosystem: \"npm\"\n directory: \"/\"\n schedule:\n interval: \"monthly\""
},
{
"path": ".github/workflows/ci.yml",
"chars": 1858,
"preview": "name: CI\n\non: [push, pull_request]\n\npermissions:\n contents: read\n\njobs:\n lint:\n timeout-minutes: 5\n runs-on: ubu"
},
{
"path": ".gitignore",
"chars": 133,
"preview": "*~\nbuild/\n.lock-wscript\n*.log\nnode_modules/\npackage-lock.json\n*.swp\ndist\n.DS_Store\n/.eslintcache\n.vscode/\nmanually-test-"
},
{
"path": ".yarnrc",
"chars": 29,
"preview": "--install.ignore-engines true"
},
{
"path": "CHANGELOG.md",
"chars": 26111,
"preview": "All major and minor releases are briefly explained below.\n\nFor richer information consult the commit log on github with "
},
{
"path": "LICENSE",
"chars": 1077,
"preview": "MIT License\n\nCopyright (c) 2010 - 2021 Brian Carlson\n\nPermission is hereby granted, free of charge, to any person obtain"
},
{
"path": "LOCAL_DEV.md",
"chars": 1041,
"preview": "# Local development\n\nSteps to install and configure Postgres on Mac for developing against locally\n\n1. Install homebrew\n"
},
{
"path": "README.md",
"chars": 6168,
"preview": "# node-postgres\n\n\n<span class"
},
{
"path": "SPONSORS.md",
"chars": 1920,
"preview": "node-postgres is made possible by the helpful contributors from the community as well as the following generous supporte"
},
{
"path": "docs/.gitignore",
"chars": 10,
"preview": ".next\nout\n"
},
{
"path": "docs/README.md",
"chars": 591,
"preview": "# node-postgres docs website\n\nThis is the documentation for node-postgres which is currently hosted at [https://node-pos"
},
{
"path": "docs/components/alert.tsx",
"chars": 175,
"preview": "import { Callout } from 'nextra/components'\n\nexport const Alert = ({ children }) => {\n return (\n <Callout type=\"warn"
},
{
"path": "docs/components/info.tsx",
"chars": 137,
"preview": "import { Callout } from 'nextra/components'\n\nexport const Info = ({ children }) => {\n return <Callout emoji=\"ℹ️\">{child"
},
{
"path": "docs/components/logo.tsx",
"chars": 227,
"preview": "type Props = {\n src: string\n alt?: string\n}\n\nexport function Logo(props: Props) {\n const alt = props.alt || 'Logo'\n "
},
{
"path": "docs/next.config.js",
"chars": 211,
"preview": "import nextra from 'nextra'\n\nconst withNextra = nextra({\n theme: 'nextra-theme-docs',\n themeConfig: './theme.config.js"
},
{
"path": "docs/package.json",
"chars": 422,
"preview": "{\n \"name\": \"docs\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"next.config.js\",\n \"type\": \"module\",\n \"script"
},
{
"path": "docs/pages/_app.js",
"chars": 137,
"preview": "import 'nextra-theme-docs/style.css'\n\nexport default function Nextra({ Component, pageProps }) {\n return <Component {.."
},
{
"path": "docs/pages/_meta.js",
"chars": 88,
"preview": "export default {\n index: 'Welcome',\n announcements: 'Announcements',\n apis: 'API',\n}\n"
},
{
"path": "docs/pages/announcements.mdx",
"chars": 8869,
"preview": "import { Alert } from '/components/alert.tsx'\n\n## 2020-02-25\n\n### pg@8.0 release\n\n`pg@8.0` is [being released](https://g"
},
{
"path": "docs/pages/apis/_meta.js",
"chars": 151,
"preview": "export default {\n client: 'pg.Client',\n pool: 'pg.Pool',\n result: 'pg.Result',\n types: 'pg.Types',\n cursor: 'Cursor"
},
{
"path": "docs/pages/apis/client.mdx",
"chars": 6880,
"preview": "---\ntitle: pg.Client\n---\n\n## new Client\n\n`new Client(config: Config)`\n\nEvery field of the `config` object is entirely op"
},
{
"path": "docs/pages/apis/cursor.mdx",
"chars": 2371,
"preview": "---\ntitle: pg.Cursor\nslug: /apis/cursor\n---\n\nA cursor can be used to efficiently read through large result sets without "
},
{
"path": "docs/pages/apis/pool.mdx",
"chars": 10079,
"preview": "---\ntitle: pg.Pool\n---\n\nimport { Alert } from '/components/alert.tsx'\n\n## new Pool\n\n```ts\nnew Pool(config: Config)\n```\n\n"
},
{
"path": "docs/pages/apis/result.mdx",
"chars": 2857,
"preview": "---\ntitle: pg.Result\nslug: /apis/result\n---\n\nThe `pg.Result` shape is returned for every successful query.\n\n<div classNa"
},
{
"path": "docs/pages/apis/types.mdx",
"chars": 150,
"preview": "---\ntitle: Types\nslug: /apis/types\n---\n\nThese docs are incomplete, for now please reference [pg-types docs](https://gith"
},
{
"path": "docs/pages/apis/utilities.mdx",
"chars": 1476,
"preview": "---\ntitle: Utilities\n---\nimport { Alert } from '/components/alert.tsx'\n\n## Utility Functions\n### pg.escapeIdentifier\n\nEs"
},
{
"path": "docs/pages/features/_meta.js",
"chars": 220,
"preview": "export default {\n connecting: 'Connecting',\n queries: 'Queries',\n pooling: 'Pooling',\n transactions: 'Transactions',"
},
{
"path": "docs/pages/features/callbacks.mdx",
"chars": 947,
"preview": "---\ntitle: Callbacks\n---\n\n## Callback Support\n\n`async` / `await` is the preferred way to write async code these days wit"
},
{
"path": "docs/pages/features/connecting.mdx",
"chars": 4278,
"preview": "---\ntitle: Connecting\n---\n\n## Environment variables\n\nnode-postgres uses the same [environment variables](https://www.pos"
},
{
"path": "docs/pages/features/esm.mdx",
"chars": 940,
"preview": "---\ntitle: ESM\n---\n\n## ESM Support\n\nAs of v8.15.x node-postgres supporters the __ECMAScript Module__ (ESM) format. This "
},
{
"path": "docs/pages/features/native.mdx",
"chars": 2637,
"preview": "---\ntitle: Native Bindings\nslug: /features/native\nmetaTitle: bar\n---\n\nNative bindings between node.js & [libpq](https://"
},
{
"path": "docs/pages/features/pooling.mdx",
"chars": 4083,
"preview": "---\ntitle: Pooling\n---\n\nimport { Alert } from '/components/alert.tsx'\nimport { Info } from '/components/info.tsx'\n\nIf yo"
},
{
"path": "docs/pages/features/queries.mdx",
"chars": 5875,
"preview": "---\ntitle: Queries\nslug: /features/queries\n---\n\nFor the sake of brevity I am using the `client.query` method instead of "
},
{
"path": "docs/pages/features/ssl.mdx",
"chars": 2115,
"preview": "---\ntitle: SSL\nslug: /features/ssl\n---\n\nnode-postgres supports TLS/SSL connections to your PostgreSQL server as long as "
},
{
"path": "docs/pages/features/transactions.mdx",
"chars": 1371,
"preview": "---\ntitle: Transactions\n---\n\nimport { Alert } from '/components/alert.tsx'\n\nTo execute a transaction with node-postgres "
},
{
"path": "docs/pages/features/types.mdx",
"chars": 4258,
"preview": "---\ntitle: Data Types\n---\n\nimport { Alert } from '/components/alert.tsx'\n\nPostgreSQL has a rich system of supported [dat"
},
{
"path": "docs/pages/guides/_meta.js",
"chars": 175,
"preview": "export default {\n 'project-structure': 'Suggested Code Structure',\n 'async-express': 'Express with Async/Await',\n 'po"
},
{
"path": "docs/pages/guides/async-express.md",
"chars": 2311,
"preview": "---\ntitle: Express with async/await\n---\n\nMy preferred way to use node-postgres (and all async code in node.js) is with `"
},
{
"path": "docs/pages/guides/pool-sizing.md",
"chars": 6065,
"preview": "---\ntitle: Pool Sizing\n---\n\nIf you're using a [pool](/apis/pool) in an application with multiple instances of your servi"
},
{
"path": "docs/pages/guides/project-structure.md",
"chars": 5089,
"preview": "---\ntitle: Suggested Project Structure\n---\n\nWhenever I am writing a project & using node-postgres I like to create a fil"
},
{
"path": "docs/pages/guides/upgrading.md",
"chars": 6467,
"preview": "---\ntitle: Upgrading\nslug: /guides/upgrading\n---\n\n## node version support\n\nI have maintained legacy apps in production f"
},
{
"path": "docs/pages/index.mdx",
"chars": 3084,
"preview": "---\ntitle: Welcome\nslug: /\n---\n\nimport { Logo } from '/components/logo.tsx'\n\nnode-postgres is a collection of node.js mo"
},
{
"path": "docs/theme.config.js",
"chars": 3737,
"preview": "// theme.config.js\nexport default {\n project: {\n link: 'https://github.com/brianc/node-postgres',\n },\n twitter: {\n"
},
{
"path": "lerna.json",
"chars": 228,
"preview": "{\n \"packages\": [\"packages/*\"],\n \"npmClient\": \"yarn\",\n \"useWorkspaces\": true,\n \"version\": \"independent\",\n \"command\":"
},
{
"path": "package.json",
"chars": 1127,
"preview": "{\n \"name\": \"node-postgres\",\n \"description\": \"node postgres monorepo\",\n \"main\": \"index.js\",\n \"private\": true,\n \"repo"
},
{
"path": "packages/pg/Makefile",
"chars": 1641,
"preview": "SHELL := /bin/sh\n\nconnectionString=postgres://\n\nparams := $(connectionString)\n\nnode-command := xargs -n 1 -I file node f"
},
{
"path": "packages/pg/README.md",
"chars": 4356,
"preview": "# node-postgres\n\n[](http://travis-ci"
},
{
"path": "packages/pg/bench.js",
"chars": 2879,
"preview": "const pg = require('./lib')\n\nconst params = {\n text: 'select typname, typnamespace, typowner, typlen, typbyval, typcate"
},
{
"path": "packages/pg/esm/index.mjs",
"chars": 579,
"preview": "// ESM wrapper for pg\nimport pg from '../lib/index.js'\n\n// Re-export all the properties\nexport const Client = pg.Client\n"
},
{
"path": "packages/pg/lib/client.js",
"chars": 21824,
"preview": "const EventEmitter = require('events').EventEmitter\nconst utils = require('./utils')\nconst nodeUtils = require('util')\nc"
},
{
"path": "packages/pg/lib/connection-parameters.js",
"chars": 5282,
"preview": "'use strict'\n\nconst dns = require('dns')\n\nconst defaults = require('./defaults')\n\nconst parse = require('pg-connection-s"
},
{
"path": "packages/pg/lib/connection.js",
"chars": 5147,
"preview": "'use strict'\n\nconst EventEmitter = require('events').EventEmitter\n\nconst { parse, serialize } = require('pg-protocol')\nc"
},
{
"path": "packages/pg/lib/crypto/cert-signatures.js",
"chars": 4096,
"preview": "function x509Error(msg, cert) {\n return new Error('SASL channel binding: ' + msg + ' when parsing public certificate ' "
},
{
"path": "packages/pg/lib/crypto/sasl.js",
"chars": 7423,
"preview": "'use strict'\nconst crypto = require('./utils')\nconst { signatureAlgorithmHashFromCertificate } = require('./cert-signatu"
},
{
"path": "packages/pg/lib/crypto/utils-legacy.js",
"chars": 1215,
"preview": "'use strict'\n// This file contains crypto utility functions for versions of Node.js < 15.0.0,\n// which does not support "
},
{
"path": "packages/pg/lib/crypto/utils-webcrypto.js",
"chars": 2649,
"preview": "const nodeCrypto = require('crypto')\n\nmodule.exports = {\n postgresMd5PasswordHash,\n randomBytes,\n deriveKey,\n sha256"
},
{
"path": "packages/pg/lib/crypto/utils.js",
"chars": 341,
"preview": "'use strict'\n\nconst useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split("
},
{
"path": "packages/pg/lib/defaults.js",
"chars": 2506,
"preview": "'use strict'\n\nlet user\ntry {\n user = process.platform === 'win32' ? process.env.USERNAME : process.env.USER\n} catch {\n "
},
{
"path": "packages/pg/lib/index.js",
"chars": 1810,
"preview": "'use strict'\n\nconst Client = require('./client')\nconst defaults = require('./defaults')\nconst Connection = require('./co"
},
{
"path": "packages/pg/lib/native/client.js",
"chars": 8563,
"preview": "const nodeUtils = require('util')\n// eslint-disable-next-line\nvar Native\n// eslint-disable-next-line no-useless-catch\ntr"
},
{
"path": "packages/pg/lib/native/index.js",
"chars": 50,
"preview": "'use strict'\nmodule.exports = require('./client')\n"
},
{
"path": "packages/pg/lib/native/query.js",
"chars": 4757,
"preview": "'use strict'\n\nconst EventEmitter = require('events').EventEmitter\nconst util = require('util')\nconst utils = require('.."
},
{
"path": "packages/pg/lib/query.js",
"chars": 7314,
"preview": "'use strict'\n\nconst { EventEmitter } = require('events')\n\nconst Result = require('./result')\nconst utils = require('./ut"
},
{
"path": "packages/pg/lib/result.js",
"chars": 2812,
"preview": "'use strict'\n\nconst types = require('pg-types')\n\nconst matchRegexp = /^([A-Za-z]+)(?: (\\d+))?(?: (\\d+))?/\n\n// result obj"
},
{
"path": "packages/pg/lib/stream.js",
"chars": 2132,
"preview": "const { getStream, getSecureStream } = getStreamFuncs()\n\nmodule.exports = {\n /**\n * Get a socket stream compatible wi"
},
{
"path": "packages/pg/lib/type-overrides.js",
"chars": 770,
"preview": "'use strict'\n\nconst types = require('pg-types')\n\nfunction TypeOverrides(userTypes) {\n this._types = userTypes || types\n"
},
{
"path": "packages/pg/lib/utils.js",
"chars": 5642,
"preview": "'use strict'\n\nconst defaults = require('./defaults')\n\nconst util = require('util')\nconst { isDate } = util.types || util"
},
{
"path": "packages/pg/package.json",
"chars": 1611,
"preview": "{\n \"name\": \"pg\",\n \"version\": \"8.20.0\",\n \"description\": \"PostgreSQL client - pure javascript & libpq with the same API"
},
{
"path": "packages/pg/script/dump-db-types.js",
"chars": 466,
"preview": "'use strict'\nconst pg = require('../lib')\nconst args = require('../test/cli')\n\nconst queries = ['select CURRENT_TIMESTAM"
},
{
"path": "packages/pg/test/buffer-list.js",
"chars": 1510,
"preview": "'use strict'\n\nconst BufferList = function () {\n this.buffers = []\n}\nconst p = BufferList.prototype\n\np.add = function (b"
},
{
"path": "packages/pg/test/cloudflare/vitest-cf.test.ts",
"chars": 281,
"preview": "import { Pool } from 'pg'\nimport { test } from 'vitest'\nimport assert from 'assert'\n\ntest('default', async () => {\n con"
},
{
"path": "packages/pg/test/integration/client/api-tests.js",
"chars": 7199,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nconst suite"
},
{
"path": "packages/pg/test/integration/client/appname-tests.js",
"chars": 2477,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Client = helper.Client\nconst assert = require('assert')\n\ncons"
},
{
"path": "packages/pg/test/integration/client/array-tests.js",
"chars": 7062,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nconst suite "
},
{
"path": "packages/pg/test/integration/client/async-stack-trace-tests.js",
"chars": 1572,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pg = helper.pg\n\nprocess.on('unhandledRejection', function (e"
},
{
"path": "packages/pg/test/integration/client/big-simple-query-tests.js",
"chars": 11486,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\nconst assert = require('assert')\n\ncon"
},
{
"path": "packages/pg/test/integration/client/configuration-tests.js",
"chars": 1788,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\nconst { Clien"
},
{
"path": "packages/pg/test/integration/client/connection-parameter-tests.js",
"chars": 516,
"preview": "const assert = require('assert')\nconst helper = require('../test-helper')\nconst suite = new helper.Suite()\nconst { Clien"
},
{
"path": "packages/pg/test/integration/client/connection-timeout-tests.js",
"chars": 2636,
"preview": "'use strict'\nconst net = require('net')\nconst buffers = require('../../test-buffers')\nconst helper = require('./test-hel"
},
{
"path": "packages/pg/test/integration/client/custom-types-tests.js",
"chars": 1472,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Client = helper.pg.Client\nconst suite = new helper.Suite()\nco"
},
{
"path": "packages/pg/test/integration/client/empty-query-tests.js",
"chars": 523,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst suite = new helper.Suite()\nconst assert = require('assert')\n\n"
},
{
"path": "packages/pg/test/integration/client/error-handling-tests.js",
"chars": 6412,
"preview": "'use strict'\n\nconst helper = require('./test-helper')\n\nconst pg = helper.pg\nconst assert = require('assert')\nconst Clien"
},
{
"path": "packages/pg/test/integration/client/field-name-escape-tests.js",
"chars": 252,
"preview": "const pg = require('./test-helper').pg\n\nconst sql = 'SELECT 1 AS \"\\\\\\'/*\", 2 AS \"\\\\\\'*/\\n + process.exit(-1)] = null;\\n/"
},
{
"path": "packages/pg/test/integration/client/huge-numeric-tests.js",
"chars": 769,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pool = new helper.pg.Pool()\nconst assert = require('assert')\n"
},
{
"path": "packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js",
"chars": 2598,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Client = helper.Client\nconst assert = require('assert')\n\ncons"
},
{
"path": "packages/pg/test/integration/client/json-type-parsing-tests.js",
"chars": 1241,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\n\nconst pool = new helper.pg.Pool()"
},
{
"path": "packages/pg/test/integration/client/multiple-results-tests.js",
"chars": 2704,
"preview": "'use strict'\nconst assert = require('assert')\nconst co = require('co')\n\nconst helper = require('./test-helper')\n\nconst s"
},
{
"path": "packages/pg/test/integration/client/network-partition-tests.js",
"chars": 2514,
"preview": "'use strict'\nconst buffers = require('../../test-buffers')\nconst helper = require('./test-helper')\nconst suite = new hel"
},
{
"path": "packages/pg/test/integration/client/no-data-tests.js",
"chars": 873,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst suite = new helper.Suite()\nconst assert = require('assert')\n\n"
},
{
"path": "packages/pg/test/integration/client/no-row-result-tests.js",
"chars": 868,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst suite = new helper.Suite()\nconst pool = "
},
{
"path": "packages/pg/test/integration/client/notice-tests.js",
"chars": 2341,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n\n"
},
{
"path": "packages/pg/test/integration/client/parse-int-8-tests.js",
"chars": 1336,
"preview": "'use strict'\n\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst suite = new helper.Suite()\nconst asser"
},
{
"path": "packages/pg/test/integration/client/prepared-statement-tests.js",
"chars": 6002,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\n\nconst assert = require('assert')\ncon"
},
{
"path": "packages/pg/test/integration/client/promise-api-tests.js",
"chars": 1394,
"preview": "'use strict'\n\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nconst suite"
},
{
"path": "packages/pg/test/integration/client/query-as-promise-tests.js",
"chars": 1492,
"preview": "'use strict'\nconst bluebird = require('bluebird')\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst as"
},
{
"path": "packages/pg/test/integration/client/query-column-names-tests.js",
"chars": 570,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nnew helper."
},
{
"path": "packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js",
"chars": 3331,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\nconst { Client } = helper\nconst asser"
},
{
"path": "packages/pg/test/integration/client/query-error-handling-tests.js",
"chars": 3952,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\nconst DatabaseError = helper.pg.Datab"
},
{
"path": "packages/pg/test/integration/client/quick-disconnect-tests.js",
"chars": 161,
"preview": "'use strict'\n// test for issue #320\n//\nconst helper = require('./test-helper')\n\nconst client = new helper.pg.Client(help"
},
{
"path": "packages/pg/test/integration/client/result-metadata-tests.js",
"chars": 1468,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nconst pool ="
},
{
"path": "packages/pg/test/integration/client/results-as-array-tests.js",
"chars": 977,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n\n"
},
{
"path": "packages/pg/test/integration/client/row-description-on-results-tests.js",
"chars": 1328,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n\n"
},
{
"path": "packages/pg/test/integration/client/sasl-scram-tests.js",
"chars": 3733,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst pg = helper.pg\nconst suite = new helper.Suite()\nconst { na"
},
{
"path": "packages/pg/test/integration/client/simple-query-tests.js",
"chars": 3069,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\nconst assert = require('assert')\ncons"
},
{
"path": "packages/pg/test/integration/client/ssl-tests.js",
"chars": 507,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n\n"
},
{
"path": "packages/pg/test/integration/client/statement_timeout-tests.js",
"chars": 2155,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Client = helper.Client\n\nconst assert = require('assert')\ncons"
},
{
"path": "packages/pg/test/integration/client/test-helper.js",
"chars": 81,
"preview": "'use strict'\nconst helper = require('./../test-helper')\n\nmodule.exports = helper\n"
},
{
"path": "packages/pg/test/integration/client/timezone-tests.js",
"chars": 1085,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst oldTz = process.env.TZ\np"
},
{
"path": "packages/pg/test/integration/client/transaction-tests.js",
"chars": 1672,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst suite = new helper.Suite()\nconst pg = helper.pg\nconst assert "
},
{
"path": "packages/pg/test/integration/client/type-coercion-tests.js",
"chars": 6275,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst suite = new helper.Suite()\nconst assert "
},
{
"path": "packages/pg/test/integration/client/type-parser-override-tests.js",
"chars": 1313,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\n\nfunction testTypeParser(client, e"
},
{
"path": "packages/pg/test/integration/connection-pool/connection-pool-size-tests.js",
"chars": 974,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite()"
},
{
"path": "packages/pg/test/integration/connection-pool/error-tests.js",
"chars": 4626,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst pg = helper.pg\nconst native = helper.args.native\nconst assert"
},
{
"path": "packages/pg/test/integration/connection-pool/idle-timeout-tests.js",
"chars": 405,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\n\nnew helper.Suite().test('idle tim"
},
{
"path": "packages/pg/test/integration/connection-pool/native-instance-tests.js",
"chars": 395,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst pg = helper.pg\nconst native = helper.args.native\nconst ass"
},
{
"path": "packages/pg/test/integration/connection-pool/test-helper.js",
"chars": 81,
"preview": "'use strict'\nconst helper = require('./../test-helper')\n\nmodule.exports = helper\n"
},
{
"path": "packages/pg/test/integration/connection-pool/tls-tests.js",
"chars": 508,
"preview": "'use strict'\n\nconst fs = require('fs')\n\nconst helper = require('./test-helper')\nconst pg = helper.pg\n\nconst suite = new "
},
{
"path": "packages/pg/test/integration/connection-pool/yield-support-tests.js",
"chars": 581,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst co = require('co')\nconst assert = require('assert')\n\nconst po"
},
{
"path": "packages/pg/test/integration/domain-tests.js",
"chars": 1647,
"preview": "'use strict'\n\nconst helper = require('./test-helper')\nconst Query = helper.pg.Query\nconst suite = new helper.Suite()\n\nco"
},
{
"path": "packages/pg/test/integration/gh-issues/1105-tests.js",
"chars": 603,
"preview": "const helper = require('../test-helper')\nconst suite = new helper.Suite()\n\nsuite.test('timeout causing query crashes', a"
},
{
"path": "packages/pg/test/integration/gh-issues/130-tests.js",
"chars": 916,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst exec = require('child_process').exec\nconst assert = require("
},
{
"path": "packages/pg/test/integration/gh-issues/131-tests.js",
"chars": 1071,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nconst suite"
},
{
"path": "packages/pg/test/integration/gh-issues/1382-tests.js",
"chars": 877,
"preview": "'use strict'\nconst helper = require('./../test-helper')\n\nconst suite = new helper.Suite()\n\nsuite.test('calling end durin"
},
{
"path": "packages/pg/test/integration/gh-issues/1542-tests.js",
"chars": 534,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite"
},
{
"path": "packages/pg/test/integration/gh-issues/1854-tests.js",
"chars": 946,
"preview": "'use strict'\nconst helper = require('./../test-helper')\n\nconst suite = new helper.Suite()\n\nsuite.test('Parameter seriali"
},
{
"path": "packages/pg/test/integration/gh-issues/199-tests.js",
"chars": 641,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst client = helper.client()\nconst assert = require('assert')\n\nc"
},
{
"path": "packages/pg/test/integration/gh-issues/1992-tests.js",
"chars": 268,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite"
},
{
"path": "packages/pg/test/integration/gh-issues/2056-tests.js",
"chars": 675,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite"
},
{
"path": "packages/pg/test/integration/gh-issues/2064-tests.js",
"chars": 1080,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\nconst util = require('util')\n\nc"
},
{
"path": "packages/pg/test/integration/gh-issues/2079-tests.js",
"chars": 1731,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite"
},
{
"path": "packages/pg/test/integration/gh-issues/2085-tests.js",
"chars": 963,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite"
},
{
"path": "packages/pg/test/integration/gh-issues/2108-tests.js",
"chars": 358,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst suite = new helper.Suite()\n\nsuite.test('Closing an unconne"
},
{
"path": "packages/pg/test/integration/gh-issues/2303-tests.js",
"chars": 1942,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\nconst util = require('util')\n\nc"
},
{
"path": "packages/pg/test/integration/gh-issues/2307-tests.js",
"chars": 469,
"preview": "'use strict'\n\nconst pg = require('../../../lib')\nconst helper = require('../test-helper')\nconst assert = require('assert"
},
{
"path": "packages/pg/test/integration/gh-issues/2416-tests.js",
"chars": 443,
"preview": "const helper = require('../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite()\n\nsuite.test("
},
{
"path": "packages/pg/test/integration/gh-issues/2556-tests.js",
"chars": 1184,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\nconst callbackError = new Erro"
},
{
"path": "packages/pg/test/integration/gh-issues/2627-tests.js",
"chars": 1651,
"preview": "'use strict'\nconst net = require('net')\nconst helper = require('./../test-helper')\nconst assert = require('assert')\n\ncon"
},
{
"path": "packages/pg/test/integration/gh-issues/2716-tests.js",
"chars": 1279,
"preview": "'use strict'\nconst helper = require('../test-helper')\n\nconst suite = new helper.Suite()\n\n// https://github.com/brianc/no"
},
{
"path": "packages/pg/test/integration/gh-issues/2862-tests.js",
"chars": 792,
"preview": "'use strict'\n\nconst helper = require('../test-helper')\nconst assert = require('assert')\nconst vm = require('vm')\n\nconst "
},
{
"path": "packages/pg/test/integration/gh-issues/3062-tests.js",
"chars": 837,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n"
},
{
"path": "packages/pg/test/integration/gh-issues/3174-tests.js",
"chars": 5515,
"preview": "const net = require('net')\nconst buffers = require('../../test-buffers')\nconst helper = require('../test-helper')\nconst "
},
{
"path": "packages/pg/test/integration/gh-issues/3487-tests.js",
"chars": 621,
"preview": "const helper = require('../test-helper')\nconst assert = require('assert')\n\nconst suite = new helper.Suite()\n\nsuite.test("
},
{
"path": "packages/pg/test/integration/gh-issues/507-tests.js",
"chars": 647,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pg = helper.pg\nconst assert = require('assert')\n\nnew helper."
},
{
"path": "packages/pg/test/integration/gh-issues/600-tests.js",
"chars": 1936,
"preview": "'use strict'\nconst async = require('async')\nconst helper = require('../test-helper')\nconst suite = new helper.Suite()\nco"
},
{
"path": "packages/pg/test/integration/gh-issues/675-tests.js",
"chars": 671,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst assert = require('assert')\n\nconst pool = new helper.pg.Pool("
},
{
"path": "packages/pg/test/integration/gh-issues/699-tests.js",
"chars": 726,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst copyFrom = require('pg-copy-streams').from\n\nif (helper.args."
},
{
"path": "packages/pg/test/integration/gh-issues/787-tests.js",
"chars": 394,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst pool = new helper.pg.Pool()\n\npool.connect(function (err, cli"
},
{
"path": "packages/pg/test/integration/gh-issues/882-tests.js",
"chars": 297,
"preview": "'use strict'\n// client should not hang on an empty query\nconst helper = require('../test-helper')\nconst client = helper."
},
{
"path": "packages/pg/test/integration/gh-issues/981-tests.js",
"chars": 908,
"preview": "'use strict'\nconst helper = require('./../test-helper')\n\n//native bindings are only installed for native tests\nif (!help"
},
{
"path": "packages/pg/test/integration/test-helper.js",
"chars": 772,
"preview": "'use strict'\nconst helper = require('./../test-helper')\nlet { Client } = helper\nconst assert = require('assert')\n\nif (he"
},
{
"path": "packages/pg/test/native/callback-api-tests.js",
"chars": 1296,
"preview": "'use strict'\nconst domain = require('domain')\nconst helper = require('./../test-helper')\nconst Client = require('./../.."
},
{
"path": "packages/pg/test/native/evented-api-tests.js",
"chars": 2892,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst Client = require('../../lib/native')\nconst Query = Client.Qu"
},
{
"path": "packages/pg/test/native/native-connection-string-tests.js",
"chars": 1511,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst Client = require('../../lib/native')\nconst suite = new helpe"
},
{
"path": "packages/pg/test/native/native-vs-js-error-tests.js",
"chars": 561,
"preview": "'use strict'\nconst assert = require('assert')\nconst Client = require('../../lib/client')\nconst NativeClient = require('."
},
{
"path": "packages/pg/test/native/stress-tests.js",
"chars": 1438,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst Client = require('../../lib/native')\nconst Query = Client.Qu"
},
{
"path": "packages/pg/test/suite.js",
"chars": 1929,
"preview": "'use strict'\n\nconst async = require('async')\nconst { deprecate } = require('util')\n\nconst deprecatedTestAsync = deprecat"
},
{
"path": "packages/pg/test/test-buffers.js",
"chars": 3550,
"preview": "'use strict'\nrequire('./test-helper')\nconst BufferList = require('./buffer-list')\n// http://developer.postgresql.org/pgd"
},
{
"path": "packages/pg/test/test-helper.js",
"chars": 7081,
"preview": "'use strict'\nconst assert = require('assert')\nconst sys = require('util')\n\nconst Suite = require('./suite')\nconst Client"
},
{
"path": "packages/pg/test/tls/GNUmakefile",
"chars": 1385,
"preview": "DESTDIR ::= /var/lib/postgres/data\nPOSTGRES_USER ::= postgres\nPOSTGRES_GROUP ::= postgres\nDATABASE_HOST ::= localhost\nDA"
},
{
"path": "packages/pg/test/tls/test-client-ca.crt",
"chars": 627,
"preview": "-----BEGIN CERTIFICATE-----\nMIIBozCCAUmgAwIBAgIUNYMF06PrmjsMR6x+C8k5YZn9heAwCgYIKoZIzj0EAwIw\nJzElMCMGA1UEAwwcbm9kZS1wb3N"
},
{
"path": "packages/pg/test/tls/test-client-ca.key",
"chars": 241,
"preview": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKsipfQWM+41FriF7\nkRxVaiNi8qY1fzLx6Dp/gUQQPG6"
},
{
"path": "packages/pg/test/tls/test-client.crt",
"chars": 453,
"preview": "-----BEGIN CERTIFICATE-----\nMIIBITCByAIBATAKBggqhkjOPQQDAjAnMSUwIwYDVQQDDBxub2RlLXBvc3RncmVz\nIHRlc3QgY2xpZW50IENBMB4XDTI"
},
{
"path": "packages/pg/test/tls/test-client.key",
"chars": 241,
"preview": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL9jW07+fXy/74Ub3\n579RXm0Xpo7lnNnQleSzkTEXCrm"
},
{
"path": "packages/pg/test/tls/test-server-ca.crt",
"chars": 627,
"preview": "-----BEGIN CERTIFICATE-----\nMIIBozCCAUmgAwIBAgIUD582G2ou0Lg9q7AJeAMpiQVaiPQwCgYIKoZIzj0EAwIw\nJzElMCMGA1UEAwwcbm9kZS1wb3N"
},
{
"path": "packages/pg/test/tls/test-server-ca.key",
"chars": 241,
"preview": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyUd4vHDNrEFzfttP\nz+AFp3Tbyui+b3i9YDW7VqpMOIK"
},
{
"path": "packages/pg/test/tls/test-server.crt",
"chars": 453,
"preview": "-----BEGIN CERTIFICATE-----\nMIIBITCByQIBATAKBggqhkjOPQQDAjAnMSUwIwYDVQQDDBxub2RlLXBvc3RncmVz\nIHRlc3Qgc2VydmVyIENBMB4XDTI"
},
{
"path": "packages/pg/test/tls/test-server.key",
"chars": 241,
"preview": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgBoW9xxWBH2tHiPFk\n9ajPALHyw0lHAY1DF8WvHQNodx2"
},
{
"path": "packages/pg/test/unit/client/cleartext-password-tests.js",
"chars": 994,
"preview": "'use strict'\n\nconst helper = require('./test-helper')\nconst createClient = require('./test-helper').createClient\nconst a"
},
{
"path": "packages/pg/test/unit/client/configuration-tests.js",
"chars": 5371,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst { Client } = helper\nconst assert = require('assert')\nconst su"
},
{
"path": "packages/pg/test/unit/client/early-disconnect-tests.js",
"chars": 477,
"preview": "'use strict'\nrequire('./test-helper')\nconst net = require('net')\nconst pg = require('../../../lib/index.js')\nconst asser"
},
{
"path": "packages/pg/test/unit/client/escape-tests.js",
"chars": 2942,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst utils = require('../../../lib/utils')\nconst assert = require("
},
{
"path": "packages/pg/test/unit/client/md5-password-tests.js",
"chars": 1074,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst BufferList = require('../../buffer-list')\nconst crypto = requ"
},
{
"path": "packages/pg/test/unit/client/notification-tests.js",
"chars": 345,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\n\n"
},
{
"path": "packages/pg/test/unit/client/password-callback-tests.js",
"chars": 1777,
"preview": "const helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\nconst pgpass ="
},
{
"path": "packages/pg/test/unit/client/pgpass.file",
"chars": 21,
"preview": "foo:5432:bar:baz:quz\n"
},
{
"path": "packages/pg/test/unit/client/prepared-statement-tests.js",
"chars": 3758,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = require('../../../lib/query')\nconst assert = require("
},
{
"path": "packages/pg/test/unit/client/query-queue-tests.js",
"chars": 913,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst { Client } = helper\nconst Connection = require('../../../lib/"
},
{
"path": "packages/pg/test/unit/client/query-timeout-tests.js",
"chars": 993,
"preview": "'use strict'\n\nconst helper = require('./test-helper')\nconst Query = require('../../../lib/query')\nconst assert = require"
},
{
"path": "packages/pg/test/unit/client/result-metadata-tests.js",
"chars": 1311,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst suite = new helper.Suite()\nc"
},
{
"path": "packages/pg/test/unit/client/sasl-scram-tests.js",
"chars": 9581,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\n\nconst sasl = require('../../../li"
},
{
"path": "packages/pg/test/unit/client/set-keepalives-tests.js",
"chars": 738,
"preview": "'use strict'\nconst net = require('net')\nconst pg = require('../../../lib/index.js')\nconst helper = require('./test-helpe"
},
{
"path": "packages/pg/test/unit/client/simple-query-tests.js",
"chars": 4268,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = require('../../../lib/query')\nconst assert = require("
},
{
"path": "packages/pg/test/unit/client/stream-and-query-error-interaction-tests.js",
"chars": 983,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Connection = require('../../../lib/connection')\nconst Client "
},
{
"path": "packages/pg/test/unit/client/test-helper.js",
"chars": 618,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst Connection = require('../../../lib/connection')\nconst { Clie"
},
{
"path": "packages/pg/test/unit/client/throw-in-type-parser-tests.js",
"chars": 1580,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Query = require('../../../lib/query')\nconst types = require('"
},
{
"path": "packages/pg/test/unit/connection/error-tests.js",
"chars": 2537,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst Connection = require('../../../lib/connection')\nconst net = r"
},
{
"path": "packages/pg/test/unit/connection/startup-tests.js",
"chars": 2047,
"preview": "'use strict'\nconst helper = require('./test-helper')\nconst assert = require('assert')\nconst Connection = require('../../"
},
{
"path": "packages/pg/test/unit/connection/test-helper.js",
"chars": 56,
"preview": "'use strict'\nmodule.exports = require('../test-helper')\n"
},
{
"path": "packages/pg/test/unit/connection-parameters/creation-tests.js",
"chars": 11474,
"preview": "'use strict'\nconst helper = require('../test-helper')\nconst assert = require('assert')\nconst ConnectionParameters = requ"
},
{
"path": "packages/pg/test/unit/connection-parameters/environment-variable-tests.js",
"chars": 4014,
"preview": "'use strict'\nconst Suite = require('../../suite')\n\nconst assert = require('assert')\nconst ConnectionParameters = require"
},
{
"path": "packages/pg/test/unit/connection-pool/configuration-tests.js",
"chars": 366,
"preview": "'use strict'\n\nconst assert = require('assert')\nconst helper = require('../test-helper')\nconst suite = new helper.Suite()"
},
{
"path": "packages/pg/test/unit/test-helper.js",
"chars": 921,
"preview": "'use strict'\nconst EventEmitter = require('events').EventEmitter\n\nconst helper = require('../test-helper')\nconst Connect"
}
]
// ... and 153 more files (download for full content)
About this extraction
This page contains the full source code of the brianc/node-postgres GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 353 files (759.8 KB), approximately 204.3k tokens, and a symbol index with 356 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.