
Security News
ECMAScript 2025 Finalized with Iterator Helpers, Set Methods, RegExp.escape, and More
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
pgsql-test
Advanced tools
pgsql-test offers isolated, role-aware, and rollback-friendly PostgreSQL environments for integration tests โ giving developers realistic test coverage without external state pollution
pgsql-test
gives you instant, isolated PostgreSQL databases for each test โ with automatic transaction rollbacks, context switching, and clean seeding. Forget flaky tests and brittle environments. Write real SQL. Get real coverage. Stay fast.
npm install pgsql-test
.setContext()
.sql
files, programmatic seeds, or even load fixturesJest
, Mocha
, etc.Part of the LaunchQL ecosystem, pgsql-test
is built to pair seamlessly with our TypeScript-based Sqitch engine rewrite:
getConnections()
OverviewgetConnections() Options
import { getConnections } from 'pgsql-test';
let db, teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections());
await db.query(`SELECT 1`); // โ
Ready to run queries
});
afterAll(() => teardown());
getConnections()
Overviewimport { getConnections } from 'pgsql-test';
// Complete object destructuring
const { pg, db, admin, teardown, manager } = await getConnections();
// Most common pattern
const { db, teardown } = await getConnections();
The getConnections()
helper sets up a fresh PostgreSQL test database and returns a structured object with:
pg
: a PgTestClient
connected as the root or superuser โ useful for administrative setup or introspectiondb
: a PgTestClient
connected as the app-level user โ used for running tests with RLS and granted permissionsadmin
: a DbAdmin
utility for managing database state, extensions, roles, and templatesteardown()
: a function that shuts down the test environment and database poolmanager
: a shared connection pool manager (PgTestConnector
) behind both clientsTogether, these allow fast, isolated, role-aware test environments with per-test rollback and full control over setup and teardown.
The PgTestClient
returned by getConnections()
is a fully-featured wrapper around pg.Pool
. It provides:
PgTestClient
API Overviewlet pg: PgTestClient;
let teardown: () => Promise<void>;
beforeAll(async () => {
({ pg, teardown } = await getConnections());
});
beforeEach(() => pg.beforeEach());
afterEach(() => pg.afterEach());
afterAll(() => teardown());
The PgTestClient
returned by getConnections()
wraps a pg.Client
and provides convenient helpers for query execution, test isolation, and context switching.
query(sql, values?)
โ Run a raw SQL query and get the QueryResult
beforeEach()
โ Begins a transaction and sets a savepoint (called at the start of each test)afterEach()
โ Rolls back to the savepoint and commits the outer transaction (cleans up test state)setContext({ key: value })
โ Sets PostgreSQL config variables (like role
) to simulate RLS contextsany
, one
, oneOrNone
, many
, manyOrNone
, none
, result
โ Typed query helpers for specific result expectationsThese methods make it easier to build expressive and isolated integration tests with strong typing and error handling.
The PgTestClient
returned by getConnections()
is a fully-featured wrapper around pg.Pool
. It provides:
import { getConnections } from 'pgsql-test';
let db; // A fully wrapped PgTestClient using pg.Pool with savepoint-based rollback per test
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections());
await db.query(`
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);
CREATE TABLE posts (id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id), content TEXT);
INSERT INTO users (name) VALUES ('Alice'), ('Bob');
INSERT INTO posts (user_id, content) VALUES (1, 'Hello world!'), (2, 'Graphile is cool!');
`);
});
afterAll(() => teardown());
beforeEach(() => db.beforeEach());
afterEach(() => db.afterEach());
test('user count starts at 2', async () => {
const res = await db.query('SELECT COUNT(*) FROM users');
expect(res.rows[0].count).toBe('2');
});
The pgsql-test
framework provides powerful tools to simulate authentication contexts during tests, which is particularly useful when testing Row-Level Security (RLS) policies.
Use setContext()
to simulate different user roles and JWT claims:
db.setContext({
role: 'authenticated',
'jwt.claims.user_id': '123',
'jwt.claims.org_id': 'acme'
});
This applies the settings using SET LOCAL
statements, ensuring they persist only for the current transaction and maintain proper isolation between tests.
describe('authenticated role', () => {
beforeEach(async () => {
db.setContext({ role: 'authenticated' });
await db.beforeEach();
});
afterEach(() => db.afterEach());
it('runs as authenticated', async () => {
const res = await db.query(`SELECT current_setting('role', true) AS role`);
expect(res.rows[0].role).toBe('authenticated');
});
});
For non-superuser testing, use the connection options described in the options section. The db.connection
property allows you to customize the non-privileged user account for your tests.
Use setContext()
to simulate Role-Based Access Control (RBAC) during tests. This is useful when testing Row-Level Security (RLS) policies. Your actual server should manage role/user claims via secure tokens (e.g., setting current_setting('jwt.claims.user_id')
), but this interface helps emulate those behaviors in test environments.
This approach enables testing various access patterns:
Note: While this interface helps simulate RBAC for testing, your production server should manage user/role claims via secure authentication tokens, typically by setting values like
current_setting('jwt.claims.user_id')
through proper authentication middleware.
The second argument to getConnections()
is an optional array of SeedAdapter
objects:
const { db, teardown } = await getConnections(getConnectionOptions, seedAdapters);
This array lets you fully customize how your test database is seeded. You can compose multiple strategies:
seed.sqlfile()
โ Execute raw .sql
files from diskseed.fn()
โ Run JavaScript/TypeScript logic to programmatically insert dataseed.csv()
โ Load tabular data from CSV filesseed.json()
โ Use in-memory objects as seed dataseed.sqitch()
โ Deploy a Sqitch-compatible migration projectseed.launchql()
โ Apply a LaunchQL module using deployFast()
(compatible with sqitch)โจ Default Behavior: If no
SeedAdapter[]
is passed, LaunchQL seeding is assumed. This makespgsql-test
zero-config for LaunchQL-based projects.
This composable system allows you to mix-and-match data setup strategies for flexible, realistic, and fast database tests.
Use .sql
files to set up your database state before tests:
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const sql = (f: string) => path.join(__dirname, 'sql', f);
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.sqlfile([
sql('schema.sql'),
sql('fixtures.sql')
])
]));
});
afterAll(async () => {
await teardown();
});
Use JavaScript functions to insert seed data:
import { getConnections, seed } from 'pgsql-test';
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.fn(async ({ pg }) => {
await pg.query(`
INSERT INTO users (name) VALUES ('Seeded User');
`);
})
]));
});
You can load tables from CSV files using seed.csv({ ... })
. CSV headers must match the table column names exactly. This is useful for loading stable fixture data for integration tests or CI environments.
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const csv = (file: string) => path.resolve(__dirname, '../csv', file);
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
// Create schema
seed.fn(async ({ pg }) => {
await pg.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
content TEXT NOT NULL
);
`);
}),
// Load from CSV
seed.csv({
users: csv('users.csv'),
posts: csv('posts.csv')
}),
// Adjust SERIAL sequences to avoid conflicts
seed.fn(async ({ pg }) => {
await pg.query(`SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT MAX(id) FROM users));`);
await pg.query(`SELECT setval(pg_get_serial_sequence('posts', 'id'), (SELECT MAX(id) FROM posts));`);
})
]));
});
afterAll(() => teardown());
it('has loaded rows', async () => {
const res = await db.query('SELECT COUNT(*) FROM users');
expect(+res.rows[0].count).toBeGreaterThan(0);
});
You can seed tables using in-memory JSON objects. This is useful when you want fast, inline fixtures without managing external files.
import { getConnections, seed } from 'pgsql-test';
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
// Create schema
seed.fn(async ({ pg }) => {
await pg.query(`
CREATE SCHEMA custom;
CREATE TABLE custom.users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE custom.posts (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES custom.users(id),
content TEXT NOT NULL
);
`);
}),
// Seed with in-memory JSON
seed.json({
'custom.users': [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
],
'custom.posts': [
{ id: 1, user_id: 1, content: 'Hello world!' },
{ id: 2, user_id: 2, content: 'Graphile is cool!' }
]
}),
// Fix SERIAL sequences
seed.fn(async ({ pg }) => {
await pg.query(`SELECT setval(pg_get_serial_sequence('custom.users', 'id'), (SELECT MAX(id) FROM custom.users));`);
await pg.query(`SELECT setval(pg_get_serial_sequence('custom.posts', 'id'), (SELECT MAX(id) FROM custom.posts));`);
})
]));
});
afterAll(() => teardown());
it('has loaded rows', async () => {
const res = await db.query('SELECT COUNT(*) FROM custom.users');
expect(+res.rows[0].count).toBeGreaterThan(0);
});
Note: While compatible with Sqitch syntax, LaunchQL uses its own high-performance TypeScript-based deploy engine. that we encourage using for sqitch projects
You can seed your test database using a Sqitch project but with significantly improved performance by leveraging LaunchQL's TypeScript deployment engine:
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const cwd = path.resolve(__dirname, '../path/to/sqitch');
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.sqitch(cwd)
]));
});
This works for any Sqitch-compatible module, now accelerated by LaunchQL's deployment tooling.
If your project uses LaunchQL modules with a precompiled sqitch.plan
, you can use pgsql-test
with zero configuration. Just call getConnections()
โ and it just works:
import { getConnections } from 'pgsql-test';
let db, teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections()); // ๐ LaunchQL deployFast() is used automatically - up to 10x faster than traditional Sqitch!
});
This works out of the box because pgsql-test
uses the high-speed deployFast()
function by default, applying any compiled LaunchQL schema located in the current working directory (process.cwd()
).
If you want to specify a custom path to your LaunchQL module, use seed.launchql()
explicitly:
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const cwd = path.resolve(__dirname, '../path/to/launchql');
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.launchql(cwd) // uses deployFast() - up to 10x faster than traditional Sqitch!
]));
});
LaunchQL provides the best of both worlds:
By maintaining Sqitch compatibility while supercharging performance, LaunchQL enables you to keep your existing migration patterns while enjoying the speed benefits of our TypeScript engine.
getConnections
OptionsThis table documents the available options for the getConnections
function. The options are passed as a combination of pg
and db
configuration objects.
db
Options (PgTestConnectionOptions)Option | Type | Default | Description |
---|---|---|---|
db.extensions | string[] | [] | Array of PostgreSQL extensions to include in the test database |
db.cwd | string | process.cwd() | Working directory used for LaunchQL/Sqitch projects |
db.connection.user | string | 'app_user' | User for simulating RLS via setContext() |
db.connection.password | string | 'app_password' | Password for RLS test user |
db.connection.role | string | 'anonymous' | Default role used during setContext() |
db.template | string | undefined | Template database used for faster test DB creation |
db.rootDb | string | 'postgres' | Root database used for administrative operations (e.g., creating databases) |
db.prefix | string | 'db-' | Prefix used when generating test database names |
pg
Options (PgConfig)Environment variables will override these options when available:
PGHOST
, PGPORT
, PGUSER
, PGPASSWORD
, PGDATABASE
Option | Type | Default | Description |
---|---|---|---|
pg.user | string | 'postgres' | Superuser for PostgreSQL |
pg.password | string | 'password' | Password for the PostgreSQL superuser |
pg.host | string | 'localhost' | Hostname for PostgreSQL |
pg.port | number | 5423 | Port for PostgreSQL |
pg.database | string | 'postgres' | Default database used when connecting initially |
const { conn, db, teardown } = await getConnections({
pg: { user: 'postgres', password: 'secret' },
db: {
extensions: ['uuid-ossp'],
cwd: '/path/to/project',
connection: { user: 'test_user', password: 'secret', role: 'authenticated' },
template: 'test_template',
prefix: 'test_',
rootDb: 'postgres'
}
});
SET LOCAL
) into queriesโideal for setting role
, jwt.claims
, and other session settings.libpg_query
, converting SQL into parse trees.SELECT
, INSERT
, UPDATE
, DELETE
, and stored procedure callsโsupports advanced SQL features like JOIN
, GROUP BY
, and schema-qualified queries.AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
FAQs
pgsql-test offers isolated, role-aware, and rollback-friendly PostgreSQL environments for integration tests โ giving developers realistic test coverage without external state pollution
The npm package pgsql-test receives a total of 135 weekly downloads. As such, pgsql-test popularity was classified as not popular.
We found that pgsql-test demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.ย It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
Security News
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.
Research
North Korean threat actors linked to the Contagious Interview campaign return with 35 new malicious npm packages using a stealthy multi-stage malware loader.