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]#
get_cloud_sql_connector()[source]#

Return the configured Cloud SQL connector instance.

Return type:

Any | None

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

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: 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

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 (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: 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

Data Dictionary#

class sqlspec.adapters.pymysql.data_dictionary.PyMysqlDataDictionary[source]#

Bases: SyncDataDictionaryBase

MySQL-specific sync data dictionary.

dialect: ClassVar[str] = 'mysql'#

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

__init__()[source]#
get_version(driver)[source]#

Get MySQL database version information.

Return type:

VersionInfo | None

get_feature_flag(driver, feature)[source]#

Check if MySQL database supports a specific feature.

Return type:

bool

get_metadata_capabilities(driver, domains=None)[source]#

Get data-dictionary capability profile.

Return type:

MetadataCapabilityProfile

get_schemas(driver)[source]#

Get schema metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_objects(driver, schema=None)[source]#

Get object metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_table_details(driver, table, schema=None)[source]#

Get rich table metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_constraints(driver, table=None, schema=None)[source]#

Get constraint metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_views(driver, schema=None)[source]#

Get view metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_routines(driver, schema=None)[source]#

Get routine metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_privileges(driver, object_name=None, schema=None)[source]#

Get privilege metadata from INFORMATION_SCHEMA.

Return type:

MetadataResult

get_ddl(driver, object_name, schema=None, *, object_type='table', include_dependencies=True, prefer_native=True, redact=True)[source]#

Get native SHOW CREATE output and replay-sensitive context for a table.

Return type:

DDLResult

get_system_metadata(driver, request=None, **kwargs)[source]#

Get opt-in system metadata from performance_schema or sys.

Return type:

SystemMetadataResult

get_optimal_type(driver, type_category)[source]#

Get optimal MySQL type for a category.

Return type:

str

get_tables(driver, schema=None)[source]#

Get tables sorted by topological dependency order using the MySQL catalog.

Return type:

list[TableMetadata]

get_columns(driver, table=None, schema=None)[source]#

Get column information for a table or schema.

Return type:

list[ColumnMetadata]

get_indexes(driver, table=None, schema=None)[source]#

Get index metadata for a table or schema.

Return type:

list[IndexMetadata]

get_foreign_keys(driver, table=None, schema=None)[source]#

Get foreign key metadata.

Return type:

list[ForeignKeyMetadata]