SQLAlchemy Mate

2.0.0.3 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to define a model using `ExtendedBase`, create an in-memory SQLite database, manage sessions with `sm.extended_session_factory`, and perform basic CRUD operations (create, read, update, delete) on the `User` model.

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()}")

view raw JSON →