mysql-connector-python#

Official MySQL driver with both sync and async support.

Sync Configuration#

class sqlspec.adapters.mysqlconnector.MysqlConnectorSyncConfig[source]#

Bases: SyncDatabaseConfig[MySQLConnection, MysqlConnectorConnectionPool, MysqlConnectorSyncDriver]

Configuration for mysql-connector synchronous MySQL connections.

driver_type#

alias of MysqlConnectorSyncDriver

__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]#

Open a standalone connection owned by the caller.

Pool settings are dropped, because mysql-connector routes connect to its own module-global pool as soon as it sees one, which would return a wrapper that neither applies autocommit nor closes on request.

Return type:

MySQLConnection

Returns:

A newly opened mysql-connector 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

Async Configuration#

class sqlspec.adapters.mysqlconnector.MysqlConnectorAsyncConfig[source]#

Bases: AsyncDatabaseConfig[MySQLConnection, MysqlConnectorAsyncPool, MysqlConnectorAsyncDriver]

Configuration for mysql-connector async MySQL connections.

driver_type#

alias of MysqlConnectorAsyncDriver

__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]#

Open and initialize a standalone connection owned by the caller.

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

Connection Parameters#

class sqlspec.adapters.mysqlconnector.MysqlConnectorSyncConnectionParams[source]#

Bases: _MysqlConnectorBaseConnectionParams

MysqlConnector sync connection parameters.

class sqlspec.adapters.mysqlconnector.MysqlConnectorAsyncConnectionParams[source]#

Bases: _MysqlConnectorBaseConnectionParams

MysqlConnector async connection parameters.

class sqlspec.adapters.mysqlconnector.MysqlConnectorCursorParams[source]#

Bases: TypedDict

Connector/Python cursor parameters routed by SQLSpec.

class sqlspec.adapters.mysqlconnector.MysqlConnectorFailoverTarget[source]#

Bases: TypedDict

Connector/Python failover target parameters.

Pool Parameters#

class sqlspec.adapters.mysqlconnector.MysqlConnectorPoolParams[source]#

Bases: MysqlConnectorSyncConnectionParams

MysqlConnector pooling parameters.

Note: pool_name, pool_size, and pool_reset_session are inherited from MysqlConnectorSyncConnectionParams.

Driver Features#

class sqlspec.adapters.mysqlconnector.MysqlConnectorDriverFeatures[source]#

Bases: TypedDict

MysqlConnector driver feature flags.

json_serializer: Custom JSON serializer function.

Defaults to sqlspec.utils.serializers.to_json.

json_deserializer: Custom JSON deserializer function.

Defaults to sqlspec.utils.serializers.from_json.

on_connection_create: Callback executed when a connection is acquired.

For sync: Callable[[MysqlConnectorSyncConnection], None] For async: Callable[[MysqlConnectorAsyncConnection], Awaitable[None]] Called once per physical connection for sync connections. Async pooled connections invoke the callback again after native session reset.

enable_events: Enable database event channel support.

Defaults to True when extension_config["events"] is configured.

events_backend: Event channel backend selection.

Only option: "poll_queue".

cursor_options: Cursor keyword arguments SQLSpec forwards to

connection.cursor() for statement execution.

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

dispatch_select_stream(statement, chunk_size)[source]#

Return a native mysql-connector row stream backed by an unbuffered cursor.

Return type:

Optional[SyncRowStream[dict[str, typing.Any]]]

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.

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

dispatch_select_stream(statement, chunk_size)[source]#

Return a native mysql-connector row stream backed by an unbuffered cursor.

Return type:

Optional[AsyncRowStream[dict[str, typing.Any]]]

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

Sync Data Dictionary#

class sqlspec.adapters.mysqlconnector.data_dictionary.MysqlConnectorSyncDataDictionary[source]#

Bases: MySQLSyncDataDictionary

MySQL-specific sync data dictionary for mysql-connector.

dialect: ClassVar[str] = 'mysql'#

Dialect identifier. Must be defined by subclasses as a class attribute.

Async Data Dictionary#

class sqlspec.adapters.mysqlconnector.data_dictionary.MysqlConnectorAsyncDataDictionary[source]#

Bases: MySQLAsyncDataDictionary

MySQL-specific async data dictionary for mysql-connector.

dialect: ClassVar[str] = 'mysql'#

Dialect identifier. Must be defined by subclasses as a class attribute.

Extension Settings#

Use the configuration types below in their corresponding extension_config namespace: "litestar", "events", or "adk" as supported by this adapter.

class sqlspec.adapters.mysqlconnector.litestar.MysqlConnectorLitestarConfig[source]#

Bases: LitestarConfig

MysqlConnector-specific Litestar settings.

Use inside extension_config["litestar"] with this adapter's session store.

table_options: NotRequired[str]#

Table DDL options.

index_options: NotRequired[str]#

Index DDL options.

class sqlspec.adapters.mysqlconnector.adk.MysqlConnectorADKConfig[source]#

Bases: ADKConfig

mysql-connector-specific ADK extension settings.

Use these keys inside extension_config["adk"] with mysql-connector ADK stores.

enable_event_generated_columns: NotRequired[bool]#

Create MySQL generated columns and indexes for common ADK event JSON paths.

enable_covering_indexes: NotRequired[bool]#

Add hot-path payload columns to MySQL ADK event replay indexes.

session_table_options: NotRequired[str]#

Raw MySQL table options appended to the ADK session table.

events_table_options: NotRequired[str]#

Raw MySQL table options appended to the ADK events table.

app_state_table_options: NotRequired[str]#

Raw MySQL table options appended to the ADK app state table.

user_state_table_options: NotRequired[str]#

Raw MySQL table options appended to the ADK user state table.

memory_table_options: NotRequired[str]#

Raw MySQL table options appended to the ADK memory table.