0%

How to do multi-row insert with postgres by nodejs

緣起

最近有一個案子必須先透過 API 取得資料後把資料經過重組塞進 local database
環境上使用的是 nodejs + postgres

過程

經過了兩次重構之後整理一下最後的做法

  1. Using request-promise lib

  2. Using pg-promise lib

作者本人有在 stackoverflow 提供一段範例可以參考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const pgp = require('pg-promise')({
/* initialization options */
capSQL: true // capitalize all generated SQL
});
const db = pgp(/*connection*/);

// our set of columns, to be created only once, and then shared/reused,
// to let it cache up its formatting templates for high performance:
const cs = new pgp.helpers.ColumnSet(['col_a', 'col_b'], {table: 'tmp'});

// data input values:
const values = [{col_a: 'a1', col_b: 'b1'}, {col_a: 'a2', col_b: 'b2'}];

// generating a multi-row insert query:
const query = pgp.helpers.insert(values, cs);
//=> INSERT INTO "tmp"("col_a","col_b") VALUES('a1','b1'),('a2','b2')

// executing the query:
db.none(query)
.then(data => {
// success;
})
.catch(error => {
// error;

  1. Using map to reformat objects in an array

這篇裡面的範例也可以參考一下,當然 var 在 es7 裡面已經被棄用,但以 map 來做集合操作仍然是相當實用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var kvArray = [{key: 1, value: 10}, 
{key: 2, value: 20},
{key: 3, value: 30}];

var reformattedArray = kvArray.map(obj =>{
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],

// kvArray is still:
// [{key: 1, value: 10},
// {key: 2, value: 20},
// {key: 3, value: 30}]

One more thing

程式結束記得補上

1
pgp.end()