Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions postgres/pgsql-test/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ beforeEach(() => db.beforeEach());
afterEach(() => db.afterEach());
```

## Transaction-Local Context

`setContext()` uses `set_config('key', 'value', true)` — the `true` makes settings **transaction-local**. This means:

- **In `it()` blocks:** Works automatically. `beforeEach()` starts a transaction, so context persists across queries.
- **In `beforeAll()`:** No active transaction. Context is lost between queries. Wrap context-dependent operations in explicit `db.begin()` / `db.commit()`.

```ts
// In beforeAll — explicit transaction required
await db.begin();
db.setContext({ role: 'authenticated', 'jwt.claims.user_id': userId });
await db.query('...'); // context persists
await db.commit();
```

## Seeding Notes

- For raw SQL seeding, use `seed.sqlfile([...paths])`.
Expand Down
14 changes: 13 additions & 1 deletion postgres/pgsql-test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,19 @@ db.setContext({
});
```

This applies the settings using `SET LOCAL` statements, ensuring they persist only for the current transaction and maintain proper isolation between tests.
This applies the settings using `SET LOCAL` and `set_config(..., true)` statements, ensuring they persist only for the current transaction and maintain proper isolation between tests.

> **⚠️ Important:** `set_config(..., true)` is **transaction-local**. Inside test bodies (`it()` blocks), `beforeEach()` has already started a transaction, so context persists across queries automatically. However, in `beforeAll()` there is no active transaction — each query runs in auto-commit mode and context is lost between calls. If you need context-aware operations in `beforeAll()`, wrap them in explicit `db.begin()` / `db.commit()`:
>
> ```ts
> beforeAll(async () => {
> ({ db, teardown } = await getConnections());
> await db.begin();
> db.setContext({ role: 'authenticated', 'jwt.claims.user_id': '123' });
> await db.query('SELECT current_user_id()'); // context persists within transaction
> await db.commit();
> });
> ```

#### Testing Role-Based Access

Expand Down
Loading