import test from 'node:test'; import assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; import { Database, isReadOnlyStatement } from '../src/db.js'; function fakePool(results) { const pool = new EventEmitter(); pool.calls = []; pool.query = async (text, values) => { pool.calls.push({ text, values }); const next = results.shift(); if (next instanceof Error) throw next; return next ?? { rows: [] }; }; return pool; } const transient = () => Object.assign(new Error('connection reset'), { code: 'ECONNRESET' }); test('only plain SELECT statements are treated as read-only', () => { assert.equal(isReadOnlyStatement('SELECT id FROM auth_users'), true); assert.equal(isReadOnlyStatement(' select 1'), true); assert.equal(isReadOnlyStatement('INSERT INTO auth_users (id) VALUES (1)'), false); assert.equal(isReadOnlyStatement('WITH x AS (DELETE FROM t RETURNING 1) SELECT * FROM x'), false); assert.equal(isReadOnlyStatement('SELECT * FROM t FOR UPDATE'), false); assert.equal(isReadOnlyStatement('SELECT nextval(\'seq\')'), false); assert.equal(isReadOnlyStatement('SELECT * INTO copy FROM t'), false); }); test('an idle pool error is logged instead of thrown', () => { const logged = []; const pool = fakePool([]); new Database({ pool, log: message => logged.push(message) }); assert.doesNotThrow(() => pool.emit('error', new Error('terminating connection'))); assert.equal(logged.length, 1); assert.match(logged[0], /terminating connection/); }); test('a transient error is retried for a read-only statement', async () => { const pool = fakePool([transient(), { rows: [{ ok: 1 }] }]); const db = new Database({ pool, log() {} }); db.ready = true; const result = await db.query('SELECT 1 AS ok'); assert.deepEqual(result.rows, [{ ok: 1 }]); assert.equal(pool.calls.length, 2); }); test('a transient error is not retried for a write', async () => { const pool = fakePool([transient(), { rows: [] }]); const db = new Database({ pool, log() {} }); db.ready = true; await assert.rejects(db.query('INSERT INTO t (id) VALUES ($1)', [1]), { code: 'ECONNRESET' }); assert.equal(pool.calls.length, 1); }); test('a write is retried only when the caller opts in', async () => { const pool = fakePool([transient(), { rows: [] }]); const db = new Database({ pool, log() {} }); db.ready = true; await db.query('INSERT INTO t (id) VALUES ($1)', [1], { retry: true }); assert.equal(pool.calls.length, 2); });