const { Client } = require('pg')
const client = new Client({user: 'postgres', 'database': 'postgres'})

client.connect()

client.query('BEGIN', [], (err,res) => {
    console.log(err ? err.stack : res.rows[0])
})

client.query('CREATE TABLE if not exists foo ( id  text, bar double precision )', [], (err,res) => {
    console.log(err ? err.stack : res.rows[0])
})

client.query('INSERT INTO foo (id, bar) VALUES ($1, $2)', ['abc', 4], (err,res) => {
    console.log(err ? err.stack : res.rows[0])
})

client.query('INSERT INTO foo (id, bar) VALUES ($1, $2)', ['bcd', 3], (err,res) => {
    console.log(err ? err.stack : res.rows[0])
})

client.query('SELECT * FROM foo', [], (err,res) => {
    console.log(err ? err.stack : res.rows)
})

client.query('UPDATE foo SET (id, bar) = ($2, $3) WHERE id=$1', ['bcd', 'ddd', 2], (err,res) => {
    console.log(err ? err.stack : res.rows)
})


client.query('SELECT * FROM foo', [], (err,res) => {
    console.log(err ? err.stack : res.rows)
})

// COMMENT BELOW TO NOT ERROR
client.query('UPDATE foo d SET bar=v.bar FROM (values ($1, $2)) as v(id,bar) WHERE d.id=v.id', ['abc', 5], (err,res) => {
    console.log(err ? err.stack : res.row})
})

// UNCOMMENT BELOW TO WORK
//client.query(`UPDATE foo d SET bar=v.bar FROM (values ('abc', 5)) as v(id,bar) WHERE d.id=v.id`, [], (err,res) => {
//    console.log(err ? err.stack : res.rows)
//})

client.query('SELECT * FROM foo', [], (err,res) => {
    console.log(err ? err.stack : res.rows)
})

client.query('ROLLBACK', [], (err,res) => {
    console.log(err ? err.stack : res.rows[0])
    client.end()
})