sless-primer/POSTGRES/code/js-pg-batch/js_pg_batch.js
2026-03-22 17:08:18 +04:00

44 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 2026-03-21 — js-pg-batch: вставляет N строк через parameterized bulk query.
// Тестирует: async/await PG с пакетной вставкой, Node.js под нагрузкой.
const { Client } = require('pg');
async function run(event) {
const n = Math.min(parseInt(event.n ?? 20, 10) || 20, 200);
const prefix = String(event.prefix ?? 'js-batch').slice(0, 40);
const client = new Client({
host: process.env.PGHOST,
port: parseInt(process.env.PGPORT ?? '5432'),
database: process.env.PGDATABASE,
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
ssl: { rejectUnauthorized: false },
});
await client.connect();
try {
const ts = Date.now();
// Строим multi-value INSERT: INSERT INTO ... VALUES ($1), ($2), ...
const placeholders = [];
const values = [];
for (let i = 0; i < n; i++) {
placeholders.push(`($${i + 1})`);
values.push(`${prefix}-${ts}-${i}`);
}
const sql = `INSERT INTO terraform_demo_table (title) VALUES ${placeholders.join(',')} RETURNING id`;
const t0 = Date.now();
const res = await client.query(sql, values);
const elapsed = (Date.now() - t0) / 1000;
return {
inserted: res.rowCount,
first_id: res.rows[0]?.id ?? null,
elapsed_sec: elapsed,
};
} finally {
await client.end();
}
}
module.exports = { run };