Skip to content

asmysql v2 Changelog

This document records all changes in asmysql v2 version.

v2.7.0

New Features

  • In-package AI development skill with one-command install: new in-package asmysql/_ai/ AI assets (AGENTS.md entry + the asmysql-dev skill with three references), shipped with the wheel and available offline; python -m asmysql skill install --target claude one-command install (--target required, project-level preferred, supports user: prefix / multi-targets / custom paths, --force refresh), single canonical + per-skill symlinks + version-stamp self-check
  • Documentation site AI entries: new bilingual AI Development page and version-independent assets under the site root /ai/ (llms.txt index, llms-full.txt full Chinese docs, skill zip and per-file reading); the root /llms.txt pointer always points to the latest entry
  • PyPI and README discovery entries: new AI-Assisted Development / AI 辅助开发 section in README, new AI Docs link in PyPI metadata, new AI-entry module docstring at the top of asmysql/__init__.py

Scope Boundaries

  • No changes to v1/v2 runtime behavior or exports; zero new runtime dependencies, no console script added; no silent auto-install

v2.6.0

Bug Fixes

  • Connection leak fix for improperly closed Results (Result.__del__): when an executed unclosed Result is GC'd, synchronously discards the connection (closes the transport, no COM_QUIT) and completes pool bookkeeping via pool.release(), emitting a ResourceWarning; connections are no longer pinned forever by Pool._used, eliminating both the acquire hang after pool exhaustion and the default disconnect() hang; discards instead of returning for reuse, so unread streaming rows never pollute the next user

Behavior Changes

  • GC safety net semantics: abandoned unclosed Results no longer leak permanently; the cost is that the connection is not reused and uncommitted transactions are rolled back by the server (already auto-committed data is unaffected); waiting semantics for Results still referenced and unclosed are unchanged
  • ResourceWarning wording: changed to "connection discarded (not reused), uncommitted transactions will be rolled back by the server"; disconnect_timeout default None unchanged

Usage Standardization

  • SQL execution recommends only the unified safe forms: async with, async for (including break), fetch_all(), iterate(), DDL/DML automatic release; bare execution + fetch without close is no longer recommended (APIs not removed; standardization lives at the documentation layer)
  • result.md gains a "Standard Usage" section; best-practices.md gains a ❌ counter-example; api.md clarifies Result does not support await result, repositions __call__ as the internal entry, adds fetch-family usage constraints and a __del__() entry; faq.md disconnect Q&A updated

Documentation

  • Bilingual docs updated (result/best-practices/api/faq)

v2.5.0

New Features

  • Engine.terminate(): synchronous forced pool cleanup (idempotent); no waiting for returns, immediately closes all in-use connections and severs in-flight queries, cleans up idle connections best-effort; suitable for atexit and synchronous shutdown hooks; the Engine can be connected again afterwards
  • Engine.__del__ safety net: if GC'd without being disconnected, emits a ResourceWarning and terminates automatically, instead of relying on Connection.__del__ (warning noise, delayed cyclic GC, RuntimeError when the loop is already closed)

Behavior Changes

  • Result.pool cleared after close: type Final[Pool] → Optional[Pool]; the reference is cleared after close / automatic release of statements without result sets, so caching closed Results no longer pins the Pool and the event loop (hazard 3)
  • Execute-after-close raises: executing an unexecuted Result after close raises RuntimeError; re-entering async with on an already executed Result remains a no-op

Documentation & Testing

  • Bilingual docs updated (connection/result/api/faq)
  • Added TestEngineTerminate, TestResultPoolRetention mock cases and a terminate integration case; real-MySQL program-level probe (severing in-flight queries, server-side connections dropping to zero, __del__ fallback, Pool reclaimable); full suite 452 passed

v2.4.0

Behavior Changes

  • result.error.__traceback__ is now None: the traceback frame chain is severed when the error is stored, eliminating the "Result → exception → frame → Result" reference cycle; error_no/error_msg/query are unaffected
  • Clear error for live pools across event loops: with the pool still connected, calling connect() / engine.pool / execute() in a new event loop raises a ConnectionError with a clear message (previously an obscure RuntimeError or silent misuse)

New Features

  • Engine reuse across event loops: the internal connect lock is rebuilt when the loop changes; after disconnecting in the original loop, you can connect again in a new loop (e.g. multiple asyncio.run() calls)

Bug Fixes

  • Fixed memory retention caused by the error traceback reference cycle: holding result.error long-term (error audit scenarios) no longer keeps the whole Result and frame locals alive; Results no longer wait for a cyclic GC pass to be reclaimed
  • Fixed _connect_lock binding the Engine to the first event loop that experienced contention: reusing an Engine across asyncio.run() calls no longer raises RuntimeError: ... is bound to a different event loop

Documentation & Testing

  • Bilingual docs updated (result/connection/faq/api)
  • Added TestErrorTracebackRetention, TestEngineCrossLoop mock cases and a cross-loop reconnect integration case; full suite 430 passed

v2.3.0

Behavior Changes

  • Auto-commit mechanism rework: the pool switches to autocommit=True (built-in, no configuration parameter), the SQL keyword whitelist is removed; successful statements with an open transaction are committed, failed statements rolled back; stream=True writes are now committed correctly; cross-statement transactions are not supported

