I'm trying to bulk insert in postgresql from an array. What I'm currently doing is the following inside of a loop.
INSERT INTO table_name (
first, second, third, forth
) VALUES (
$1, $2, $3, $4
)
There are around 8 to 9 other fields, and only 2 of them change in each iteration. What I would ideally want to do is something along the lines of this psudo-code
FOREACH (obj IN $5)
INSERT INTO table_name (
first, second, third, forth
) VALUES (
obj.fieldOne, $2, obj.fieldThree, $4
)
and only supply $2
and $4
(the non-changing properties), and $5
which is an array of changing properties like so
[{one: 123, two: 63}]
I know that PostgreSQL allows inserting multiple values in one INSERT statement, but to construct the query and manage its parameters can be a hassle and honestly I'm running away from it just because of parameter and query string hell.
INSERT INTO tabel_name (
first, second, third, forth
) VALUES (
$1, $2, $3, $4
) VALUES (
$5, $2, $6, $4
) VALUES (
$7, $2, $8, $4
)
I also read that PostgreSQL has loops like FOR and FOREACH, but I have no idea how to work with them in this scenario. I'm using NodeJS with pg-promise
if that is relevant.
Any help is appreciated!