0

I have application written in Javascript which uses postgreSQL (9.6) DB to store data. Is there a way how to insert Javascript object directly into DB ?

I created this example table:

CREATE TABLE people (
  "uuid" uuid PRIMARY KEY,
  "name" text NOT NULL,
  "phone" number
); 

Javascript object in the app:

{
  uuid: 'df7c5fdc-d6b7-4b5e-ac3b-1228fac64a90',
  name: 'Martin',
  phone: 123456
}

Now I have the array of different people (array of objects above) and I managed to insert it to DB in this way:

let uuids = people.map(p => `'${p.uuid}'`) // adding quotes, otherwise syntax error
let names = people.map(p => `'${p.name}'`)
let phones = people.map(p => `'${p.phone}'`)

INSERT INTO people (
  "uuid",
  "name",
  "phone"
)
VALUES (
  UNNEST(ARRAY[${uuids}])::uuid,
  UNNEST(ARRAY[${names}])::text,
  UNNEST(ARRAY[${phones}])::number
)

Is there a way to do this more efficiently ? like in mongo db.collection.insertMany(array) ? Also, I'd like to omit some of the values and have them NULL, which is not possible in this example.

I was searching in PostgreSQL docs and there are several functions to work with json but I couldn't find any suitable for this.

Thank you for help.

6
  • What makes you think there is anything inefficient about that? Commented Oct 10, 2018 at 15:52
  • Postgresql's json_to_recordset() function looks promising when combined with INSERT INTO ... SELECT as a way to do it entirely in SQL. Commented Oct 10, 2018 at 17:27
  • "adding quotes, otherwise syntax error" sounds like an SQL injection in the making. Commented Oct 10, 2018 at 18:03
  • @Pointy well, the creation of three new arrays with map is weird. In my app, I have more than 10 properties, so it means more than 10 new arrays which were all UNNESTed after. Commented Oct 11, 2018 at 8:49
  • @IljaEverilä it seems to be quite safe after JSON.stringify Commented Oct 11, 2018 at 9:35

1 Answer 1

2

Got a chance to test json_to_recordset():

INSERT INTO people("uuid", name, phone)
SELECT "uuid", name, phone
FROM json_to_recordset(?) AS x("uuid" uuid, name text, phone int);

where the placeholder should be bound to an array of objects like you describe (Except in proper JSON, of course).

sqlfiddle example

1
  • That works, I just had to do json_to_recordset(JSON.stringify(myArraw)), thank you! Commented Oct 11, 2018 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.