Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A carefully crafted, thoroughly tested, optimized companion library for SQLAlchemy

License

NotificationsYou must be signed in to change notification settings

litestar-org/advanced-alchemy

Advanced Alchemy Logo

ProjectStatus
CI/CDLatest ReleaseciDocumentation Building
QualityCoverageQuality Gate StatusMaintainability RatingReliability RatingSecurity Rating
PackagePyPI - VersionPyPI - Support Python VersionsAdvanced Alchemy PyPI - Downloads
CommunityDiscordMatrix
MetaLitestar Projecttypes - MypyLicense - MITlinting - Ruff

Check out theproject documentation 📚 for more information.

About

A carefully crafted, thoroughly tested, optimized companion library for SQLAlchemy,offering:

  • Sync and async repositories, featuring common CRUD and highly optimized bulk operations
  • Integration with major web frameworks including Litestar, Starlette, FastAPI, Sanic
  • Custom-built alembic configuration and CLI with optional framework integration
  • Utility base classes with audit columns, primary keys and utility functions
  • Built inFile Object data type for storing objects:
    • Unified interface for various storage backends (fsspec andobstore)
    • Optional lifecycle event hooks integrated with SQLAlchemy's event system to automatically save and delete files as records are inserted, updated, or deleted.
  • Optimized JSON types including a custom JSON type for Oracle
  • Integrated support for UUID6 and UUID7 usinguuid-utils (install with theuuid extra)
  • Integrated support for Nano ID usingfastnanoid (install with thenanoid extra)
  • Custom encrypted text type with multiple backend support includingpgcrypto for PostgreSQL and the Fernet implementation fromcryptography for other databases
  • Custom password hashing type with multiple backend support includingArgon2,Passlib, andPwdlib with automatic salt generation
  • Pre-configured base classes with audit columns UUID or Big Integer primary keys andasentinel column.
  • Synchronous and asynchronous repositories featuring:
    • Common CRUD operations for SQLAlchemy models
    • Bulk inserts, updates, upserts, and deletes with dialect-specific enhancements
    • Integrated counts, pagination, sorting, filtering withLIKE,IN, and dates before and/or after.
  • Tested support for multiple database backends including:
  • ...and much more

Usage

Installation

pip install advanced-alchemy

Important

Check outthe installation guide in our official documentation!

Repositories

Advanced Alchemy includes a set of asynchronous and synchronous repository classes for easy CRUDoperations on your SQLAlchemy models.

Click to expand the example
fromadvanced_alchemyimportbase,repository,configfromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportMapped,sessionmakerclassUser(base.UUIDBase):# you can optionally override the generated table name by manually setting it.__tablename__="user_account"# type: ignore[assignment]email:Mapped[str]name:Mapped[str]classUserRepository(repository.SQLAlchemySyncRepository[User]):"""User repository."""model_type=Userdb=config.SQLAlchemySyncConfig(connection_string="duckdb:///:memory:",session_config=config.SyncSessionConfig(expire_on_commit=False))# Initializes the database.withdb.get_engine().begin()asconn:User.metadata.create_all(conn)withdb.get_session()asdb_session:repo=UserRepository(session=db_session)# 1) Create multiple users with `add_many`bulk_users= [        {"email":'cody@litestar.dev','name':'Cody'},        {"email":'janek@litestar.dev','name':'Janek'},        {"email":'peter@litestar.dev','name':'Peter'},        {"email":'jacob@litestar.dev','name':'Jacob'}    ]objs=repo.add_many([User(**raw_user)forraw_userinbulk_users])db_session.commit()print(f"Created{len(objs)} new objects.")# 2) Select paginated data and total row count.  Pass additional filters as kwargscreated_objs,total_objs=repo.list_and_count(LimitOffset(limit=10,offset=0),name="Cody")print(f"Selected{len(created_objs)} records out of a total of{total_objs}.")# 3) Let's remove the batch of records selected.deleted_objs=repo.delete_many([new_obj.idfornew_objincreated_objs])print(f"Removed{len(deleted_objs)} records out of a total of{total_objs}.")# 4) Let's count the remaining rowsremaining_count=repo.count()print(f"Found{remaining_count} remaining records after delete.")

For a full standalone example, see the samplehere

Services

Advanced Alchemy includes an additional service class to make working with a repository easier.This class is designed to accept data as a dictionary or SQLAlchemy model,and it will handle the type conversions for you.

