To provide a more complex example of the Unit of Work pattern, I'll build on the basic concept by introducing multiple entities and relationships between them. This example will include operations that span multiple tables and demonstrate managing complex transactions involving related data changes. We'll still use SQLAlchemy for ORM (Object-Relational Mapping).
Example: Complex Unit of Work Pattern in Python
Entities and Relationships
We'll define a few entities with relationships:
- User: Represents application users.
- Order: Represents orders placed by users.
- Product: Represents products that can be ordered.
Each user can place multiple orders, and each order can include multiple products.
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
Base = declarative_base()
# Association table for many-to-many relationship between Orders and Products
order_product_association = Table(
'order_product', Base.metadata,
Column('order_id', Integer, ForeignKey('orders.id')),
Column('product_id', Integer, ForeignKey('products.id'))
)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
orders = relationship("Order", back_populates="user")
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", back_populates="orders")
products = relationship("Product", secondary=order_product_association, back_populates="orders")
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String(50))
orders = relationship("Order", secondary=order_product_association, back_populates="products")
# Unit of Work Pattern Implementation
class UnitOfWork:
def __init__(self, session_factory):
self.session_factory = session_factory
self._session = None
def __enter__(self):
self._session = self.session_factory()
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
self._session.rollback()
else:
self._session.commit()
self._session.close()
@property
def session(self):
return self._session
# Database setup
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
SessionFactory = sessionmaker(bind=engine)
# Operations using Unit of Work
def add_user(name):
with UnitOfWork(SessionFactory) as uow:
user = User(name=name)
uow.session.add(user)
return user
def add_product(name):
with UnitOfWork(SessionFactory) as uow:
product = Product(name=name)
uow.session.add(product)
return product
def place_order(user, product_ids):
with UnitOfWork(SessionFactory) as uow:
order = Order(user=user)
uow.session.add(order)
for product_id in product_ids:
product = uow.session.query(Product).filter_by(id=product_id).one()
order.products.append(product)
def get_user_orders(user_id):
with UnitOfWork(SessionFactory) as uow:
user = uow.session.query(User).filter_by(id=user_id).one()
return [(order.id, [product.name for product in order.products]) for order in user.orders]
# Example of usage
alice = add_user('Alice')
bob = add_user('Bob')
apple = add_product('Apple')
banana = add_product('Banana')
place_order(alice, [apple.id, banana.id])
place_order(bob, [banana.id])
# Retrieve and display orders for Alice
alice_orders = get_user_orders(alice.id)
for order_id, products in alice_orders:
print(f"Order ID: {order_id}, Products: {', '.join(products)}")
Explanation:
-
Database Model:
User, Order, and Product classes represent entities.
- An association table
order_product_association handles the many-to-many relationship between Order and Product.
-
Unit of Work:
- Encapsulates database session operations, allowing for clean transaction handling.
- Commits if all operations are successful, and rolls back in case of failure.
-
Operations:
add_user: Adds a new user.
add_product: Adds a new product.
place_order: Creates a new order for a user and associates selected products with the order.
get_user_orders: Retrieves all orders for a specific user and the products in each order.
This setup provides a robust way to handle complex transaction logic involving multiple entities and managing their relationships within a consistent transactional context.