Skip to content

aiomysql Adapter

from sqlspec.adapters.aiomysql import (
    AiomysqlConfig,
    AiomysqlConnectionParams,
    AiomysqlDriver,
    AiomysqlDriverFeatures,
    AiomysqlExceptionHandler,
    AiomysqlPoolParams,
)

Asynchronous MySQL and MariaDB adapter built on aiomysql. Inherited execution methods are documented on AsyncDriverAdapterBase. See the MySQL & MariaDB Setup Guide for usage examples.

Configuration & Parameters

AiomysqlConfig

Bases: AsyncDatabaseConfig[AiomysqlConnection, 'AiomysqlPool', AiomysqlDriver]

Configuration for aiomysql database connections.

AiomysqlConnectionParams

Bases: TypedDict

aiomysql connection parameters.

PyMySQL-only flat TLS and read/write timeout kwargs are intentionally excluded until aiomysql accepts them at runtime.

Attributes:

Name Type Description
dsn NotRequired[str]

MySQL/MariaDB connection URI (mysql://user:pass@host:port/db).

url NotRequired[str]

Connection URL alias parsed identically to dsn.

connection_string NotRequired[str]

Connection string alias parsed identically to dsn.

host NotRequired[str]

MySQL or MariaDB server hostname (defaults to 'localhost').

user NotRequired[str]

Database account username.

username NotRequired[str]

Alias normalized to user when user is omitted.

password NotRequired[str]

Password for the database user.

passwd NotRequired[str]

Legacy PyMySQL/aiomysql alias for password.

db NotRequired[str]

Default schema/database selected upon connecting.

database NotRequired[str]

Alias normalized to db when db is omitted.

port NotRequired[int]

MySQL/MariaDB TCP port (defaults to 3306).

unix_socket NotRequired[str]

Filesystem path to a local MySQL Unix domain socket.

charset NotRequired[str]

Connection character set (defaults to 'utf8mb4').

connect_timeout NotRequired[int | float | None]

TCP connection establishment timeout in seconds.

read_default_file NotRequired[str]

Path to a MySQL my.cnf option file.

read_default_group NotRequired[str]

Option group name read from read_default_file.

autocommit NotRequired[bool | None]

Enable MySQL autocommit mode on new connections.

allow_local_infile NotRequired[bool]

Alias enabling client-side LOAD DATA LOCAL INFILE transfers.

echo NotRequired[bool]

Log executed SQL statements through aiomysql.

local_infile NotRequired[bool]

Permit client-side LOAD DATA LOCAL INFILE transfers.

ssl NotRequired[SSLContext]

Configured ssl.SSLContext used for TLS connections.

sql_mode NotRequired[str]

Session sql_mode string applied at connection startup.

init_command NotRequired[str]

SQL statement executed immediately after authentication.

conv NotRequired[dict[int, Callable[[bytes], Any]] | dict[int, type[Any]] | Mapping[int, Any]]

Custom PyMySQL/aiomysql type decoder mapping.

use_unicode NotRequired[bool | None]

Decode text columns into Python str values (defaults to True).

client_flag NotRequired[int]

Bitmask of MySQL CLIENT_* capability flags.

cursorclass NotRequired[type[AiomysqlRawCursor] | type[AiomysqlDictCursor]]

Default aiomysql cursor class instantiated by conn.cursor().

cursor_class NotRequired[type[AiomysqlRawCursor] | type[AiomysqlDictCursor]]

Alias normalized to cursorclass.

auth_plugin NotRequired[str]

Explicit client authentication plugin name (such as caching_sha2_password).

program_name NotRequired[str]

Application name reported in MySQL connection attributes.

server_public_key NotRequired[str | bytes]

Server RSA public key PEM for SHA-256 password exchange.

loop NotRequired[Any]

Explicit asyncio event loop passed to aiomysql.

AiomysqlPoolParams

Bases: AiomysqlConnectionParams

aiomysql pool parameters.

Attributes:

Name Type Description
minsize NotRequired[int]

Minimum number of open connections maintained in aiomysql.Pool.

maxsize NotRequired[int]

Maximum number of concurrent connections allowed in aiomysql.Pool.

pool_recycle NotRequired[int]

Maximum connection age in seconds before recycling pooled connections.

AiomysqlDriverFeatures

Bases: TypedDict

Optional aiomysql driver feature flags for JSON serialization, bulk loading, and events.

Attributes:

Name Type Description
json_serializer NotRequired[Callable[[Any], str]]

Custom JSON serializer applied to bound JSON parameters (defaults to to_json).

json_deserializer NotRequired[Callable[[str], Any]]

Custom JSON deserializer applied to JSON result columns (defaults to from_json).

on_connection_create NotRequired[Callable[[AiomysqlConnection], Awaitable[None]]]

Async callback invoked once per physical aiomysql connection acquired from the pool.

enable_events NotRequired[bool]

Enable durable table-backed SQLSpec event queue support.

events_backend NotRequired[Literal['poll_queue']]

Event channel backend (poll_queue is the sole MySQL/MariaDB backend).

enable_local_infile_bulk_load NotRequired[bool]

Use LOAD DATA LOCAL INFILE for load_from_arrow when local infile is enabled.

Driver & Pool

AiomysqlDriver

Bases: AsyncDriverAdapterBase

MySQL/MariaDB database driver using aiomysql client library.

Implements asynchronous database operations for MySQL and MariaDB servers with support for parameter style conversion, type coercion, error handling, and transaction management.

AiomysqlExceptionHandler

Bases: BaseAsyncExceptionHandler

Async context manager for handling aiomysql (MySQL) database exceptions.

Maps MySQL error codes and SQLSTATE values from pymysql.err.Error to SQLSpec exceptions stored on pending_exception.

Extension Stores

AiomysqlStore

Bases: BaseSQLSpecStore['AiomysqlConfig']

MySQL/MariaDB session store using aiomysql driver.

Implements server-side session storage for Litestar using MySQL/MariaDB via the aiomysql driver. Provides efficient session management with: - Native async MySQL operations - UPSERT support using ON DUPLICATE KEY UPDATE - Automatic expiration handling - Efficient cleanup of expired sessions - Timezone-aware expiration (stored as UTC in DATETIME)

Parameters:

Name Type Description Default
config AiomysqlConfig

AiomysqlConfig instance.

required

AiomysqlADKStore

Bases: BaseAsyncADKStore['AiomysqlConfig']

MySQL/MariaDB ADK store using aiomysql driver.

AiomysqlADKMemoryStore

Bases: BaseAsyncADKMemoryStore['AiomysqlConfig']

MySQL/MariaDB ADK memory store using aiomysql driver.

AiomysqlEventQueueStore

Bases: BaseEventQueueStore[AiomysqlConfig]

MySQL-specific event queue store.

Generates DDL optimized for MySQL 5.7.8+ using native JSON type. Index creation emits a plain ADD INDEX statement; the migration gates it on a data_dictionary.get_indexes check since MySQL has no idempotent CREATE INDEX IF NOT EXISTS.

Parameters:

Name Type Description Default
config ConfigT

AiomysqlConfig with extension_config["events"] settings.

required