-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathinsert-worker.cjs
More file actions
37 lines (29 loc) · 1009 Bytes
/
insert-worker.cjs
File metadata and controls
37 lines (29 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Worker module for Postgres batch inserts
// Loaded by tasklets worker threads via MODULE: prefix
const { Client } = require('pg')
async function insertBatch(items) {
const client = new Client({
user: 'erickwendel',
host: process.env.POSTGRES_HOST || 'localhost',
database: 'school',
password: 'mypassword',
port: 5432,
})
await client.connect()
try {
// Build a single bulk INSERT for performance
const values = []
const placeholders = []
let idx = 1
for (const item of items) {
placeholders.push(`($${idx++}, $${idx++}, $${idx++}, $${idx++})`)
values.push(item.name, item.email, item.age, item.registeredAt)
}
const query = `INSERT INTO students (name, email, age, registered_at) VALUES ${placeholders.join(', ')}`
await client.query(query, values)
} finally {
await client.end()
}
return items.length
}
module.exports = insertBatch