sqlalchemy#
- class litestar.plugins.sqlalchemy.AuditColumns#
Bases:
objectCreated/Updated At Fields Mixin.
- class litestar.plugins.sqlalchemy.BigIntAuditBase#
Bases:
CommonTableAttributes,BigIntPrimaryKey,AuditColumns,DeclarativeBaseBase for declarative models with BigInt primary keys and audit columns.
- __init__(**kwargs: Any) None#
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata: ClassVar[MetaData] = MetaData()#
Refers to the
_schema.MetaDatacollection that will be used for new_schema.Tableobjects.See also
- registry: ClassVar[_RegistryType] = <sqlalchemy.orm.decl_api.registry object>#
Refers to the
_orm.registryin use where new_orm.Mapperobjects will be associated.
- class litestar.plugins.sqlalchemy.BigIntBase#
Bases:
BigIntPrimaryKey,CommonTableAttributes,DeclarativeBaseBase for all SQLAlchemy declarative models with BigInt primary keys.
- __init__(**kwargs: Any) None#
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata: ClassVar[MetaData] = MetaData()#
Refers to the
_schema.MetaDatacollection that will be used for new_schema.Tableobjects.See also
- registry: ClassVar[_RegistryType] = <sqlalchemy.orm.decl_api.registry object>#
Refers to the
_orm.registryin use where new_orm.Mapperobjects will be associated.
- class litestar.plugins.sqlalchemy.UUIDAuditBase#
Bases:
CommonTableAttributes,UUIDPrimaryKey,AuditColumns,DeclarativeBaseBase for declarative models with UUID primary keys and audit columns.
- registry: ClassVar[_RegistryType] = <sqlalchemy.orm.decl_api.registry object>#
Refers to the
_orm.registryin use where new_orm.Mapperobjects will be associated.
- __init__(**kwargs: Any) None#
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata: ClassVar[MetaData] = MetaData()#
Refers to the
_schema.MetaDatacollection that will be used for new_schema.Tableobjects.See also
- class litestar.plugins.sqlalchemy.CommonTableAttributes#
Bases:
objectCommon attributes for SQLALchemy tables.
- class litestar.plugins.sqlalchemy.UUIDBase#
Bases:
UUIDPrimaryKey,CommonTableAttributes,DeclarativeBaseBase for all SQLAlchemy declarative models with UUID primary keys.
- registry: ClassVar[_RegistryType] = <sqlalchemy.orm.decl_api.registry object>#
Refers to the
_orm.registryin use where new_orm.Mapperobjects will be associated.
- __init__(**kwargs: Any) None#
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata: ClassVar[MetaData] = MetaData()#
Refers to the
_schema.MetaDatacollection that will be used for new_schema.Tableobjects.See also
- class litestar.plugins.sqlalchemy.BigIntPrimaryKey#
Bases:
objectBigInt Primary Key Field Mixin.
- id#
BigInt Primary key column.
- class litestar.plugins.sqlalchemy.AlembicAsyncConfig#
Bases:
GenericAlembicConfigConfiguration for an Async Alembic’s
Config.For details see: https://alembic.sqlalchemy.org/en/latest/api/config.html
- __init__(script_config: str = 'alembic.ini', version_table_name: str = 'alembic_versions', version_table_schema: str | None = None, script_location: str = 'migrations', target_metadata: MetaData = MetaData(), user_module_prefix: str | None = 'sa.', render_as_batch: bool = True, compare_type: bool = False, template_path: str = '/home/runner/work/litestar/litestar/.venv/lib/python3.12/site-packages/advanced_alchemy/alembic/templates') None#
- class litestar.plugins.sqlalchemy.AlembicSyncConfig#
Bases:
GenericAlembicConfigConfiguration for a Sync Alembic’s
Config.For details see: https://alembic.sqlalchemy.org/en/latest/api/config.html
- __init__(script_config: str = 'alembic.ini', version_table_name: str = 'alembic_versions', version_table_schema: str | None = None, script_location: str = 'migrations', target_metadata: MetaData = MetaData(), user_module_prefix: str | None = 'sa.', render_as_batch: bool = True, compare_type: bool = False, template_path: str = '/home/runner/work/litestar/litestar/.venv/lib/python3.12/site-packages/advanced_alchemy/alembic/templates') None#
- class litestar.plugins.sqlalchemy.AsyncSessionConfig#
Bases:
GenericSessionConfig[AsyncConnection,AsyncEngine,AsyncSession]SQLAlchemy async session config.
- sync_session_class#
alias of
Empty
- __init__(autobegin: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, autoflush: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, bind: EngineT | ConnectionT | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, binds: dict[type[Any] | Mapper | TableClause | str, EngineT | ConnectionT] | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, class_: type[SessionT] | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, expire_on_commit: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, info: dict[str, Any] | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, join_transaction_mode: JoinTransactionMode | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, query_cls: type[Query] | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, twophase: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, sync_session_class: type[Session] | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>) None#
- class litestar.plugins.sqlalchemy.SyncSessionConfig#
Bases:
GenericSessionConfig[Connection,Engine,Session]
- class litestar.plugins.sqlalchemy.SQLAlchemyDTO#
Bases:
AbstractDTO,Generic[T]Support for domain modelling with SQLAlchemy.
- config: ClassVar[SQLAlchemyDTOConfig]#
Config objects to define properties of the DTO.
- classmethod generate_field_definitions(model_type: type[DeclarativeBase]) Generator[DTOFieldDefinition, None, None]#
Generate
FieldDefinitioninstances frommodel_type.- Yields:
FieldDefinitioninstances.
- classmethod detect_nested_field(field_definition: FieldDefinition) bool#
Return
Trueiffield_definitionrepresents a nested model field.- Parameters:
field_definition¶ – inspect type to determine if field represents a nested model.
- Returns:
Trueiffield_definitionrepresents a nested model field.
- class litestar.plugins.sqlalchemy.SQLAlchemyDTOConfig#
Bases:
DTOConfigAdditional controls for the generated SQLAlchemy DTO.
- include_implicit_fields: bool | Literal['hybrid-only'] = True#
Fields that are implicitly mapped are included.
Turning this off will lead to exclude all fields not using
Mappedannotation,When setting this to
hybrid-only, all implicitly mapped fields are excluded with the exception for hybrid properties.
- __init__(exclude: AbstractSet[str] = <factory>, include: AbstractSet[str] = <factory>, rename_fields: dict[str, str] = <factory>, rename_strategy: RenameStrategy | None = None, max_nested_depth: int = 1, partial: bool = False, underscore_fields_private: bool = True, experimental_codegen_backend: bool | None = None, include_implicit_fields: bool | Literal['hybrid-only'] = True) None#
- class litestar.plugins.sqlalchemy.SQLAlchemyAsyncConfig#
Bases:
SQLAlchemyAsyncConfigAsync SQLAlchemy Configuration.
- async before_send_handler(scope: Scope) None#
Handler to call before the ASGI message is sent.
The handler should handle closing the session stored in the ASGI scope, if it’s still open, and committing and uncommitted data.
- engine_dependency_key: str = 'db_engine'#
Key to use for the dependency injection of database engines.
- session_dependency_key: str = 'db_session'#
Key to use for the dependency injection of database sessions.
- engine_app_state_key: str = 'db_engine'#
Key under which to store the SQLAlchemy engine in the application
Stateinstance.
- session_maker_app_state_key: str = 'session_maker_class'#
Key under which to store the SQLAlchemy
sessionmakerin the applicationStateinstance.
- engine_config: EngineConfig#
Configuration for the SQLAlchemy engine.
The configuration options are documented in the SQLAlchemy documentation.
- create_session_maker() Callable[[], AsyncSession]#
Get a session maker. If none exists yet, create one.
- Returns:
Session factory used by the plugin.
- __init__(create_engine_callable: Callable[[str], AsyncEngine] = <function create_async_engine>, session_config: AsyncSessionConfig = <factory>, session_maker_class: type[async_sessionmaker] = <class 'sqlalchemy.ext.asyncio.session.async_sessionmaker'>, connection_string: str | None = None, engine_config: EngineConfig = <factory>, session_maker: Callable[[], SessionT] | None = None, engine_instance: EngineT | None = None, create_all: bool = False, metadata: MetaData | None = None, enable_touch_updated_timestamp_listener: bool = True, alembic_config: AlembicAsyncConfig = <factory>, before_send_handler: BeforeMessageSendHookHandler = <function default_before_send_handler>, engine_dependency_key: str = 'db_engine', session_dependency_key: str = 'db_session', engine_app_state_key: str = 'db_engine', session_maker_app_state_key: str = 'session_maker_class') None#
- provide_engine(state: State) AsyncEngine#
Create an engine instance.
- Parameters:
state¶ – The
Litestar.stateinstance.- Returns:
An engine instance.
- property signature_namespace: dict[str, Any]#
Return the plugin’s signature namespace.
- Returns:
A string keyed dict of names to be added to the namespace for signature forward reference resolution.
- class litestar.plugins.sqlalchemy.SQLAlchemyInitPlugin#
Bases:
InitPluginProtocol,CLIPluginProtocol,SlotsBaseSQLAlchemy application lifecycle configuration.
- __init__(config: SQLAlchemyAsyncConfig | SQLAlchemySyncConfig) None#
Initialize
SQLAlchemyPlugin.- Parameters:
config¶ – configure DB connection and hook handlers and dependencies.
- on_cli_init(cli: Group) None#
Called when the CLI is initialized.
This can be used to extend or override existing commands.
- Parameters:
cli¶ – The root
click.Groupof the Litestar CLI
Examples
from litestar import Litestar from litestar.plugins import CLIPluginProtocol from click import Group class CLIPlugin(CLIPluginProtocol): def on_cli_init(self, cli: Group) -> None: @cli.command() def is_debug_mode(app: Litestar): print(app.debug) app = Litestar(plugins=[CLIPlugin()])
- class litestar.plugins.sqlalchemy.SQLAlchemyPlugin#
Bases:
InitPluginProtocol,SlotsBaseA plugin that provides SQLAlchemy integration.
- __init__(config: SQLAlchemyAsyncConfig | SQLAlchemySyncConfig) None#
Initialize
SQLAlchemyPlugin.- Parameters:
config¶ – configure DB connection and hook handlers and dependencies.
- class litestar.plugins.sqlalchemy.SQLAlchemySerializationPlugin#
Bases:
SerializationPluginProtocol,SlotsBase- supports_type(field_definition: FieldDefinition) bool#
Given a value of indeterminate type, determine if this value is supported by the plugin.
- Parameters:
field_definition¶ – A parsed type.
- Returns:
Whether the type is supported by the plugin.
- create_dto_for_type(field_definition: FieldDefinition) type[SQLAlchemyDTO[Any]]#
Given a parsed type, create a DTO class.
- Parameters:
field_definition¶ – A parsed type.
- Returns:
A DTO class.
- class litestar.plugins.sqlalchemy.SQLAlchemySyncConfig#
Bases:
SQLAlchemySyncConfigSync SQLAlchemy Configuration.
- before_send_handler(scope: Scope) None#
Handler to call before the ASGI message is sent.
The handler should handle closing the session stored in the ASGI scope, if it’s still open, and committing and uncommitted data.
- engine_dependency_key: str = 'db_engine'#
Key to use for the dependency injection of database engines.
- session_dependency_key: str = 'db_session'#
Key to use for the dependency injection of database sessions.
- engine_app_state_key: str = 'db_engine'#
Key under which to store the SQLAlchemy engine in the application
Stateinstance.
- session_maker_app_state_key: str = 'session_maker_class'#
Key under which to store the SQLAlchemy
sessionmakerin the applicationStateinstance.
- engine_config: EngineConfig#
Configuration for the SQLAlchemy engine.
The configuration options are documented in the SQLAlchemy documentation.
- create_session_maker() Callable[[], Session]#
Get a session maker. If none exists yet, create one.
- Returns:
Session factory used by the plugin.
- __init__(create_engine_callable: Callable[[str], Engine] = <function create_engine>, session_config: SyncSessionConfig = <factory>, session_maker_class: type[sessionmaker] = <class 'sqlalchemy.orm.session.sessionmaker'>, connection_string: str | None = None, engine_config: EngineConfig = <factory>, session_maker: Callable[[], SessionT] | None = None, engine_instance: EngineT | None = None, create_all: bool = False, metadata: MetaData | None = None, enable_touch_updated_timestamp_listener: bool = True, alembic_config: AlembicSyncConfig = <factory>, before_send_handler: BeforeMessageSendHookHandler = <function default_before_send_handler>, engine_dependency_key: str = 'db_engine', session_dependency_key: str = 'db_session', engine_app_state_key: str = 'db_engine', session_maker_app_state_key: str = 'session_maker_class') None#
- provide_engine(state: State) Engine#
Create an engine instance.
- Parameters:
state¶ – The
Litestar.stateinstance.- Returns:
An engine instance.
- property signature_namespace: dict[str, Any]#
Return the plugin’s signature namespace.
- Returns:
A string keyed dict of names to be added to the namespace for signature forward reference resolution.
- class litestar.plugins.sqlalchemy.EngineConfig#
Bases:
EngineConfigConfiguration for SQLAlchemy’s
Engine.For details see: https://docs.sqlalchemy.org/en/20/core/engines.html
- json_deserializer(target_type: type[T] | EmptyType = _EmptyEnum.EMPTY, type_decoders: TypeDecodersSequence | None = None) Any#
For dialects that support the
JSONdatatype, this is a Python callable that will convert a JSON string to a Python object. By default, this is set to Litestar’sdecode_json()function.
- __init__(connect_args: dict[Any, Any] | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, echo: _EchoFlagType | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, echo_pool: _EchoFlagType | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, enable_from_linting: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, execution_options: Mapping[str, Any] | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, hide_parameters: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, insertmanyvalues_page_size: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, isolation_level: IsolationLevel | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, json_deserializer: Callable[[str], Any] = <function decode_json>, json_serializer: Callable[[Any], str] = <function serializer>, label_length: int | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, logging_name: str | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, max_identifier_length: int | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, max_overflow: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, module: Any | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, paramstyle: _ParamStyle | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool: Pool | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, poolclass: type[Pool] | None | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_logging_name: str | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_pre_ping: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_size: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_recycle: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_reset_on_return: Literal['rollback', 'commit'] | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_timeout: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, pool_use_lifo: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, plugins: list[str] | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, query_cache_size: int | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>, use_insertmanyvalues: bool | EmptyType = <class 'advanced_alchemy.utils.dataclass.Empty'>) None#
- json_serializer() str#
For dialects that support the JSON datatype, this is a Python callable that will render a given object as JSON. By default, Litestar’s
encode_json()is used.