Junior — Middle
How to implement locking mechanisms at the database level to ensure data integrity?
sobes.tech AI
Answer from AI
To ensure data integrity at the database level, locking mechanisms are used to prevent simultaneous modifications of the same data by different transactions. The main approaches:
-
Lock-based transactions:
- Exclusive Locks — block reading and writing data by other transactions.
- Shared Locks — allow reading but not modifying data.
-
Transaction isolation levels: Control the visibility of changes between transactions, for example:
- Read Uncommitted
- Read Committed
- Repeatable Read
- Serializable
-
Optimistic and Pessimistic Locking:
- Pessimistic assumes locking data at the start of work.
- Optimistic assumes conflict checking at transaction commit.
-
Use of specific SQL constructs:
SELECT ... FOR UPDATE— locks selected rows for update.
Example in SQL for locking a row during update:
BEGIN TRANSACTION;
SELECT * FROM users WHERE id = 1 FOR UPDATE;
-- perform update
UPDATE users SET name = 'New Name' WHERE id = 1;
COMMIT;
In Node.js, transactions and locks are usually used via database management systems (e.g., PostgreSQL, MySQL) through appropriate drivers and ORM.