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
- __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.
The connection carries the same parameters and creation hook the pool applies, but it is not the pool's thread-local connection, so closing it leaves the pool usable.
- Returns:
A newly opened 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.
Cloud SQL Connector#
PyMySQL configs can use the in-process Google Cloud SQL Python Connector by
installing the cloud-sql extra and enabling the connector in
driver_features:
from sqlspec.adapters.pymysql import PyMysqlConfig
config = PyMysqlConfig(
connection_config={
"user": "app-user",
"password": "secret",
"database": "app",
},
driver_features={
"enable_cloud_sql": True,
"cloud_sql_instance": "project:region:instance",
"cloud_sql_ip_type": "PRIVATE",
},
)
When enable_cloud_sql is true, cloud_sql_instance is required and must
use project:region:instance format. Host, port, socket, and direct auth
connection values are passed through the connector rather than opened directly
by PyMySQL.
Driver#
- class sqlspec.adapters.pymysql.PyMysqlDriver[source]#
Bases:
SyncDriverAdapterBaseMySQL/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 instancestatement_config¶ (
StatementConfig|None) -- Statement configuration for the driverdriver_features¶ (
dict[str, typing.Any] |None) -- Driver-specific features like extensions, secrets, and connection callbacksobservability¶ -- 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:
- Return type:
- 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:
- Return type:
- 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:
- Return type:
- Returns:
ExecutionResult with script execution data including statement counts
- 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
- dispatch_select_stream(statement, chunk_size)[source]#
Return a native PyMySQL row stream backed by an unbuffered
SSCursor.- Return type:
Optional[SyncRowStream[dict[str, typing.Any]]]
- 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_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:
- 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:
- Return type:
- 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.
- property data_dictionary: PyMysqlDataDictionary#
Get the data dictionary for this driver.
- Returns:
Data dictionary instance for metadata queries
Connection Parameters#
Pool Parameters#
- class sqlspec.adapters.pymysql.PyMysqlPoolParams[source]#
Bases:
PyMysqlConnectionParamsPyMySQL pool parameters.
Driver Features#
- class sqlspec.adapters.pymysql.PyMysqlDriverFeatures[source]#
Bases:
TypedDictPyMySQL 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 created.
Receives the raw pymysql connection for low-level driver configuration. Runs after connection creation.
enable_events: Enable database event channel support. events_backend: Event channel backend selection. enable_local_infile_bulk_load: Route load_from_arrow through LOAD DATA LOCAL INFILE.
Defaults to the connection's local_infile or allow_local_infile opt-in. Set False to force executemany on an opted-in connection.
- enable_cloud_sql: Enable Google Cloud SQL connector integration.
Requires cloud-sql-python-connector package. Defaults to False (explicit opt-in required).
- cloud_sql_instance: Cloud SQL instance connection name.
Format: "project:region:instance" Required when enable_cloud_sql is True.
- cloud_sql_enable_iam_auth: Enable IAM database authentication.
Defaults to False for passwordless authentication.
- cloud_sql_ip_type: IP address type for connection.
Options: "PUBLIC", "PRIVATE", "PSC" Defaults to "PRIVATE".
Connection Pool#
- class sqlspec.adapters.pymysql.pool.PyMysqlConnectionPool[source]#
Bases:
objectThread-local connection manager for PyMySQL.
- __init__(connection_parameters, recycle_seconds=86400, health_check_interval=30.0, on_connection_create=None, connection_factory=None)[source]#
Initialize the thread-local connection manager.
- Parameters:
connection_parameters¶ (
dict[str, typing.Any]) -- PyMySQL connection parametersrecycle_seconds¶ (
int) -- Connection recycle time in seconds (default 24h)health_check_interval¶ (
float) -- Seconds of idle time before running health checkon_connection_create¶ (typing.Callable[[pymysql.connections.Connection],
None] |None) -- Callback executed when connection is createdconnection_factory¶ (typing.Callable[[],
Connection] |None) -- Optional factory for custom connection creation
- new_connection()[source]#
Open a standalone connection configured like a pooled one.
The result is owned by the caller: it is not thread-local and is not tracked for pool shutdown.
- Returns:
A newly opened, fully configured connection.
- Return type:
Connection
- get_connection()[source]#
Get a thread-local connection.
- Yields:
A thread-local database connection.
Data Dictionary#
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.pymysql.litestar.PyMysqlLitestarConfig[source]#
Bases:
LitestarConfigPyMysql-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.pymysql.adk.PyMysqlADKConfig[source]#
Bases:
ADKConfigPyMySQL-specific ADK extension settings.
Use these keys inside
extension_config["adk"]with the PyMySQL ADK store.- 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.