I have a question about handling transactions in a database (e.g., PostgreSQL or DynamoDB) using an ORM (e.g., TypeORM or Dynamoose).
Scenario:
I need to perform the following steps atomically:
- Read a value from Table A (SQL query)
- Read a value from Table B (SQL query)
- Read a value from Table C (SQL query)
- Perform calculations in JavaScript:
temp = A + B
- Conditional check in JavaScript:
if (temp < C)
- If the condition is met, write
temp
to Table D (SQL query)
I want steps 1, 2, 3, and 6 to be executed within a single transaction, ensuring data consistency.
Questions:
- Will the database transaction wait for JavaScript to process steps 4 and 5 before executing step 6?
- If the database can wait, how does that mechanism work?
- If another process modifies Table A after my transaction starts but before it commits, will my transaction be rolled back automatically?
- How does TypeORM handle this kind of transaction?
SQL Approach:
Would it be possible to start a transaction with the following SQL statements?
BEGIN;
SELECT value FROM TableA WHERE id = 1;
SELECT value FROM TableB WHERE id = 2;
SELECT value FROM TableC WHERE id = 3;
Then, process the retrieved values in JavaScript and decide whether to proceed. Finally, if the condition is met, execute:
UPDATE TableD SET value = ? WHERE id = 4;
COMMIT;
Would this ensure that Table A and Table B are not modified by another transaction while processing JavaScript logic?
TypeORM Example:
How can this be handled in TypeORM?
await dataSource.transaction(async (transactionalEntityManager) => {
const aValue = await transactionalEntityManager.findOne(TableA, { where: { id: 1 } });
const bValue = await transactionalEntityManager.findOne(TableB, { where: { id: 2 } });
const cValue = await transactionalEntityManager.findOne(TableC, { where: { id: 3 } });
const temp = aValue.value + bValue.value;
if (temp < cValue.value) {
await transactionalEntityManager.update(TableD, { id: 4 }, { value: temp });
}
});
Would TypeORM ensure that the transaction locks the data until the JavaScript logic is completed? What happens if another process modifies Table A before the transaction commits?
Any insights into best practices or potential issues would be greatly appreciated!