MySQL

SQLSpec provides three MySQL adapters covering sync and async use cases.

mysql-connector-python

Official MySQL driver with both sync and async support.

Sync Configuration

class sqlspec.adapters.mysqlconnector.MysqlConnectorSyncConfig[source]

Bases: SyncDatabaseConfig[MySQLConnection, MySQLConnectionPool, MysqlConnectorSyncDriver]

Configuration for mysql-connector synchronous MySQL connections.

driver_type

alias of MysqlConnectorSyncDriver

connection_type

alias of MySQLConnection

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]
create_connection()[source]

Create a database connection.

Return type:

MySQLConnection

get_signature_namespace()[source]

Get the signature namespace for this database configuration.

Returns a dictionary of type names to objects (classes, functions, or other callables) that should be registered with Litestar's signature namespace to prevent serialization attempts on database-specific structures.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to objects.

get_event_runtime_hints()[source]

Return default event runtime hints for this configuration.

Return type:

EventRuntimeHints

Async Configuration

class sqlspec.adapters.mysqlconnector.MysqlConnectorAsyncConfig[source]

Bases: NoPoolAsyncConfig[MySQLConnection, MysqlConnectorAsyncDriver]

Configuration for mysql-connector async MySQL connections.

driver_type

alias of MysqlConnectorAsyncDriver

connection_type

alias of MySQLConnection

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]
async create_connection()[source]

Create a database connection.

Return type:

MySQLConnection

provide_connection(*args, **kwargs)[source]

Provide a database connection context manager.

Return type:

MysqlConnectorAsyncConnectionContext

provide_session(*_args, statement_config=None, **_kwargs)[source]

Provide a database session context manager.

Return type:

MysqlConnectorAsyncSessionContext

get_signature_namespace()[source]

Get the signature namespace for this database configuration.

Returns a dictionary of type names to objects (classes, functions, or other callables) that should be registered with Litestar's signature namespace to prevent serialization attempts on database-specific structures.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to objects.

get_event_runtime_hints()[source]

Return default event runtime hints for this configuration.

Return type:

EventRuntimeHints

Sync Driver

class sqlspec.adapters.mysqlconnector.MysqlConnectorSyncDriver[source]

Bases: SyncDriverAdapterBase

MySQL/MariaDB database driver using mysql-connector sync library.

__init__(connection, statement_config=None, driver_features=None)[source]

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (MySQLConnection) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

dispatch_execute(cursor, statement)[source]

Execute a single SQL statement.

Must be implemented by each driver for database-specific execution logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data

dispatch_execute_many(cursor, statement)[source]

Execute SQL with multiple parameter sets (executemany).

Must be implemented by each driver for database-specific executemany logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data for the many operation

dispatch_execute_script(cursor, statement)[source]

Execute a SQL script containing multiple statements.

Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with script execution data including statement counts

begin()[source]

Begin a database transaction on the current connection.

Return type:

None

commit()[source]

Commit the current transaction on the current connection.

Return type:

None

rollback()[source]

Rollback the current transaction on the current connection.

Return type:

None

with_cursor(connection)[source]

Create and return a context manager for cursor acquisition and cleanup.

Returns a context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.

Return type:

MysqlConnectorSyncCursor

handle_database_exceptions()[source]

Handle database-specific exceptions and wrap them appropriately.

Return type:

MysqlConnectorSyncExceptionHandler

Returns:

Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __exit__ to avoid ABI boundary violations.

select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]

Stream a SELECT statement directly into storage.

