Skip to content

v2.2.0

New Features

1. AsMysql Constructive Singleton

The AsMysql base class now provides a process-wide constructive singleton: instances are reused with (subclass, engine object) as the key, so business subclasses need no singleton code of their own.

Background:

In Web services (e.g., creating mysql_engine_master in lifespan) and CLI loops, business code repeatedly constructs the same business class. Previously each construction produced a new object, so state could not be shared within the process; now the base class manages instance reuse centrally, with zero iteration and zero temporary allocation on the hit path.

How it works:

  • AsMysql.__new__ maintains a process-wide instance table keyed by (subclass, engine object)
  • Same subclass + same engine object: the same instance is always reused; on a hit __init__ still runs, but only reassigns the same engine (idempotent)
  • Different engine objects / different subclasses: each keeps its own instance, isolated from each other
  • The instance table holds strong references to engines; on a miss, stale entries whose engine is disconnected (is_connected is False) are lazily removed to prevent unbounded cache growth

Usage:

from asmysql import Engine, AsMysql

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
await engine.connect()

class UserService(AsMysql):
    pass

assert UserService(engine) is UserService(engine)  # same instance

2. release() Unregisters Instances

Added the AsMysql.release() class method to explicitly unregister instance table entries (it only releases strong references, not disconnect):

# Remove this engine's entries across all subclasses, returns the removed count
removed = UserService.release(engine)

# Clear the whole table (Web service lifespan shutdown, end of each CLI round), returns the removed count
removed = UserService.release()
  • Releasing the same engine repeatedly returns 0 without raising KeyError
  • The connection pool is still closed by whoever owns the engine via engine.disconnect()

Behavior Changes

  • Construction behavior of AsMysql(engine) changes: repeated construction with the same subclass + same engine object now returns the same instance. Business classes that rely on a fresh instance per construction (e.g., storing request-scoped state on instance attributes) should use local variables inside methods or reuse the instance explicitly

Documentation

  • Added constructive singleton and release() documentation in business-logic.md and api.md (Chinese and English)
  • Added the v2.2.0 changelog

Testing

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