I am trying to insert an array of JSON into Postgres. Everything appears to run successfully (the table gets created), but there is no data inserted, and no error given. I am using the async/await method for transactions, but I can't understand what is failing.
(async() => {
const client = await pool.connect()
let val= [
{"table_pk":1,"NAME":"my Great Name","ROLE":"name1"},
{"table_pk":2,"NAME":"new Name","ROLE":"name1"},
{"table_pk":3,"NAME":"someone's funny name","ROLE":"name1"}
]
try {
await client.query('BEGIN');
await client.query('DROP TABLE IF EXISTS myTable')
await client.query(`CREATE TABLE myTable(table_pk INTEGER PRIMARY KEY, name TEXT, role TEXT)`)
await client.query(`INSERT INTO myTable SELECT * FROM jsonb_populate_recordset(NULL::myTable, $1::jsonb)`,[JSON.stringify(val)]);
await client.query('COMMIT');
}
catch (e) {
await client.query('ROLLBACK');
throw e
}
finally {
client.release();
}
})().catch(e => console.error(e.stack))
EDIT Updated the code to account for missing INSERT, now rows will insert, but not all the data.
INSERT? You are not adding anything into the table.SELECT, it got nothing to do with inserting records.