Parameters:
  • statement (SQL | str) -- SQL statement to execute.

  • destination (str | Path) -- Storage destination path.

  • parameters (Any) -- Query parameters.

  • statement_config (StatementConfig | None) -- Optional statement configuration.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • format_hint (Optional[Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']]) -- Optional format hint for storage.

  • telemetry (StorageTelemetry | None) -- Optional telemetry dict to merge.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

Raises:

StorageCapabilityError -- If not implemented.

load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (Union[ArrowResult, typing.Any]) -- Arrow data source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load artifacts from storage into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (str | Path) -- Storage source path.

  • file_format (Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']) -- File format of source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

property data_dictionary: MysqlConnectorSyncDataDictionary

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]

Collect mysql-connector sync rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from mysql-connector cursor for the direct execution path.

Return type:

int

Async Driver

class sqlspec.adapters.mysqlconnector.MysqlConnectorAsyncDriver[source]

Bases: AsyncDriverAdapterBase

MySQL/MariaDB database driver using mysql-connector async library.

__init__(connection, statement_config=None, driver_features=None)[source]

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (MySQLConnection) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

async dispatch_execute(cursor, statement)[source]

Execute a single SQL statement.

Must be implemented by each driver for database-specific execution logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data

async dispatch_execute_many(cursor, statement)[source]

Execute SQL with multiple parameter sets (executemany).

Must be implemented by each driver for database-specific executemany logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data for the many operation

async dispatch_execute_script(cursor, statement)[source]

Execute a SQL script containing multiple statements.

Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with script execution data including statement counts

async begin()[source]

Begin a database transaction on the current connection.

Return type:

None

async commit()[source]

Commit the current transaction on the current connection.

Return type:

None

async rollback()[source]

Rollback the current transaction on the current connection.

Return type:

None

with_cursor(connection)[source]

Create and return an async context manager for cursor acquisition and cleanup.

Returns an async context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.

Return type:

MysqlConnectorAsyncCursor

handle_database_exceptions()[source]

Handle database-specific exceptions and wrap them appropriately.

Return type:

MysqlConnectorAsyncExceptionHandler

Returns:

Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __aexit__ to avoid ABI boundary violations.

async select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]

Stream a SELECT statement directly into storage.

Parameters:
  • statement (SQL | str) -- SQL statement to execute.

  • destination (str | Path) -- Storage destination path.

  • parameters (Any) -- Query parameters.

  • statement_config (StatementConfig | None) -- Optional statement configuration.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • format_hint (Optional[Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']]) -- Optional format hint for storage.

  • telemetry (StorageTelemetry | None) -- Optional telemetry dict to merge.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

async load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (Union[ArrowResult, typing.Any]) -- Arrow data source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

Raises:

NotImplementedError -- If not implemented.

async load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load artifacts from storage into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (str | Path) -- Storage source path.

  • file_format (Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']) -- File format of source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

property data_dictionary: MysqlConnectorAsyncDataDictionary

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]

Collect mysql-connector async rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from mysql-connector cursor for the direct execution path.

Return type:

int

PyMySQL

Pure-Python MySQL driver for sync usage.

Configuration

class sqlspec.adapters.pymysql.PyMysqlConfig[source]

Bases: SyncDatabaseConfig[Connection, PyMysqlConnectionPool, PyMysqlDriver]

Configuration for PyMySQL synchronous connections.

driver_type

alias of PyMysqlDriver

connection_type

alias of Connection

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]
create_connection()[source]

Create a database connection.

Return type:

Connection

get_signature_namespace()[source]

Get the signature namespace for this database configuration.

Returns a dictionary of type names to objects (classes, functions, or other callables) that should be registered with Litestar's signature namespace to prevent serialization attempts on database-specific structures.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to objects.

get_event_runtime_hints()[source]

Return default event runtime hints for this configuration.

Return type:

EventRuntimeHints

Driver

class sqlspec.adapters.pymysql.PyMysqlDriver[source]

Bases: SyncDriverAdapterBase

MySQL/MariaDB database driver using PyMySQL.

__init__(connection, statement_config=None, driver_features=None)[source]

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (Connection) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

dispatch_execute(cursor, statement)[source]

Execute a single SQL statement.

Must be implemented by each driver for database-specific execution logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data

dispatch_execute_many(cursor, statement)[source]

Execute SQL with multiple parameter sets (executemany).

Must be implemented by each driver for database-specific executemany logic.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with execution data for the many operation

dispatch_execute_script(cursor, statement)[source]

Execute a SQL script containing multiple statements.

Default implementation splits the script and executes statements individually. Drivers can override for database-specific script execution methods.

Parameters:
  • cursor (Any) -- Database cursor/connection object

  • statement (SQL) -- SQL statement object with all necessary data and configuration

Return type:

ExecutionResult

Returns:

ExecutionResult with script execution data including statement counts

begin()[source]

Begin a database transaction on the current connection.

Return type:

None

commit()[source]

Commit the current transaction on the current connection.

Return type:

None

rollback()[source]

Rollback the current transaction on the current connection.

Return type:

None

with_cursor(connection)[source]

Create and return a context manager for cursor acquisition and cleanup.

Returns a context manager that yields a cursor for database operations. Concrete implementations handle database-specific cursor creation and cleanup.

Return type:

PyMysqlCursor

handle_database_exceptions()[source]

Handle database-specific exceptions and wrap them appropriately.

Return type:

PyMysqlExceptionHandler

Returns:

Exception handler with deferred exception pattern for mypyc compatibility. The handler stores mapped exceptions in pending_exception rather than raising from __exit__ to avoid ABI boundary violations.

select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]

Stream a SELECT statement directly into storage.

Parameters:
  • statement (SQL | str) -- SQL statement to execute.

  • destination (str | Path) -- Storage destination path.

  • parameters (Any) -- Query parameters.

  • statement_config (StatementConfig | None) -- Optional statement configuration.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • format_hint (Optional[Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']]) -- Optional format hint for storage.

  • telemetry (StorageTelemetry | None) -- Optional telemetry dict to merge.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

Raises:

StorageCapabilityError -- If not implemented.

load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (Union[ArrowResult, typing.Any]) -- Arrow data source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load artifacts from storage into the target table.

Parameters:
  • table (str) -- Target table name.

  • source (str | Path) -- Storage source path.

  • file_format (Literal['jsonl', 'json', 'parquet', 'arrow-ipc', 'csv']) -- File format of source.

  • partitioner (dict[str, object] | None) -- Optional partitioner configuration.

  • overwrite (bool) -- Whether to overwrite existing data.

Return type:

StorageBridgeJob

Returns:

StorageBridgeJob with execution telemetry.

property data_dictionary: PyMysqlDataDictionary

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]

Collect PyMySQL rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from PyMySQL cursor for the direct execution path.

Return type:

int

asyncmy

Async MySQL driver.

Configuration

class sqlspec.adapters.asyncmy.AsyncmyConfig[source]

Bases: AsyncDatabaseConfig[Connection, AsyncmyPool, AsyncmyDriver]

Configuration for Asyncmy database connections.

Example:

config = AsyncmyConfig(
    connection_config=AsyncmyPoolParams(
        host="localhost", user="root", database="mydb"
    )
)
driver_type

alias of AsyncmyDriver

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]

Initialize Asyncmy configuration.

Parameters:
  • connection_config -- Connection and pool configuration parameters

  • connection_instance -- Existing pool instance to use

  • migration_config -- Migration configuration

  • statement_config -- Statement configuration override

  • driver_features -- Driver feature configuration (TypedDict or dict)

  • bind_key -- Optional unique identifier for this configuration

  • extension_config -- Extension-specific configuration (e.g., Litestar plugin settings)

  • observability_config -- Adapter-level observability overrides for lifecycle hooks and observers

  • **kwargs -- Additional keyword arguments

async close_pool()[source]

Close the connection pool.

Return type:

None

async create_connection()[source]

Create a single async connection (not from pool).

Return type:

Connection

Returns:

An Asyncmy connection instance.

async provide_pool(*args, **kwargs)[source]

Provide async pool instance.

Return type:

Pool

Returns:

The async connection pool.

get_signature_namespace()[source]

Get the signature namespace for Asyncmy types.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to types.

get_event_runtime_hints()[source]

Return queue polling defaults for Asyncmy adapters.

Return type:

EventRuntimeHints

Driver

class sqlspec.adapters.asyncmy.AsyncmyDriver[source]

Bases: AsyncDriverAdapterBase

MySQL/MariaDB database driver using AsyncMy client library.

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

__init__(connection, statement_config=None, driver_features=None)[source]

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (Connection) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

async dispatch_execute(cursor, statement)[source]

Execute single SQL statement.

Handles parameter processing, result fetching, and data transformation for MySQL/MariaDB operations.

Parameters:
  • cursor (Any) -- AsyncMy cursor object

  • statement (SQL) -- SQL statement to execute

Returns:

Statement execution results with data or row counts

Return type:

ExecutionResult

async dispatch_execute_many(cursor, statement)[source]

Execute SQL statement with multiple parameter sets.

Uses AsyncMy's executemany for batch operations with MySQL type conversion and parameter processing.

Parameters:
  • cursor (Any) -- AsyncMy cursor object

  • statement (SQL) -- SQL statement with multiple parameter sets

Returns:

Batch execution results

Return type:

ExecutionResult

Raises:

ValueError -- If no parameters provided for executemany operation

async dispatch_execute_script(cursor, statement)[source]

Execute SQL script with statement splitting and parameter handling.

Splits multi-statement scripts and executes each statement sequentially. Parameters are embedded as static values for script execution compatibility.

Parameters:
  • cursor (Any) -- AsyncMy cursor object

  • statement (SQL) -- SQL script to execute

Returns:

Script execution results with statement count

Return type:

ExecutionResult

async begin()[source]

Begin a database transaction.

Explicitly starts a MySQL transaction to ensure proper transaction boundaries.

Raises:

SQLSpecError -- If transaction initialization fails

Return type:

None

async commit()[source]

Commit the current transaction.

Raises:

SQLSpecError -- If transaction commit fails

Return type:

None

async rollback()[source]

Rollback the current transaction.

Raises:

SQLSpecError -- If transaction rollback fails

Return type:

None

with_cursor(connection)[source]

Create cursor context manager for the connection.

Parameters:

connection (Connection) -- AsyncMy database connection

Returns:

Context manager for cursor operations

Return type:

AsyncmyCursor

handle_database_exceptions()[source]

Provide exception handling context manager.

Returns:

Context manager for AsyncMy exception handling

Return type:

AsyncmyExceptionHandler

async select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]

