aio-libs / aiomysql

aiomysql is a library for accessing a MySQL database from the asyncio
https://aiomysql.rtfd.io
MIT License
1.72k stars 254 forks source link

fix #166 (Got an error reading communication packets) for pool #987

Open parsapoorsh opened 1 month ago

parsapoorsh commented 1 month ago

What do these changes do?

there is a problem for pool connections when the program exits even after using pool.wait_closed() it causes a ton of [Warning] Aborted connection 1 to db: 'database' user: 'user' host: '127.0.0.1' (Got an error reading communication packets) warning in mariadb (maybe mysql too). the problem is in aiomysql/connection.py close function:

def close(self):
    """Close socket connection"""
    if self._writer:
        self._writer.transport.close()
    self._writer = None
    self._reader = None

async def ensure_closed(self):
    """Send quit command and then close socket connection"""
    if self._writer is None:
        # connection has been closed
        return
    send_data = struct.pack('<i', 1) + bytes([COMMAND.COM_QUIT])
    self._writer.write(send_data)
    await self._writer.drain()
    self.close()

the close function just replaces self._writer content with None, it does not send any close packets. this causes the said warning. just by using await conn.ensure_closed() instead of conn.close() in wait_closed() function in Pool, the problem goes away.

Are there changes in behavior for the user?

No.

Related issue number

Fixes #166

Checklist