Complete the code to start a transaction using a Node.js database client.
const client = await pool.connect(); try { await client.query('[1]'); // perform queries } finally { client.release(); }
In Node.js database clients like 'pg', the SQL command to start a transaction is BEGIN.
Complete the code to commit the transaction after successful queries.
try { await client.query('INSERT INTO users(name) VALUES($1)', ['Alice']); await client.query('[1]'); } catch (e) { await client.query('ROLLBACK'); }
The SQL command to save changes in a transaction is COMMIT.
Fix the error in the code to rollback the transaction on error.
try { await client.query('UPDATE accounts SET balance = balance - 100 WHERE id = $1', [accountId]); await client.query('UPDATE accounts SET balance = balance + 100 WHERE id = $2', [recipientId]); await client.query('COMMIT'); } catch (e) { await client.query('[1]'); }
The correct SQL command to undo changes in a transaction is ROLLBACK.
Fill both blanks to correctly handle transaction with async/await.
async function transferFunds(client, fromId, toId, amount) {
try {
await client.query('[1]');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, fromId]);
await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, toId]);
await client.query('[2]');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}Transactions start with BEGIN and end with COMMIT to save changes.
Fill all three blanks to create a transaction that rolls back on error and releases the client.
const client = await pool.connect(); try { await client.query('[1]'); await client.query('DELETE FROM orders WHERE id = $1', [orderId]); await client.query('[2]'); } catch (err) { await client.query('[3]'); throw err; } finally { client.release(); }
Start the transaction with BEGIN, save changes with COMMIT, and undo changes with ROLLBACK on error.