Execute a query and stream Arrow-formatted results into storage.

Return type:

StorageBridgeJob

async load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into MySQL using batched inserts.

Return type:

StorageBridgeJob

async load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load staged artifacts from storage into MySQL.

Return type:

StorageBridgeJob

property data_dictionary: AsyncmyDataDictionary

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]

Collect asyncmy rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from asyncmy cursor for the direct execution path.

Return type:

int

aiomysql

Async MySQL driver (PyMySQL-compatible wire protocol, asyncio-native).

Configuration

class sqlspec.adapters.aiomysql.AiomysqlConfig[source]

Bases: AsyncDatabaseConfig[Connection, AiomysqlPool, AiomysqlDriver]

Configuration for aiomysql database connections.

Example:

config = AiomysqlConfig(
    connection_config=AiomysqlPoolParams(
        host="localhost", user="root", db="mydb"
    )
)
driver_type

alias of AiomysqlDriver

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]

Initialize aiomysql configuration.

Parameters:
  • connection_config -- Connection and pool configuration parameters

  • connection_instance -- Existing pool instance to use

  • migration_config -- Migration configuration

  • statement_config -- Statement configuration override

  • driver_features -- Driver feature configuration (TypedDict or dict)

  • bind_key -- Optional unique identifier for this configuration

  • extension_config -- Extension-specific configuration (e.g., Litestar plugin settings)

  • observability_config -- Adapter-level observability overrides for lifecycle hooks and observers

  • **kwargs -- Additional keyword arguments