Here's the same example from above but using a service to create the data:
fromadvanced_alchemyimportbase,repository,filters,service,configfromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportMapped,sessionmakerclassUser(base.UUIDBase):# you can optionally override the generated table name by manually setting it.__tablename__="user_account"# type: ignore[assignment]email:Mapped[str]name:Mapped[str]classUserService(service.SQLAlchemySyncRepositoryService[User]):"""User repository."""classRepo(repository.SQLAlchemySyncRepository[User]):"""User repository."""model_type=Userrepository_type=Repodb=config.SQLAlchemySyncConfig(connection_string="duckdb:///:memory:",session_config=config.SyncSessionConfig(expire_on_commit=False))# Initializes the database.withdb.get_engine().begin()asconn:User.metadata.create_all(conn)withdb.get_session()asdb_session:service=UserService(session=db_session)# 1) Create multiple users with `add_many`objs=service.create_many([        {"email":'cody@litestar.dev','name':'Cody'},        {"email":'janek@litestar.dev','name':'Janek'},        {"email":'peter@litestar.dev','name':'Peter'},        {"email":'jacob@litestar.dev','name':'Jacob'}    ])print(objs)print(f"Created{len(objs)} new objects.")# 2) Select paginated data and total row count.  Pass additional filters as kwargscreated_objs,total_objs=service.list_and_count(LimitOffset(limit=10,offset=0),name="Cody")print(f"Selected{len(created_objs)} records out of a total of{total_objs}.")# 3) Let's remove the batch of records selected.deleted_objs=service.delete_many([new_obj.idfornew_objincreated_objs])print(f"Removed{len(deleted_objs)} records out of a total of{total_objs}.")# 4) Let's count the remaining rowsremaining_count=service.count()print(f"Found{remaining_count} remaining records after delete.")

Web Frameworks

Advanced Alchemy works with nearly all Python web frameworks.Several helpers for popular libraries are included, and additional PRs to support others are welcomed.

Litestar

Advanced Alchemy is the official SQLAlchemy integration for Litestar.

In addition to installing withpip install advanced-alchemy,it can also be installed as a Litestar extra withpip install litestar[sqlalchemy].

Litestar Example
fromlitestarimportLitestarfromlitestar.plugins.sqlalchemyimportSQLAlchemyPlugin,SQLAlchemyAsyncConfig# alternately...# from advanced_alchemy.extensions.litestar import SQLAlchemyAsyncConfig, SQLAlchemyPluginalchemy=SQLAlchemyPlugin(config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),)app=Litestar(plugins=[alchemy])

For a full Litestar example, checkhere

Flask

Flask Example
fromflaskimportFlaskfromadvanced_alchemy.extensions.flaskimportAdvancedAlchemy,SQLAlchemySyncConfigapp=Flask(__name__)alchemy=AdvancedAlchemy(config=SQLAlchemySyncConfig(connection_string="duckdb:///:memory:"),app=app,)

For a full Flask example, seehere

FastAPI

FastAPI Example
fromadvanced_alchemy.extensions.fastapiimportAdvancedAlchemy,SQLAlchemyAsyncConfigfromfastapiimportFastAPIapp=FastAPI()alchemy=AdvancedAlchemy(config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),app=app,)

For a full FastAPI example with optional CLI integration, seehere

Starlette

Pre-built Example Apps
fromadvanced_alchemy.extensions.starletteimportAdvancedAlchemy,SQLAlchemyAsyncConfigfromstarlette.applicationsimportStarletteapp=Starlette()alchemy=AdvancedAlchemy(config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),app=app,)

Sanic

Pre-built Example Apps
fromsanicimportSanicfromsanic_extimportExtendfromadvanced_alchemy.extensions.sanicimportAdvancedAlchemy,SQLAlchemyAsyncConfigapp=Sanic("AlchemySanicApp")alchemy=AdvancedAlchemy(sqlalchemy_config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),)Extend.register(alchemy)

Contributing

AllLitestar Organization projects will always be a community-centered, available for contributions of any size.

Before contributing, please review thecontribution guide.

If you have any questions, reach out to us onDiscord, our org-wideGitHub discussions page,or theproject-specific GitHub discussions page.


Litestar Organization Project
An officialLitestar Organization Project

Contributors53

Languages


[8]ページ先頭

©2009-2025 Movatter.jp