SQLAlchemy Adapter is the SQLAlchemy adapter for PyCasbin. With this library, Casbin can load policy from SQLAlchemy supported database or save policy to it. It supports various databases like PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, and Sybase. The library is currently at version 1.4.0 and releases are frequent, often including new features and compatibility updates.
pip install casbin-sqlalchemy-adapterVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize the SQLAlchemy adapter with a database (SQLite in this example), create a Casbin Enforcer, and then add, enforce, and remove policies. The policies are persisted in the configured database. Ensure you have Casbin model (`.conf`) and policy (`.csv`) files defined for the Enforcer to load initially, or manage all policies programmatically after initializing with an empty model.
Review the official GitHub releases and PyCasbin documentation for any changes related to model definitions or adapter instantiation. Ensure your Python version meets the `pycasbin` requirement of `>=3.8`.
Upgrade to the latest `casbin-sqlalchemy-adapter` version (>=1.1.0) for SQLAlchemy 2.0 compatibility fixes. If maintaining an older SQLAlchemy version, ensure your adapter version is compatible or pin SQLAlchemy to 1.x if necessary and check specific adapter version requirements.
To prevent automatic table creation, pass `create_table=False` when initializing the adapter: `adapter = Adapter('sqlite:///test.db', create_table=False)`.When using soft deletion, define a custom `CasbinRule` model with a boolean soft delete attribute (e.g., `is_deleted`) and initialize the adapter with `db_class=MyCustomCasbinRuleModel` and `db_class_softdelete_attribute=MyCustomCasbinRuleModel.is_deleted`.
Ensure the package is installed using `pip install casbin-sqlalchemy-adapter`. Verify the import statement is `from casbin_sqlalchemy_adapter import Adapter`.
Upgrade `casbin-sqlalchemy-adapter` to its latest version (`>=1.1.0`) which includes fixes for SQLAlchemy 2.0's `DeclarativeBase`. If still encountering issues, ensure your application's SQLAlchemy usage aligns with 2.0 conventions.
Ensure `create_table` is `True` (default) or that your migration system creates the `casbin_rule` table. For programmatic policy changes, confirm that auto-save is enabled (default behavior) or explicitly call `e.save_policy()` after modifications if you are managing policies manually or with an older adapter/enforcer.
Upgrade to `casbin-sqlalchemy-adapter` version 1.2.0 or newer, which includes a fix for nested session deadlocks.