async close_pool()[source]

Close the connection pool.

Return type:

None

async create_connection()[source]

Create a single async connection (not from pool).

Return type:

Connection

Returns:

An aiomysql connection instance.

async provide_pool(*args, **kwargs)[source]

Provide async pool instance.

Return type:

Pool

Returns:

The async connection pool.

get_signature_namespace()[source]

Get the signature namespace for aiomysql types.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to types.

get_event_runtime_hints()[source]

Return queue polling defaults for aiomysql adapters.

Return type:

EventRuntimeHints

Driver

class sqlspec.adapters.aiomysql.AiomysqlDriver[source]

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.

__init__(connection, statement_config=None, driver_features=None)[source]

Initialize driver adapter with connection and configuration.

Parameters:
  • connection (Connection) -- Database connection instance

  • statement_config (StatementConfig | None) -- Statement configuration for the driver

  • driver_features (dict[str, typing.Any] | None) -- Driver-specific features like extensions, secrets, and connection callbacks

  • observability -- Optional runtime handling lifecycle hooks, observers, and spans

async dispatch_execute(cursor, statement)[source]

Execute single SQL statement.

Parameters:
  • cursor (Any) -- aiomysql cursor object

  • statement (SQL) -- SQL statement to execute

Returns:

Statement execution results with data or row counts

