Skip to content

Latest commit

 

History

History

pg-query-context

Folders and files

README.md

pg-query-context

pg-query-context

A small utility for executing PostgreSQL queries within a session context using pg. It allows you to temporarily set PostgreSQL session variables (set_config) for RLS (Row-Level Security) and other scoped operations.

Installation

npm install pg-query-context

Features

  • Sets session-level context (e.g., role, user ID) using set_config.
  • Automatically wraps execution in a transaction (BEGIN/COMMIT).
  • Automatically rolls back on error.
  • Supports both Pool and Client from pg.

Usage

import pgQueryContext from 'pg-query-context';
import { Pool } from 'pg';

const pool = new Pool();

const result = await pgQueryContext({
  client: pool,
  context: {
    'role': 'authenticated',
    'myapp.user_id': '123e4567-e89b-12d3-a456-426614174000'
  },
  query: 'SELECT * FROM app_private.do_something_secure($1)',
  variables: ['input-value']
});

console.log(result.rows);

API

pgQueryContext(options: ExecOptions): Promise<QueryResult>

Options

Name Type Required Description
client Pool or ClientBase ✅ The PostgreSQL client or pool to use
context Record<string, string> ❌ Key-value session variables to be set via set_config
query string ✅ SQL query to run
variables any[] ❌ Parameterized query variables

Callback-based API (withPgClient)

For multi-query RLS transactions, use withPgClient which gives you a connected client within a scoped transaction:

import { withPgClient } from 'pg-query-context';
import { Pool } from 'pg';

const pool = new Pool();

const user = await withPgClient(
  pool,
  { 'role': 'authenticated', 'jwt.claims.user_id': userId },
  async (client) => {
    const { rows: [row] } = await client.query('SELECT * FROM app_public.current_user()');
    await client.query('UPDATE app_public.users SET last_seen = now() WHERE id = $1', [row.id]);
    return row;
  }
);

withPgClient<T>(pool, context, fn, opts?): Promise<T>

Name Type Required Description
pool Pool ✅ The PostgreSQL pool to acquire a client from
context Record<string, string> ✅ Session variables set via set_config
fn (client: PoolClient) => T ✅ Callback receiving the connected client
opts { skipTransaction?: boolean } ❌ Skip BEGIN/COMMIT wrapping (e.g., inside existing txn)

Example with express

app.post('/secure-endpoint', async (req, res) => {
  const authToken = req.headers.authorization;

  const result = await pgQueryContext({
    client: pool,
    context: {
      'role': 'authenticated',
      'myapp.token': authToken,
    },
    query: 'SELECT * FROM app_private.verify_token($1)',
    variables: [authToken],
  });

  if (!result.rows.length) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  res.json({ user: result.rows[0] });
});