import { describe, expect, it, vi } from 'vitest'; import type { PoolClient } from 'pg'; import { attachSerializedQuery } from '../src/db'; describe('attachSerializedQuery', () => { it('serializes concurrent query calls on one client', async () => { const events: string[] = []; let active = 0; let maxActive = 0; const rawQuery = vi.fn(async (sql: string) => { active += 1; maxActive = Math.max(maxActive, active); events.push(`start:${sql}`); await new Promise((resolve) => setTimeout(resolve, 20)); events.push(`end:${sql}`); active -= 1; return { rows: [{ sql }], rowCount: 1 }; }); const client = { query: rawQuery } as unknown as PoolClient; const serialized = attachSerializedQuery(client); const results = await Promise.all([ serialized.query('A'), serialized.query('B'), serialized.query('C'), ]); expect(maxActive).toBe(1); expect(events).toEqual(['start:A', 'end:A', 'start:B', 'end:B', 'start:C', 'end:C']); expect(results.map((row: any) => row.rows[0].sql)).toEqual(['A', 'B', 'C']); }); it('keeps queue moving after a failed query', async () => { const rawQuery = vi.fn(async (sql: string) => { if (sql === 'fail') throw new Error('boom'); return { rows: [{ sql }], rowCount: 1 }; }); const client = { query: rawQuery } as unknown as PoolClient; const serialized = attachSerializedQuery(client); await expect(serialized.query('fail')).rejects.toThrow('boom'); const ok = await serialized.query('ok'); expect(ok.rows[0].sql).toBe('ok'); }); });