Consider a Node.js application using a database client that supports transactions. If you start a transaction but never commit or rollback, what will be the state of the transaction?
async function runTransaction(client) { await client.query('BEGIN'); await client.query('INSERT INTO users(name) VALUES($1)', ['Alice']); // No COMMIT or ROLLBACK }
Think about what happens when a transaction is left hanging without a commit or rollback.
If a transaction is started but not committed or rolled back, it stays open. This can cause locks on the affected rows or tables, potentially blocking other operations until the connection closes or a timeout happens.
Given a database client with async query support, which code snippet correctly starts a transaction, inserts a row, commits, and handles errors?
Remember to commit only if no error occurs, and rollback on error.
Option C correctly wraps the transaction in a try/catch block. It commits if all queries succeed, and rolls back if any error occurs, then rethrows the error.
Examine the following code snippet. Why might it cause a deadlock when multiple instances run concurrently?
async function transferFunds(client, fromId, toId, amount) { await client.query('BEGIN'); 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('COMMIT'); }
Think about how concurrent transactions lock rows in different orders.
If two transactions update accounts in opposite order (one updates fromId then toId, the other toId then fromId), they can each hold a lock the other needs, causing a deadlock.
Assume account 1 has balance 100, account 2 has balance 50. What are their balances after this transaction completes?
async function transfer(client) { await client.query('BEGIN'); await client.query('UPDATE accounts SET balance = balance - 30 WHERE id = 1'); await client.query('UPDATE accounts SET balance = balance + 30 WHERE id = 2'); await client.query('COMMIT'); } // Initial balances: account 1 = 100, account 2 = 50
Subtract 30 from account 1 and add 30 to account 2.
The transaction deducts 30 from account 1 (100 - 30 = 70) and adds 30 to account 2 (50 + 30 = 80). The commit makes these changes permanent.
Choose the statement that best explains the 'Isolation' property of transactions.
Think about how transactions behave when running at the same time.
Isolation means each transaction runs as if it were alone, so concurrent transactions do not see partial changes from others, preventing interference.