Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ jobs:

- name: Install dependency
run: |
pip install --upgrade -r requirements-dev.txt
pip install --upgrade -r requirements-dev.txt '.[zstd]'

- name: Set up MySQL
run: |
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changes

## Unreleased

* Support MySQL protocol compression with `compress=True`, `compress="zlib"`,
or `compress="zstd"`. Automatic selection prefers zstd when available and
supported by the server and falls back to zlib or an uncompressed connection.
zstd uses the standard library on Python 3.14+ and the API-compatible
`backports.zstd` on older versions, installed with `PyMySQL[zstd]`.
Compression is skipped for outgoing payloads smaller than 400 bytes or when
it would not reduce their size.

## v1.2.3

Release date: 2026-09-17
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ additional dependency:

$ python3 -m pip install PyMySQL[ed25519]

Protocol compression can be enabled with `pymysql.connect(..., compress=True)`.
This prefers zstd when available and supported by the server, otherwise it uses
zlib. Servers that support neither algorithm use an uncompressed connection.
Use `compress="zlib"` or `compress="zstd"` to require a specific algorithm.
On Python 3.14 and newer, zstd uses the standard library's `compression.zstd`.
On older Python versions, install the optional extra to use the API-compatible
[`backports.zstd`](https://pypi.org/project/backports.zstd/) implementation:

$ python3 -m pip install 'PyMySQL[zstd]'

The backport dependency is installed only on Python versions below 3.14.
Outgoing compression payloads below 400 bytes, or those that do not become
smaller, are sent uncompressed within the compressed protocol.

## Documentation

Documentation is available online: <https://pymysql.readthedocs.io/>
Expand Down
100 changes: 100 additions & 0 deletions pymysql/_compression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Framing for the MySQL compressed packet stream."""

import sys
import zlib

from . import err

try:
if sys.version_info >= (3, 14):
from compression import zstd
else:
from backports import zstd
except ImportError:
zstd = None

MAX_PAYLOAD_LENGTH = (1 << 24) - 1
MIN_COMPRESS_LENGTH = 400


def _pack_int24(value):
return value.to_bytes(3, "little")


class CompressedStream:
def __init__(self, algorithm):
self.algorithm = algorithm
self.sequence = 0
self._buffer = b""
self._offset = 0

def write(self, data, write_bytes):
for start in range(0, len(data), MAX_PAYLOAD_LENGTH):
payload = data[start : start + MAX_PAYLOAD_LENGTH]
original_length = 0
if len(payload) >= MIN_COMPRESS_LENGTH:
if self.algorithm == "zstd":
compressed = zstd.compress(payload, level=3)
else:
compressed = zlib.compress(payload, level=2)
if len(compressed) < len(payload):
original_length = len(payload)
payload = compressed
write_bytes(
b"".join(
(
_pack_int24(len(payload)),
bytes([self.sequence]),
_pack_int24(original_length),
payload,
)
)
)
self.sequence = (self.sequence + 1) % 256

def read(self, size, read_bytes):
parts = []
while size:
if self._offset == len(self._buffer):
self._read_frame(read_bytes)
count = min(size, len(self._buffer) - self._offset)
parts.append(self._buffer[self._offset : self._offset + count])
self._offset += count
size -= count
return b"".join(parts)

def _read_frame(self, read_bytes):
header = read_bytes(7)
length = int.from_bytes(header[:3], "little")
original_length = int.from_bytes(header[4:], "little")
# Like libmysqlclient and go-sql-driver/mysql, accept the server's
# sequence: an early error can precede receipt of all client frames.
self.sequence = (header[3] + 1) % 256
if not length:
raise err.InternalError("Empty compressed packet")
payload = read_bytes(length)
if original_length:
# These stateful decoders stop at EOF and expose no reset API.
# Use an independent context for each frame, including across
# connections/threads. One-shot helpers also create contexts and
# cannot enforce the declared output limit before allocation.
if self.algorithm == "zstd":
decoder = zstd.ZstdDecompressor()
decode_error = zstd.ZstdError
else:
decoder = zlib.decompressobj()
decode_error = zlib.error
Comment thread
methane marked this conversation as resolved.
Resolved
try:
# Bound output to detect invalid lengths without expanding an
# arbitrarily large compressed payload into memory.
payload = decoder.decompress(payload, original_length + 1)
except decode_error as exc:
raise err.InternalError("Invalid compressed packet") from exc
if (
len(payload) != original_length
or not decoder.eof
or decoder.unused_data
):
raise err.InternalError("Invalid compressed packet length or stream")
self._buffer = payload
self._offset = 0
103 changes: 96 additions & 7 deletions pymysql/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import traceback
import warnings

from . import VERSION_STRING, _auth, converters, err
from . import VERSION_STRING, _auth, _compression, converters, err
from .charset import charset_by_id, charset_by_name
from .constants import CLIENT, COMMAND, CR, ER, FIELD_TYPE, SERVER_STATUS
from .cursors import Cursor
Expand Down Expand Up @@ -159,7 +159,13 @@ class Connection:
(if no authenticate method) for returning a string from the user. (experimental)
:param server_public_key: SHA256 authentication plugin public key value. (default: None)
:param binary_prefix: **DEPRECATED**
:param compress: Not supported.
:param compress: Enable protocol compression with True (prefer zstd when
available and supported by the server, otherwise zlib). "zlib" or "zstd"
requires that algorithm; zstd uses compression.zstd on Python 3.14+
and backports.zstd on older Python versions (install PyMySQL[zstd]).
True falls back to an uncompressed connection if the server supports neither.
Packets smaller than 400 bytes and data that does not shrink are sent
uncompressed within the compressed protocol. (default: None)
:param named_pipe: Not supported.
:param db: **DEPRECATED** Alias for database.
:param passwd: **DEPRECATED** Alias for password.
Expand All @@ -173,6 +179,7 @@ class Connection:
_auth_plugin_name = ""
_closed = False
_secure = False
_compression = None

def __init__(
self,
Expand Down Expand Up @@ -213,7 +220,7 @@ def __init__(
ssl_key_password=None,
ssl_verify_cert=None,
ssl_verify_identity=None,
compress=None, # not supported
compress=None,
named_pipe=None, # not supported
passwd=None, # deprecated
db=None, # deprecated
Expand All @@ -227,10 +234,27 @@ def __init__(
)
password = passwd

if compress or named_pipe:
if named_pipe:
raise NotImplementedError("named_pipe argument is not supported")
if (
compress is not None
and compress is not False
and compress is not True
and compress not in ("zlib", "zstd")
):
raise ValueError('compress must be True, False, None, "zlib" or "zstd"')
# Honor callers that enabled compression through the capability flags.
if not compress:
if client_flag & CLIENT.ZSTD_COMPRESSION_ALGORITHM:
compress = "zstd"
elif client_flag & CLIENT.COMPRESS:
compress = "zlib"
if compress == "zstd" and _compression.zstd is None:
raise NotImplementedError(
"compress and named_pipe arguments are not supported"
"zstd compression requires compression.zstd (Python 3.14+) "
"or backports.zstd; install PyMySQL[zstd] on older Python versions"
)
self.compress = compress

self._local_infile = bool(local_infile)
if self._local_infile:
Expand Down Expand Up @@ -434,6 +458,8 @@ def close(self):
if self._sock is None:
return
send_data = struct.pack("<iB", 1, COMMAND.COM_QUIT)
if self._compression is not None:
self._compression.sequence = 0
try:
with contextlib.suppress(Exception):
self._write_bytes(send_data)
Expand All @@ -456,6 +482,7 @@ def _force_close(self):
pass
self._sock = None
self._rfile = None
self._compression = None

__del__ = _force_close

Expand Down Expand Up @@ -662,6 +689,7 @@ def set_character_set(self, charset, collation=None):

def connect(self, sock=None):
self._closed = False
self._compression = None
try:
if sock is None:
if self.unix_socket:
Expand Down Expand Up @@ -781,7 +809,8 @@ def _read_packet(self, packet_type=MysqlPacket):

btrl, btrh, packet_number = struct.unpack("<HBB", packet_header)
bytes_to_read = btrl + (btrh << 16)
if packet_number != self._next_seq_id:
expected_packet_number = self._next_seq_id
if self._compression is None and packet_number != expected_packet_number:
self._force_close()
if packet_number == 0:
# MariaDB sends error packet with seqno==0 when shutdown
Expand All @@ -793,7 +822,9 @@ def _read_packet(self, packet_type=MysqlPacket):
"Packet sequence number wrong - got %d expected %d"
% (packet_number, self._next_seq_id)
)
self._next_seq_id = (self._next_seq_id + 1) % 256
# Compressed servers may reset the inner sequence at frame
# boundaries. Follow it, as libmysqlclient does.
self._next_seq_id = (packet_number + 1) % 256

recv_data = self._read_bytes(bytes_to_read)
if DEBUG:
Expand All @@ -805,12 +836,33 @@ def _read_packet(self, packet_type=MysqlPacket):

packet = packet_type(b"".join(buff), self.encoding)
if packet.is_error_packet():
if (
self._compression is not None
and packet_number == 0
and expected_packet_number != 0
):
# Preserve the normal protocol's treatment of unsolicited
# shutdown/idle-timeout errors with a reset sequence number.
self._force_close()
raise err.OperationalError(
CR.CR_SERVER_LOST,
"Lost connection to MySQL server during query",
)
if self._result is not None and self._result.unbuffered_active is True:
self._result.unbuffered_active = False
packet.raise_for_error()
return packet

def _read_bytes(self, num_bytes):
if self._compression is not None:
try:
return self._compression.read(num_bytes, self._read_bytes_uncompressed)
except err.InternalError:
self._force_close()
raise
return self._read_bytes_uncompressed(num_bytes)

def _read_bytes_uncompressed(self, num_bytes):
# NOTE: caller should call self._sock.settimeout(self._read_timeout)
# before first read.
while True:
Expand All @@ -837,6 +889,12 @@ def _read_bytes(self, num_bytes):
return data

def _write_bytes(self, data):
if self._compression is not None:
self._compression.write(data, self._write_bytes_uncompressed)
else:
self._write_bytes_uncompressed(data)

def _write_bytes_uncompressed(self, data):
if self._current_timeout != self._write_timeout:
self._sock.settimeout(self._write_timeout)
self._current_timeout = self._write_timeout
Expand Down Expand Up @@ -893,6 +951,8 @@ def _execute_command(self, command, sql):
# calling self..write_packet()
prelude = struct.pack("<iB", packet_size, command)
packet = prelude + sql[: packet_size - 1]
if self._compression is not None:
self._compression.sequence = 0
self._write_bytes(packet)
if DEBUG:
dump_packet(packet)
Expand Down Expand Up @@ -927,6 +987,26 @@ def _request_authentication(self):
# also advertises SSL support.
# _do_ssl is set here and checked below for sha256_password auth.
client_flags = self.client_flag
client_flags &= ~(CLIENT.COMPRESS | CLIENT.ZSTD_COMPRESSION_ALGORITHM)
compression_algorithm = None
if self.compress:
if (
self.compress in (True, "zstd")
and _compression.zstd is not None
and self.server_capabilities & CLIENT.ZSTD_COMPRESSION_ALGORITHM
):
compression_algorithm = "zstd"
client_flags |= CLIENT.ZSTD_COMPRESSION_ALGORITHM
elif (
self.compress in (True, "zlib")
and self.server_capabilities & CLIENT.COMPRESS
):
compression_algorithm = "zlib"
client_flags |= CLIENT.COMPRESS
elif self.compress is not True:
raise err.NotSupportedError(
f"Server does not support {self.compress} compression"
)
if self.ssl:
if self.server_capabilities & CLIENT.SSL:
# SSL upgrade: include CLIENT.SSL flag and wrap the socket.
Expand Down Expand Up @@ -1006,6 +1086,10 @@ def _request_authentication(self):
connect_attrs += _lenenc_int(len(v)) + v
data += _lenenc_int(len(connect_attrs)) + connect_attrs

if compression_algorithm == "zstd":
# zstd_compression_level follows the connection attributes.
data += b"\x03"

self.write_packet(data)
auth_packet = self._read_packet()

Expand Down Expand Up @@ -1073,6 +1157,11 @@ def _request_authentication(self):
break
raise err.OperationalError("unexpected packet during authentication")

# The complete authentication exchange, including the final OK packet,
# uses normal framing. Compression starts with the first command.
if compression_algorithm is not None:
self._compression = _compression.CompressedStream(compression_algorithm)

if DEBUG:
print("Succeed to auth")

Expand Down
1 change: 1 addition & 0 deletions pymysql/constants/CLIENT.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@
HANDLE_EXPIRED_PASSWORDS = 1 << 22
SESSION_TRACK = 1 << 23
DEPRECATE_EOF = 1 << 24
ZSTD_COMPRESSION_ALGORITHM = 1 << 26
Loading
Loading