pgsql-test
Version:
pgsql-test offers isolated, role-aware, and rollback-friendly PostgreSQL environments for integration tests — giving developers realistic test coverage without external state pollution
45 lines (44 loc) • 1.61 kB
JavaScript
import { pipeline } from 'node:stream/promises';
import { Logger } from '@launchql/logger';
import { createReadStream, createWriteStream, existsSync } from 'fs';
import { from as copyFrom, to as copyTo } from 'pg-copy-streams';
const log = new Logger('csv');
export function csv(tables) {
return {
async seed(ctx) {
for (const [table, filePath] of Object.entries(tables)) {
if (!existsSync(filePath)) {
throw new Error(`CSV file not found: ${filePath}`);
}
log.info(`📥 Seeding "${table}" from ${filePath}`);
await copyCsvIntoTable(ctx.pg, table, filePath);
}
}
};
}
export async function copyCsvIntoTable(pg, table, filePath) {
const client = pg.client;
const stream = client.query(copyFrom(`COPY ${table} FROM STDIN WITH CSV HEADER`));
const source = createReadStream(filePath);
try {
await pipeline(source, stream);
log.success(`✅ Successfully seeded "${table}"`);
}
catch (err) {
log.error(`❌ COPY failed for "${table}": ${err.message}`);
throw err;
}
}
export async function exportTableToCsv(pg, table, filePath) {
const client = pg.client;
const stream = client.query(copyTo(`COPY ${table} TO STDOUT WITH CSV HEADER`));
const target = createWriteStream(filePath);
try {
await pipeline(stream, target);
log.success(`✅ Exported "${table}" to ${filePath}`);
}
catch (err) {
log.error(`❌ Failed to export "${table}": ${err.message}`);
throw err;
}
}