{"id":6892,"library":"sqlalchemy-mixins","title":"SQLAlchemy Mixins","description":"SQLAlchemy Mixins provides an Active Record pattern, Django-like query methods, nested eager loading, and enhanced `__repr__` for SQLAlchemy models. It aims to simplify common ORM operations by adding convenient class methods. The current stable version is 2.0.5, with releases occurring semi-regularly as features and fixes are added.","status":"active","version":"2.0.5","language":"en","source_language":"en","source_url":"https://github.com/absent1706/sqlalchemy-mixins","tags":["SQLAlchemy","ORM","Active Record","Mixins","Database","Productivity"],"install":[{"cmd":"pip install sqlalchemy-mixins","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core ORM library; `sqlalchemy-mixins` is built on top of it and requires at least version 1.3, with full 2.x support added in v2.0.0.","package":"SQLAlchemy"}],"imports":[{"symbol":"ActiveRecordMixin","correct":"from sqlalchemy_mixins import ActiveRecordMixin"},{"symbol":"InspectionMixin","correct":"from sqlalchemy_mixins import InspectionMixin"}],"quickstart":{"code":"from sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker, declarative_base\nfrom sqlalchemy_mixins import ActiveRecordMixin\nimport os\n\n# Setup SQLAlchemy engine and session (using in-memory sqlite for example)\n# For a real app, you might get this from an environment variable\ndatabase_url = os.environ.get('DATABASE_URL', 'sqlite:///test.db')\nengine = create_engine(database_url)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n# Define the declarative base for models\nBase = declarative_base()\n\n# Define a User model inheriting from Base and ActiveRecordMixin\nclass User(Base, ActiveRecordMixin):\n    __tablename__ = 'users'\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n    email = Column(String, unique=True)\n\n    def __repr__(self):\n        return f\"<User(id={self.id}, name='{self.name}')>\"\n\n# Create database tables\nBase.metadata.create_all(engine)\n\n# Set the session for ActiveRecordMixin for this model\nUser.set_session(session)\n\n# --- Usage Examples ---\n\n# 1. Create a new user (commit=True is available from v2.0.5)\nuser1 = User.create(name='Alice', email='alice@example.com', commit=True)\nprint(f\"Created user: {user1}\")\n\n# 2. Find a user by ID\nfound_user = User.find(user1.id)\nprint(f\"Found user by ID: {found_user}\")\n\n# 3. Find a user by attributes (Django-like filter)\nfiltered_user = User.where(name='Alice').first()\nprint(f\"Found user by name: {filtered_user}\")\n\n# 4. Update a user\nuser1.update(name='Alicia', commit=True)\nprint(f\"Updated user: {user1}\")\n\n# 5. Get all users\nall_users = User.all()\nprint(f\"Total users: {len(all_users)}\")\n\n# 6. Delete a user\nuser1.delete(commit=True)\nprint(f\"User {user1.name} deleted.\")\n\n# Clean up and close the session\nsession.close()\n","lang":"python","description":"This quickstart demonstrates how to set up `ActiveRecordMixin` with a SQLAlchemy declarative model. It covers common CRUD operations (create, find, update, delete) using the mixin's class methods, as well as basic query filtering. It highlights the use of `commit=True` which simplifies transaction management from version 2.0.5 onwards."},"warnings":[{"fix":"Ensure your application's SQLAlchemy usage aligns with SQLAlchemy 2.0's API style, even if running on SQLAlchemy 1.4 in compatibility mode. Consider upgrading SQLAlchemy to version 2.0 alongside `sqlalchemy-mixins`.","message":"Version 2.0.0 of `sqlalchemy-mixins` introduced support for SQLAlchemy 2.0. While it aims for backward compatibility with SQLAlchemy 1.4+, applications still using older SQLAlchemy 1.x specific patterns (e.g., `create_engine(..., strategy='threadlocal')` or explicit query objects without `.scalars()`) may encounter breaking changes or require migration.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always explicitly call `session.commit()` after operations that modify data or ensure you consistently use the `commit=True` argument when available in versions 2.0.5 and newer.","message":"By default, `ActiveRecordMixin` methods like `create`, `save`, `update`, and `delete` do not automatically commit changes to the database session. Prior to `v2.0.5`, manual `session.commit()` calls were always required. From `v2.0.5` onwards, a convenient `commit=True` keyword argument was added to these methods, but if omitted, manual commitment is still necessary.","severity":"gotcha","affected_versions":"<2.0.5 (manual commit always required), >=2.0.5 (optional `commit=True` kwarg)"},{"fix":"For concurrent applications, consider using SQLAlchemy's `scoped_session` for managing sessions per-thread/request, or ensure sessions are explicitly passed and managed within your application's context (e.g., via dependency injection or a request context).","message":"The `set_session()` method assigns a global session to the model class for `ActiveRecordMixin` operations. In concurrent environments (e.g., multi-threaded, async web applications), this can lead to issues where objects belong to different sessions, or transactions are not isolated correctly. While `v2.1.0` adds async support, proper session management is crucial for `v2.0.5` and earlier.","severity":"gotcha","affected_versions":"All versions, particularly prior to `v2.1.0`'s async features."}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z","problems":[]}