Skip to content

Business Logic Development

Inherit AsMysql Class

The AsMysql class provides a base class for business logic development, making it convenient to organize code through inheritance:

from asmysql import Engine, AsMysql

class UserService(AsMysql):
    async def get_user_by_id(self, user_id: int):
        async with self.client.execute(
            "SELECT * FROM users WHERE id = %s",
            (user_id,),
            result_class=dict
        ) as result:
            if result.error:
                return None
            return await result.fetch_one()

    async def create_user(self, name: str, email: str):
        async with self.client.execute(
            "INSERT INTO users (name, email) VALUES (%s, %s)",
            (name, email)
        ) as result:
            if result.error:
                raise Exception(f"Failed to create user: {result.error_msg}")
            return result.last_rowid

    async def list_users(self):
        async with self.client.execute(
            "SELECT * FROM users",
            result_class=dict
        ) as result:
            if result.error:
                return []
            return await result.fetch_all()

Using Business Logic Class

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

# Create business logic instance
user_service = UserService(engine)

# Use business methods
user = await user_service.get_user_by_id(1)
users = await user_service.list_users()
new_user_id = await user_service.create_user("张三", "zhangsan@example.com")

Instance Reuse (Constructive Singleton)

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

  • Same subclass + same engine object: always reuse the same instance
  • Different engine objects: each keeps its own instance
  • Different subclasses + same engine object: isolated from each other
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
await engine.connect()

class OrderService(AsMysql):
    pass

assert UserService(engine) is UserService(engine)       # same instance
assert UserService(engine) is not OrderService(engine)  # isolated per subclass

Releasing Instances

The instance table holds strong references to engines. After an engine is disconnected, its stale entries are automatically removed on the next instance creation; you can also unregister explicitly when the application shuts down or a task round finishes:

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

# Clear the whole table (e.g., Web service lifespan shutdown), returns the removed count
removed = UserService.release()

Note: release() only releases the instance table's strong references to engines; it does not disconnect them. The connection pool is still closed by whoever owns the engine via engine.disconnect().

Lifecycle and GC Semantics

The instance table holds strong references to instances keyed by (subclass, engine object), so reference counts never drop to zero:

  • AsMysql has no __del__ cleanup path; instances are never unregistered by garbage collection;
  • Lazy removal only runs when a new instance misses the table, and only removes engine entries whose is_connected is False;
  • In a long-running process that repeatedly creates and disconnects engines without constructing new instances afterwards, stale entries remain until an explicit release() or process exit.

Recommended shutdown order:

# Web lifespan shutdown / end of each CLI round
await engine.disconnect()      # close the connection pool first
UserService.release(engine)    # then unregister this engine's instance entries

release() does not depend on engine connection state, so the two steps can be swapped; it only releases the table's strong references and never calls disconnect() for you.

Advantages

  • Code Organization: Encapsulate database operations in business classes for easy maintenance
  • Reusability: Business methods can be reused in multiple places
  • Type Safety: Combined with type hints to improve code quality
  • Test Friendly: Easy to perform unit testing