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 claudeone-command install (--targetrequired, project-level preferred, supportsuser:prefix / multi-targets / custom paths,--forcerefresh), 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.txtpointer always points to the latest entry - PyPI and README discovery entries: new AI-Assisted Development / AI 辅助开发 section in README, new
AI Docslink in PyPI metadata, new AI-entry module docstring at the top ofasmysql/__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 viapool.release(), emitting aResourceWarning; connections are no longer pinned forever byPool._used, eliminating both the acquire hang after pool exhaustion and the defaultdisconnect()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_timeoutdefault 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.mdgains a "Standard Usage" section;best-practices.mdgains a ❌ counter-example;api.mdclarifies Result does not supportawait result, repositions__call__as the internal entry, adds fetch-family usage constraints and a__del__()entry;faq.mddisconnect 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 afterwardsEngine.__del__safety net: if GC'd without being disconnected, emits aResourceWarningand terminates automatically, instead of relying onConnection.__del__(warning noise, delayed cyclic GC, RuntimeError when the loop is already closed)
Behavior Changes¶
Result.poolcleared after close: typeFinal[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-enteringasync withon an already executed Result remains a no-op
Documentation & Testing¶
- Bilingual docs updated (connection/result/api/faq)
- Added
TestEngineTerminate,TestResultPoolRetentionmock 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 nowNone: the traceback frame chain is severed when the error is stored, eliminating the "Result → exception → frame → Result" reference cycle;error_no/error_msg/queryare 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 aConnectionErrorwith 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.errorlong-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_lockbinding the Engine to the first event loop that experienced contention: reusing an Engine acrossasyncio.run()calls no longer raisesRuntimeError: ... is bound to a different event loop
Documentation & Testing¶
- Bilingual docs updated (result/connection/faq/api)
- Added
TestErrorTracebackRetention,TestEngineCrossLoopmock 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=Truewrites 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 aUserWarning,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
CancelledErrorconnection leaks: synchronous discard + re-raise, not enteringresult.error init_sqlfailures 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, andrelease()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 inbusiness-logic.mdandapi.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): Addedinit_sqlparameter 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. UsesWeakKeyDictionaryto track initialized connections. Fully backward compatible.
Breaking Changes¶
- Auto-Commit Mechanism Refactored: Removed
auto_commitEngine parameter andcommitexecute/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
streamParameter:streamis no longer an Engine class attribute, only available atexecute()method level - Removed Engine
result_classParameter:result_classis no longer an Engine class attribute or constructor parameter, only available at theexecute()/execute_many()method level, defaulting totuple
Bug Fixes¶
- Fixed 6 connection leak issues:
fetch_all()custom type leak, double release after error,async for+breakleak, non-MySQLError exception leak,__del__crash, DDL/DML statements not releasing connections - Fixed 5 logic errors:
echo_sql_logURL parsing,oroperator overriding falsy values, concurrent race conditions, pool null passing, generic parameter semantic error - Fixed 5 medium/low-severity issues:
release_connections()null check,@lru_cachememory leak,error_msgformatting,iterate()check inconsistency, property access crashes
Documentation¶
- Fixed non-existent API usage in homepage examples
- Added
init_sqldocumentation acrossconnection.md,api.md, andexamples.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/commitparameters
Testing¶
- Added
test_engine_init_sql.pycoveringinit_sqlcore functionality and edge cases - Rewrote integration test
enginefixture to auto-select test database viainit_sql=USE <test_db> - Removed Engine
result_classrelated test cases fromtest_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
EngineandAsMysqlclasses, added independentEngineclass to handle MySQL connections and execute statements - Result Class Changes:
Result.errattribute renamed toResult.error - API Changes: Connection method changed from auto-connect to explicitly creating
Engineand callingconnect()
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 supportsstream,result_classparameters 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
uvas package management tool - Code Quality: Improved code structure, error handling, and docstrings
Core Features¶
v2 version retains the core features of v1:
- Easy to Use: asmysql is an easy-to-use library that wraps aiomysql
- Connection Pool Management: Automatic MySQL connection pool management with reconnection mechanism
- Error Handling: Global automatic capture of
MysqlErrorerrors - Separation of Execution and Retrieval: Separation of SQL statement execution and result retrieval
- Type Hints: Complete Python type hint support
- Business Logic Development: Directly inherit
AsMysqlclass for logic development
Migration Guide¶
For detailed migration guide, please refer to Migration Guide.