Ok, I have looked but didn't find anything that worked for me. If you can point me to anything or help my find the solution it would be great.
Let's say I have a "users" table (columns: id, username and name) and a "users_items" table (columns: id_item, id_user, both Foreign Keys)
What I want to do: I want to insert a new user and assign him a default item that everyone should have. For that, I want to create a transaction where everything or nothing is saved. So if (for any reason) I can't give him that item, I want the user creation to fail.
How I do it:
const pgp = require('pg-promise')(
{
capSQL: true // generate capitalized SQL
});
const db = pgp(configuration);
saveUser = (username, name) =>
db.tx (t =>
t.one('INSERT INTO users (username, name) VALUES $1, $2 RETURNING *', [username, name]).then(user =>
t.none ('INSERT INTO users_items (id_user, id_item) VALUES $1, 1', [user.id]).then(()=>
console.log('Everything\'s alright :)');
)
);
What I expect: everything runs perfectly and we are all happy :).
What actually happens: The first instruction is OK, and returns correctly the user with the ID. However, the second one tells me that the constraint fk_id_user is being violated, and perform a ROLLBACK.
The part of it not commiting the first insert is working properly. However, shouldn't the second insert work too? Am I understanding something extremely wrong or is pg-promise
not working as expected? Or maybe I need to do something different.. Any help would be appreciated.