Isolation Level Set Too Late
A money-transfer transaction tries to raise its isolation level, but places the command in the wrong spot.
Codejavascript
// node-postgres: transfer funds with SERIALIZABLE isolation
async function transfer(client, from, to, amount) {
await client.query('BEGIN');
const { rows } = await client.query(
'SELECT balance FROM accounts WHERE id = $1', [from]
);
await client.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
if (rows[0].balance < amount) throw new Error('insufficient funds');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
await client.query('COMMIT');
}What is the bug in this transaction?