Sobes.tech
Junior — Middle

What methods can be used to prevent competition when changing data in a database?

sobes.tech AI

Answer from AI

The following methods are used to prevent conflicts when modifying data in a database:

  1. Locks — allow restricting access to data during a transaction. There are different levels of locks: on rows, tables, etc.

  2. Optimistic Locking — assumes conflicts are rare. When saving data, it checks whether it has changed since it was read (for example, by version or timestamp). If it has changed, the operation is rolled back.

  3. Transactions — using atomic operations with support for ACID properties ensures data integrity.

  4. Transaction Isolation — setting isolation levels (READ COMMITTED, SERIALIZABLE, etc.) helps control the visibility of changes between transactions.

  5. Use of unique indexes and constraints — prevents duplication and incorrect modifications.

An example of optimistic locking in Python using SQLAlchemy:

from sqlalchemy import Column, Integer, String, Version
from sqlalchemy.orm import sessionmaker

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    version = Column(Integer, nullable=False, default=0)

# When updating, the version is checked
session = sessionmaker(bind=engine)()
user = session.query(User).filter_by(id=1).one()
user.name = 'New Name'
user.version += 1
try:
    session.commit()
except:
    session.rollback()
    print('Data was modified by another user')

Thus, the choice of method depends on performance requirements and data consistency.