New Features

  • disconnect_timeout: optional finite disconnect timeout + terminate fallback (default None waits forever, backward compatible); cancellation paths always converge
  • Explicit warning for execute_many([]): empty lists execute no SQL, emit a UserWarning, row_count=0

Bug Fixes

  • Fixed multiple silent write-loss paths: uncommitted streaming writes, whitelist misses, swallowed COMMIT failures, id(conn) address reuse in init_sql, session loss from silent ping reconnects, connection pollution on streaming cursor close failure
  • Fixed CancelledError connection leaks: synchronous discard + re-raise, not entering result.error
  • init_sql failures discard the connection; init now runs on an independent buffered cursor

Documentation & Testing

  • Bilingual docs updated (transaction/connection/result/faq/examples/api/index); ClickHouse examples switched to the query-level SETTINGS clause (wait_for_async_insert=1)
  • M1-M33 mock matrix + new MySQL/ClickHouse integration tests, full suite 339 passed; dual-backend live probes and independent mycli persistence checks passed

v2.2.0

New Features

  • AsMysql Constructive Singleton: instances are reused with (subclass, engine object) as the key; the same subclass and engine always return the same instance, while different subclasses/engines stay isolated
  • release() unregister: release(engine) removes this engine's entries across all subclasses, and release() clears the whole table; stale entries of disconnected engines are lazily removed on the next creation

Behavior Changes

  • Constructing AsMysql(engine) multiple times now reuses the same instance; business classes that rely on a fresh instance per construction need adjustment

Documentation

  • Added constructive singleton and release() docs in business-logic.md and api.md (Chinese and English)

Testing

  • Added test_mock_asmysql_singleton.py, covering the constructive singleton, release() semantics, and lazy cleanup of stale entries

v2.1.0

New Features

  • Connection Init SQL (init_sql): Added init_sql parameter to automatically execute preset SQL on each new TCP connection's first use. Ideal for ClickHouse async insert configuration, MySQL session variable setup, and similar scenarios. Uses WeakKeyDictionary to track initialized connections. Fully backward compatible.

Breaking Changes

  • Auto-Commit Mechanism Refactored: Removed auto_commit Engine parameter and commit execute/Result parameter, replaced with SQL first-keyword-based auto-commit mechanism (_should_commit()). Write operations auto-COMMIT, read operations do not commit, stream mode does not commit
  • Removed Engine stream Parameter: stream is no longer an Engine class attribute, only available at execute() method level
  • Removed Engine result_class Parameter: result_class is no longer an Engine class attribute or constructor parameter, only available at the execute() / execute_many() method level, defaulting to tuple

Bug Fixes

  • Fixed 6 connection leak issues: fetch_all() custom type leak, double release after error, async for + break leak, non-MySQLError exception leak, __del__ crash, DDL/DML statements not releasing connections
  • Fixed 5 logic errors: echo_sql_log URL parsing, or operator overriding falsy values, concurrent race conditions, pool null passing, generic parameter semantic error
  • Fixed 5 medium/low-severity issues: release_connections() null check, @lru_cache memory leak, error_msg formatting, iterate() check inconsistency, property access crashes

Documentation

  • Fixed non-existent API usage in homepage examples
  • Added init_sql documentation across connection.md, api.md, and examples.md (both Chinese and English versions)
  • Rewrote transaction control documentation to describe SQL statement type-based auto-commit mechanism
  • Fixed API documentation signatures: removed non-existent close/commit parameters

Testing

  • Added test_engine_init_sql.py covering init_sql core functionality and edge cases
  • Rewrote integration test engine fixture to auto-select test database via init_sql=USE <test_db>
  • Removed Engine result_class related test cases from test_mock_engine.py

v2.0.0

Breaking Changes

v2.0.0 is a completely refactored version that is incompatible with v1. Main changes include:

  • Architecture Refactoring: Separated Engine and AsMysql classes, added independent Engine class to handle MySQL connections and execute statements
  • Result Class Changes: Result.err attribute renamed to Result.error
  • API Changes: Connection method changed from auto-connect to explicitly creating Engine and calling connect()

New Features

  • Engine Class: Brand new connection engine class with URL connection string support, connection status monitoring, and flexible connection management
  • Result Class Enhancements: Support for error information access (error_no, error_msg), streaming queries, context managers, async iterators, and custom result types
  • Execution Method Enhancements: execute() method supports stream, result_class parameters and multiple calling methods
  • Type Hints: Complete type hint support with generic types (Result[T])
  • Testing: New pytest test suite covering main functional scenarios

Updates

  • Package Management Tool: Using uv as package management tool
  • Code Quality: Improved code structure, error handling, and docstrings

Core Features

v2 version retains the core features of v1:

  1. Easy to Use: asmysql is an easy-to-use library that wraps aiomysql
  2. Connection Pool Management: Automatic MySQL connection pool management with reconnection mechanism
  3. Error Handling: Global automatic capture of MysqlError errors
  4. Separation of Execution and Retrieval: Separation of SQL statement execution and result retrieval
  5. Type Hints: Complete Python type hint support
  6. Business Logic Development: Directly inherit AsMysql class for logic development

Migration Guide

For detailed migration guide, please refer to Migration Guide.