FAQ¶
Q: How to check connection pool status?¶
A: Use the engine.status attribute:
Q: What's the difference between streaming query and regular query?¶
A: - Regular Query: Loads all results into memory, suitable for small datasets - Streaming Query: Returns results row by row, does not consume memory, suitable for large datasets
Q: How to customize result type?¶
A: Use the result_class parameter, supports tuple, dict, or custom model classes:
async with engine.execute(
"SELECT * FROM users",
result_class=dict, # or custom model class
) as result:
users = await result.fetch_all()
Q: How to handle transactions?¶
A: Since v2.3.0, a "server-side auto-commit + transaction-state fallback" mechanism is used: the pool is fixed at autocommit=True; successful statements with an open transaction are committed, failed statements are rolled back automatically:
engine = Engine(url="...")
await engine.connect()
# Write operations are auto-committed by the server, persisted on success
# Failed statements are ROLLBACKed automatically, errors written to result.error
Q: Are write statements with stream=True committed?¶
A: Yes. v2.3.0 fixes the silent data loss caused by uncommitted streaming writes in older versions: stream=True + writes without result sets are committed immediately after execution according to the transaction state; streaming statements with result sets (such as CALL returning result sets) defer the commit until the cursor closes.
Q: Are cross-statement transactions supported?¶
A: No. Each execute() in v2 commits independently; a manual BEGIN / START TRANSACTION is committed immediately after execution. For transaction boundaries, combine operations into a single statement or a stored procedure.
Q: When a task is cancelled (wait_for timeout / TaskGroup), is the statement rolled back?¶
A: Not necessarily. Cancellation only interrupts the client-side wait, not SQL already sent: under autocommit=1, writes already completed by the server are independent transactions and are already committed — cancellation ≠ rollback. On cancellation the connection is discarded synchronously and the slot reclaimed; CancelledError propagates (it does not enter result.error); a cancelled Result is abandoned entirely — do not read its attributes or retry it. Cancellation while queued in acquire means the statement definitely did not execute and can be safely retried.
Q: What if disconnect() keeps waiting and never returns?¶
A: By default disconnect_timeout=None waits forever for all connections to return. Since v2.6.0, abandoned (garbage-collected) unclosed Result objects no longer cause an infinite wait — their connections are synchronously discarded with pool bookkeeping completed (emitting a ResourceWarning); only Result objects that are still referenced and unclosed keep it waiting. Make sure every Result is closed via async with / async for / close(); when convergence guarantees are needed, configure a finite timeout explicitly (e.g. disconnect_timeout=30): on timeout all in-use connections are terminated automatically with a ResourceWarning, and in-flight queries receive error_no=2013. Externally cancelling disconnect also terminates and converges.
Q: How to clean up an Engine in synchronous shutdown scenarios (atexit / no event loop)?¶
A: Use engine.terminate() (since v2.5.0): synchronous forced cleanup that does not wait for connections to return, immediately closes all in-use connections and severs in-flight queries, and cleans up idle connections best-effort; it is idempotent and safe to register via atexit.register(engine.terminate). You can connect() again afterwards to reuse the Engine. The Engine also ships a __del__ safety net: if it is GC'd without being disconnected, it emits a ResourceWarning and terminates automatically — but production code should still clean up explicitly (await engine.disconnect() inside an event loop, terminate() in synchronous hooks). See Connection Management.
Q: How to get error information?¶
A: Through result.error, result.error_no, and result.error_msg attributes:
async with engine.execute("SELECT * FROM invalid_table") as result:
if result.error:
print(f"Error code: {result.error_no}")
print(f"Error message: {result.error_msg}")
Q: Why does result.error have no traceback?¶
A: Since v2.4.0, the __traceback__ frame chain is deliberately severed (set to None) when the error is stored, breaking the "Result → exception → frame → Result" reference cycle — otherwise holding result.error long-term (e.g. in an error audit list) would also retain the whole Result and the frame's local variables. Use error_no / error_msg and the SQL in result.query for troubleshooting; re-raising the exception produces a fresh traceback at the raise site.
Q: How to batch insert data?¶
A: Use the execute_many() method:
data = [("张三", "zhangsan@example.com"), ("李四", "lisi@example.com")]
async with engine.execute_many("INSERT INTO users (name, email) VALUES (%s, %s)", data) as result:
print(f"Inserted {result.row_count} records")
Q: How to share Engine instance across different modules?¶
A: You can create an Engine instance at application startup, then share it through dependency injection or global variables:
# app.py
engine = Engine(url="mysql://...")
await engine.connect()
# service.py
from app import engine
class UserService(AsMysql):
def __init__(self):
super().__init__(engine)
Q: Can an Engine be reused across multiple asyncio.run() calls / event loops?¶
A: Yes, but you must "disconnect in the original loop → connect in the new loop" (since v2.4.0 the internal lock is rebuilt when the loop changes). An aiomysql pool is bound to its loop at creation and a live pool cannot be shared across loops: connecting/executing in a new loop without disconnecting first raises a ConnectionError with a clear message. See the "Reuse Across Event Loops" section in Connection Management.
Q: How to set connection pool size?¶
A: Set based on application concurrency and database server performance:
- Low concurrency applications:
min_pool_size=2, max_pool_size=10 - Medium concurrency:
min_pool_size=5, max_pool_size=50 - High concurrency applications:
min_pool_size=10, max_pool_size=100+
Q: How to handle connection timeout?¶
A: You can set connection timeout through the connect_timeout parameter:
Q: Are AsMysql instances garbage collected automatically? Do I need to call release manually?¶
A: No, they are not unregistered automatically. The instance table holds strong references keyed by (subclass, engine object), so __del__ never triggers and garbage collection does not clean up entries.
- Web services call
UserService.release(engine)during lifespan shutdown; CLI calls it at the end of each round (orrelease()to clear the whole table) - Stale entries whose engine is disconnected (
is_connectedisFalse) are lazily removed on the next construction miss release()only releases the table's strong references; it does not close the connection pool, which remains the responsibility ofengine.disconnect()