Connection¶
rustmy.connect() is rustmy.connections.Connection: calling it opens the
connection.
Connection
¶
Connection(
host: str | None = None,
user: str | None = None,
password: str | None = None,
database: str | None = None,
port: int | None = None,
unix_socket: PathArg | None = None,
*,
passwd: str | None = None,
db: str | None = None,
charset: str | None = None,
collation: str | None = None,
connect_timeout: float | None = None,
read_timeout: float | None = None,
write_timeout: float | None = None,
autocommit: bool | None = False,
init_command: str | None = None,
client_flag: int = 0,
multi_statements: bool = False,
sql_mode: str | None = None,
conv: Mapping[Any, Any] | None = None,
cursorclass: type[Cursor] = Cursor,
ssl_mode: str | None = None,
ssl_ca: PathArg | None = None,
ssl_cert: PathArg | None = None,
ssl_key: PathArg | None = None,
ssl: Mapping[str, object] | bool | None = None,
server_public_key: PathArg | None = None,
get_server_public_key: bool | None = None,
binary_prefix: bool = True,
statement_cache_size: int = 32,
compress: bool | str = False,
zstd_level: int | None = None,
local_infile: bool = False,
local_infile_dir: PathArg | None = None,
program_name: str | None = None,
conn_attrs: Mapping[str, str] | None = None,
read_default_file: PathArg | None = None,
read_default_group: str | None = None,
)
A connection to a MySQL or MariaDB server.
Not thread-safe: share the module between threads, not connections.
Using one connection from two threads at once raises
ProgrammingError instead of corrupting the stream.
Open a connection.
host defaults to localhost, port to 3306 and user and
password to empty. passwd and db are accepted as aliases
of password and database for compatibility with other MySQL
drivers. autocommit=None keeps the server's default.
read_default_file reads connection options from a MySQL option
file (my.cnf): its [client] group and, if given,
read_default_group. With only read_default_group, the
default option files are read (/etc/my.cnf, ~/.my.cnf…).
Arguments passed here win over the file. Used: host, port,
user, password, database, socket,
default-character-set, init-command, connect-timeout,
ssl-mode, ssl-ca, ssl-cert, ssl-key,
server-public-key-path, get-server-public-key,
multi-statements,
return-found-rows, compress, compression-algorithms,
zstd-compression-level, local-infile and
load-data-local-dir; other options are ignored.
connect_timeout (seconds, default 15) bounds opening the
connection and every read and write until authentication ends, so a
server that accepts the connection but never answers fails too; 0
waits forever. read_timeout and write_timeout (no default)
apply from then on. TCP connections send keepalive probes after 60
seconds idle, so a connection a firewall or load balancer dropped
while it sat in a pool fails within minutes instead of hanging.
charset is the session's character set (default utf8mb4;
utf8 means utf8mb4): queries are encoded and text results
decoded in it. Any MySQL character set with a Python codec works.
Without collation the session uses the server's default collation
for it (what its tables use, so comparisons with user variables
work), set in the handshake at no extra cost; with collation,
SET NAMES … COLLATE … runs after connecting, in the same
statement as sql_mode and autocommit.
multi_statements=True allows several statements separated by
; in one execute (off by default: it lets an injected string
append whole statements). sql_mode sets the session's SQL mode;
init_command runs after it. Both are applied again after
reset_connection() and change_user().
conv maps column types (FIELD_TYPE) to decoders and Python
types to encoders, in MySQLdb's format; start from
rustmy.converters.conversions. Only entries that differ from
it are called from Python, so the other columns keep the native fast
path. A decoder gets str for DECIMAL and date/time columns and
bytes for the rest (None is passed through); a column type may
map to [(FLAG mask, decoder), …] to choose by the column's flags.
An encoder is called as encoder(value, conv) and returns the SQL
literal.
bytes parameters go as _binary'…', so the server reads them
as binary data whatever the session's character set;
binary_prefix=False writes a plain '…' instead, for SQL that
writes _binary %s itself (Django's MySQL backend; the
install_as_MySQLdb() alias defaults to it, as mysqlclient does).
Multi-byte legacy character sets (gbk, big5, sjis…) always get a
hexadecimal X'…', which is binary on its own.
compress=True (or "zlib") uses the compressed protocol with
zlib, which pays off on slow or metered networks and costs CPU on
fast ones; compress="zstd" uses zstd (MySQL 8.0.18+) at
zstd_level (1 to 22, default 3), or zlib if the server offers no
zstd (MariaDB). A server that offers no compression at all gets an
uncompressed connection: compression says what was agreed.
LOAD DATA LOCAL INFILE is off by default: the server names the
file the client sends, so a malicious one could ask for any file.
local_infile_dir turns it on for the files inside that directory
(resolved when connecting, symbolic links included); a request is
answered only if the statement being run names that very file and
the file, resolved too, is inside the directory. Anything else is
refused with OperationalError 2068 and an empty
file, without reading the disk. Relative names start at the working
directory, as in other clients. local_infile=True is accepted for
compatibility but needs local_infile_dir: rustmy never sends
files from anywhere.
Prepared statements (PreparedCursor) are
prepared once per connection: the last statement_cache_size stay
prepared on the server, which allows 16,382 across all its
connections by default (max_prepared_stmt_count); when it is
full (error 1461), the least recently used one is closed and the
statement prepared again, once.
The server lists every connection's attributes in
performance_schema.session_connect_attrs: rustmy sends
_client_name, _client_version, _os, _platform and
_pid, program_name names the application, and
conn_attrs adds any others (str names and values; names
starting with _ are reserved). MySQL keeps names up to 32
characters and values up to 1024, and 512 bytes per connection by
default (performance_schema_session_connect_attrs_size).
TLS: ssl_mode is one of disabled, preferred (default),
required (encrypted, server not verified), verify_ca and
verify_identity. Passing ssl_ca alone means
verify_identity against that CA only; the verify modes without
ssl_ca trust the operating system's certificate store.
ssl_cert/ssl_key present a client certificate. ssl accepts
the {"ca", "cert", "key", "check_hostname"} dict of other MySQL
drivers, or True/False.
Without TLS, accounts using caching_sha2_password (MySQL's
default) or sha256_password send their password RSA-encrypted
with the server's public key, which is requested from the server as
PyMySQL does. server_public_key (a PEM file) pins the key
instead, so a man in the middle cannot substitute its own.
get_server_public_key=False never asks for it, as libmysqlclient
does by default: those accounts then need TLS, a Unix socket or a
pinned key, and fail with OperationalError 2061
otherwise.
encoders
instance-attribute
¶
Python types to SQL literal encoders (MySQLdb's attribute), from conv; escape() takes it as its mapping.
no_backslash_escapes
property
¶
no_backslash_escapes: bool
Whether the session has NO_BACKSLASH_ESCAPES in its SQL mode.
cursor
¶
cursor(
cursorclass: type[Cursor] | None = None,
*,
cursor: type[Cursor] | None = None,
prepared: bool = False,
) -> Cursor
Create a cursor of cursorclass, by default the one given to
connect(). cursor= is accepted as an alias (PyMySQL's name).
prepared=True gives that class's prepared-statement version
(PreparedCursor for Cursor,
PreparedDictCursor for DictCursor).
escape
¶
reset_connection
¶
Return the session to its just-connected state, cheaply.
Rolls back any open transaction, drops temporary tables and clears
user and session variables without re-authenticating, then applies
init_command and the autocommit mode given to connect()
again. Useful for connection pools.
change_user
¶
Re-authenticate as another account on this connection.
The session is reset as with reset_connection(), then
init_command and the autocommit mode given to connect()
are applied again.
close
¶
Close the connection.
Closing it again raises InterfaceError, as PEP 249 asks of
any use of a closed connection (leaving a with block does not).
A connection that broke (server gone, timeout) can still be closed.
set_character_set
¶
Switch the session to charset (and collation, if given).
Queries are encoded and results decoded in it from now on, and it
survives reset_connection() and change_user().