Return type:

ExecutionResult

async dispatch_execute_many(cursor, statement)[source]

Execute SQL statement with multiple parameter sets.

Parameters:
  • cursor (Any) -- aiomysql cursor object

  • statement (SQL) -- SQL statement with multiple parameter sets

Returns:

Batch execution results

Return type:

ExecutionResult

Raises:

ValueError -- If no parameters provided for executemany operation

async dispatch_execute_script(cursor, statement)[source]

Execute SQL script with statement splitting and parameter handling.

Parameters:
  • cursor (Any) -- aiomysql cursor object

  • statement (SQL) -- SQL script to execute

Returns:

Script execution results with statement count

Return type:

ExecutionResult

async begin()[source]

Begin a database transaction.

Raises:

SQLSpecError -- If transaction initialization fails

Return type:

None

async commit()[source]

Commit the current transaction.

Raises:

SQLSpecError -- If transaction commit fails

Return type:

None

async rollback()[source]

Rollback the current transaction.

Raises:

SQLSpecError -- If transaction rollback fails

Return type:

None

with_cursor(connection)[source]

Create cursor context manager for the connection.

Parameters:

connection (Connection) -- aiomysql database connection

Returns:

Context manager for cursor operations

Return type:

AiomysqlCursor

handle_database_exceptions()[source]

Provide exception handling context manager.

Returns:

Context manager for aiomysql exception handling

Return type:

AiomysqlExceptionHandler

async select_to_storage(statement, destination, /, *parameters, statement_config=None, partitioner=None, format_hint=None, telemetry=None, **kwargs)[source]

Execute a query and stream Arrow-formatted results into storage.

Return type:

StorageBridgeJob

async load_from_arrow(table, source, *, partitioner=None, overwrite=False, telemetry=None)[source]

Load Arrow data into MySQL using batched inserts.

Return type:

StorageBridgeJob

async load_from_storage(table, source, *, file_format, partitioner=None, overwrite=False)[source]

Load staged artifacts from storage into MySQL.

Return type:

StorageBridgeJob

property data_dictionary: AiomysqlDataDictionary

Get the data dictionary for this driver.

Returns:

Data dictionary instance for metadata queries

collect_rows(cursor, fetched)[source]

Collect aiomysql rows for the direct execution path.

Return type:

tuple[list[typing.Any], list[str], int]

resolve_rowcount(cursor)[source]

Resolve rowcount from aiomysql cursor for the direct execution path.

Return type:

int

Connection Parameters

class sqlspec.adapters.aiomysql.AiomysqlConnectionParams[source]

Bases: TypedDict

aiomysql connection parameters.

Pool Parameters

class sqlspec.adapters.aiomysql.AiomysqlPoolParams[source]

Bases: AiomysqlConnectionParams

aiomysql pool parameters.

Driver Features

class sqlspec.adapters.aiomysql.AiomysqlDriverFeatures[source]

Bases: TypedDict

aiomysql driver feature flags.

MySQL/MariaDB handle JSON natively, but custom serializers can be provided for specialized use cases (e.g., orjson for performance, msgspec for type safety).

json_serializer: Custom JSON serializer function.

Defaults to sqlspec.utils.serializers.to_json. Use for performance (orjson) or custom encoding.

json_deserializer: Custom JSON deserializer function.

Defaults to sqlspec.utils.serializers.from_json. Use for performance (orjson) or custom decoding.

on_connection_create: Async callback executed when a connection is acquired from pool.

Receives the raw aiomysql connection for low-level driver configuration. Called exactly once per physical connection using WeakSet tracking.

enable_events: Enable database event channel support.

Defaults to True when extension_config["events"] is configured. Provides pub/sub capabilities via table-backed queue (MySQL/MariaDB have no native pub/sub). Requires extension_config["events"] for migration setup.

events_backend: Event channel backend selection.

Only option: "table_queue" (durable table-backed queue with retries and exactly-once delivery). MySQL/MariaDB do not have native pub/sub, so table_queue is the only backend. Defaults to "table_queue".