Skip to content

feat: add aiomysql adapter#413

Merged
cofin merged 14 commits intolitestar-org:mainfrom
hasansezertasan:feat/hasansezertasan/add-aiomysql-adapter
Apr 22, 2026
Merged

feat: add aiomysql adapter#413
cofin merged 14 commits intolitestar-org:mainfrom
hasansezertasan:feat/hasansezertasan/add-aiomysql-adapter

Conversation

@hasansezertasan
Copy link
Copy Markdown
Contributor

@hasansezertasan hasansezertasan commented Apr 12, 2026

Summary

  • Add new async MySQL adapter using aiomysql (built on PyMySQL)
  • Mirrors the existing asyncmy adapter structure for consistency
  • Extensions (ADK, Litestar, Events) deferred to follow-up

Closes #412

Motivation

Teams with inherited aiomysql codebases can adopt sqlspec without a driver migration. See #412 for full rationale.

Implementation notes

Key differences from the asyncmy adapter:

Aspect asyncmy aiomysql
Error hierarchy asyncmy.errors.* pymysql.err.* (re-exported)
DB name config key "database" "db"
FIELD_TYPE source asyncmy.constants.FIELD_TYPE pymysql.constants.FIELD_TYPE
Pool creation asyncmy.create_pool() aiomysql.create_pool()
Parameter style QMARK → POSITIONAL_PYFORMAT identical

Connection.cursor() is synchronous in both drivers (verified against aiomysql source — the docs are misleading).

What's included

  • sqlspec/adapters/aiomysql/ — full driver-only adapter (6 files, ~1,450 LOC)
  • tests/unit/adapters/test_aiomysql/ — unit tests (passing)
  • tests/integration/adapters/aiomysql/ — integration tests (need MySQL container in CI)
  • pyproject.toml — optional dep, pytest marker, mypy ignore

What's NOT included (deferred)

  • Extension stores (ADK, Litestar, Events)
  • SSCursor server-side streaming support
  • Docs page updates

Test plan

  • Unit tests pass locally (pytest tests/unit/adapters/test_aiomysql/ -v)
  • Integration tests pass in CI (requires MySQL container via pytest-databases)
  • No regressions in existing adapters

Disclosure: This PR was drafted with AI assistance (Claude Code) based on my motivation and direction. Authored by @hasansezertasan — I take responsibility for its content and will engage with any review feedback.

🤖 Generated with Claude Code

@hasansezertasan hasansezertasan marked this pull request as ready for review April 13, 2026 18:20
@hasansezertasan hasansezertasan marked this pull request as draft April 18, 2026 15:36
@cofin
Copy link
Copy Markdown
Member

cofin commented Apr 22, 2026

Correction to the PR description: the claim under Implementation notes that Connection.cursor() is synchronous in both drivers was wrong. On pool-acquired aiomysql connections, Connection.cursor() returns a Future and must be awaited — the aiomysql docs were correct. This was fixed in commit b734f68 (cursor coroutine awaited in AiomysqlCursor.__aenter__; AiomysqlConnectionProtocol.cursor re-typed as async def).

Verification: the full tests/integration/adapters/aiomysql/ suite passes clean under -W error::RuntimeWarning (95 passing, zero Python RuntimeWarnings), confirming no "Event loop is closed" / "coroutine was never awaited" regressions remain.

hasansezertasan and others added 2 commits April 22, 2026 11:12
Add a new async MySQL adapter using aiomysql (built on PyMySQL), complementing
the existing asyncmy adapter. This gives teams with inherited aiomysql codebases
a path to adopt sqlspec without a driver migration.

Key implementation details:
- Exception handling uses pymysql.err.* (aiomysql's underlying error hierarchy)
- Connection.cursor() is synchronous (same as asyncmy, despite aiomysql docs)
- Pool API uses aiomysql.create_pool() with "db" key (not "database" like asyncmy)
- Parameter style: QMARK input -> POSITIONAL_PYFORMAT execution (identical to asyncmy)
- Extensions (ADK, Litestar, Events) deferred to follow-up

Refs: litestar-org#412

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- cursor() returns a Future on pool-acquired connections, must be awaited
- Fix protocol to match (async cursor method)
- Run ruff format on all new files to pass pre-commit validation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@cofin cofin force-pushed the feat/hasansezertasan/add-aiomysql-adapter branch from b734f68 to 77f3d12 Compare April 22, 2026 18:12
cofin added 3 commits April 22, 2026 18:24
AsyncmyConfig exposes AsyncmyPool so Litestar route handlers can
type-hint the pool via DI. AiomysqlConfig omitted the analog, causing
a silent parity gap. Add a runtime alias of aiomysql.Pool and register
it in get_signature_namespace(), plus a unit test that locks the
parity to prevent regression.
- Implemented AiomysqlStore for managing sessions with MySQL/MariaDB using aiomysql.
- Added methods for session creation, retrieval, updating, and deletion with expiration handling.
- Created integration tests for the AiomysqlStore, covering various scenarios including session management and expiration.
- Introduced fixtures for setting up test databases with MySQL service.
- Added tests for event handling with aiomysql, ensuring proper message publishing, acknowledgment, and redelivery.
@cofin cofin marked this pull request as ready for review April 22, 2026 18:41
cofin and others added 9 commits April 22, 2026 18:49
sqlglot 30.6.0 changed how `exp.Update.where` renders: the generator now
emits the node verbatim instead of prepending the "WHERE" keyword. Setting
a bare condition expression on the "where" arg produced corrupted Oracle
SQL like `UPDATE SET col = src.valsrc.val < t.val`, breaking
test_oracle_merge_when_matched_with_condition after the sqlglot bump.

Wrap the predicate in `exp.Where(this=...)` in both the builder fast-path
and the Oracle normalizer so the generator emits
`UPDATE SET ... WHERE <condition>` across dialects. Strengthen the unit
test to assert the full Oracle render rather than just "UPDATE" substring.
aiomysql and asyncmy integration tests share the same MySQLService
container and pytest-xdist group. Both test_features.py suites created
identical unprefixed tables (json_test, isolation_test, bulk_test,
error_test, advanced_test, concurrent_test, mysql_features) with
CREATE TABLE IF NOT EXISTS plus unconditional inserts, so aiomysql data
poisoned asyncmy primary keys and row counts when run sequentially.

Rename aiomysql tables to match the _aiomysql convention already used
by aiomysql_clean_driver so each adapter owns its own schema surface.
Mirror the asyncmy reference layout with an aiomysql section in
docs/reference/adapters/mysql.rst covering AiomysqlConfig,
AiomysqlDriver, AiomysqlConnectionParams, AiomysqlPoolParams, and
AiomysqlDriverFeatures. Add an aiomysql row to the feature comparison
table and update the MySQL card description in the adapters index so
the adapter is discoverable from the landing grid.
DuckDB derives an attached-database name from the filename stem, so
repeated tests sharing the path test_sessions_<worker>.duckdb collide
process-wide when a prior connection has not released the file yet.
On CI this surfaced as a BinderException ("already attached by
database test_sessions_gw0") during test_sync_to_thread_concurrency.

Add a uuid4 suffix to the filename so each test owns its own attach
name, and explicitly close the config's connection pool in the
fixture teardown so the file handle is released before the next test
runs.
@cofin cofin merged commit eb90aba into litestar-org:main Apr 22, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhancement: add aiomysql adapter

2 participants