46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import pg from "pg";
|
|
import { createPool, migrate, type Pool } from "../db/index.js";
|
|
import { readSettingsFile } from "../settings/index.js";
|
|
|
|
export interface TestDb {
|
|
pool: Pool;
|
|
name: string;
|
|
drop(): Promise<void>;
|
|
}
|
|
|
|
/** Адрес серверной БД из settings.json5 (или KHB_TEST_DATABASE_URL); null - БД недоступна, интеграционные тесты пропускаются. */
|
|
export function testDatabaseUrl(): string | null {
|
|
if (process.env.KHB_TEST_DATABASE_URL) return process.env.KHB_TEST_DATABASE_URL;
|
|
try {
|
|
const url = (readSettingsFile().common as { database?: { url?: string } } | undefined)?.database?.url;
|
|
return url || null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Создаёт временную базу llmtest_<random>, применяет миграции, возвращает пул и drop(). */
|
|
export async function createTestDb(baseUrl: string): Promise<TestDb> {
|
|
const name = `llmtest_${randomBytes(4).toString("hex")}`;
|
|
const admin = new pg.Client({ connectionString: baseUrl });
|
|
await admin.connect();
|
|
await admin.query(`create database ${name}`);
|
|
await admin.end();
|
|
const u = new URL(baseUrl);
|
|
u.pathname = `/${name}`;
|
|
const pool = createPool(u.toString(), 4);
|
|
await migrate(pool);
|
|
return {
|
|
pool,
|
|
name,
|
|
async drop() {
|
|
await pool.end();
|
|
const a = new pg.Client({ connectionString: baseUrl });
|
|
await a.connect();
|
|
await a.query(`drop database if exists ${name} with (force)`);
|
|
await a.end();
|
|
},
|
|
};
|
|
}
|