SQLAlchemy Mate
SQLAlchemy Mate (sqlalchemy-mate) is a library that extends SQLAlchemy's ORM capabilities, simplifying common CRUD (Create, Read, Update, Delete) operations and session management. It aims to reduce boilerplate code for database interactions. The current version is 2.0.0.3, with recent updates focusing on the 2.x API. Releases often occur for minor bug fixes or feature enhancements within major versions.
Warnings
- breaking Major API changes occurred in version 2.0.0.0. Users upgrading from 1.x to 2.x will need to refactor their code, especially around session management (now primarily using `sm.extended_session_factory`) and the methods available on `ExtendedBase`.
- gotcha While `sqlalchemy-mate` simplifies session management with `sm.extended_session_factory`, it's still crucial to understand core SQLAlchemy session mechanics. Improper handling of sessions (e.g., not committing or rolling back transactions, not closing connections in long-running processes) can lead to unexpected data states or connection leaks.
- gotcha SQLAlchemy Mate extends SQLAlchemy; it does not replace it. A foundational understanding of core SQLAlchemy concepts (e.g., engines, metadata, declarative base, relationships, query objects) is still necessary for effective use, especially for complex queries or advanced ORM patterns.
Install
-
pip install sqlalchemy-mate
Imports
- ExtendedBase
from sqlalchemy_mate import ExtendedBase
- sm
from sqlalchemy_mate import sm
- engine_factory
from sqlalchemy_mate import engine_factory
Quickstart
import os
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy_mate import ExtendedBase, sm
# 1. Define your model inheriting from ExtendedBase
class User(ExtendedBase):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
email = Column(String(50), unique=True, nullable=False)
def __repr__(self):
return f"<User(id={self.id}, name='{self.name}', email='{self.email}')>"
# 2. Create an in-memory SQLite engine for demonstration
engine = create_engine("sqlite:///:memory:", echo=False)
# 3. Create tables based on the metadata
ExtendedBase.metadata.create_all(engine)
# 4. Use sm.extended_session_factory for simplified session management
with sm.extended_session_factory(engine) as session:
# 5. Create and add new objects
user1 = User(name="Alice", email="alice@example.com")
user2 = User(name="Bob", email="bob@example.com")
session.add_all([user1, user2])
session.commit() # Commit changes to the database
print("\n--- Added Users ---")
print(f"User 1 ID: {user1.id}") # IDs are assigned after commit
print(f"User 2 ID: {user2.id}")
# 6. Query objects
print("\n--- Query All Users ---")
all_users = session.query(User).all()
for user in all_users:
print(user)
print("\n--- Query Specific User ---")
alice = session.query(User).filter_by(name="Alice").one_or_none()
if alice:
print(f"Found Alice: {alice}")
# 7. Update an object
if alice:
alice.name = "Alicia"
session.add(alice) # Re-add modified object to session
session.commit()
print("\n--- Updated User ---")
print(f"Alice updated to: {session.query(User).filter_by(email='alice@example.com').one_or_none()}")
# 8. Delete an object
bob = session.query(User).filter_by(name="Bob").one_or_none()
if bob:
session.delete(bob)
session.commit()
print("\n--- Deleted User ---")
print(f"Bob deleted. Remaining users: {session.query(User).all()}")