High-performance MySQL driver for Python
Project description
pyro-mysql
A high-performance MySQL driver for Python, backed by Rust.
Usage
0. Import
# Async
from pyro_mysql.async_ import Conn, Pool
from pyro_mysql import AsyncConn, AsyncPool
# Sync
from pyro_mysql.sync import Conn, Transaction
from pyro_mysql import SyncConn, SyncTransaction
1. Connection
import pyro_mysql
from pyro_mysql.async_ import Conn, Pool, OptsBuilder
# Optionally configure the number of Rust threads
# pyro_mysql.init(worker_threads=1)
def example1():
conn = await Conn.new(f"mysql://{USER}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}")
def example2():
pool = Pool(
OptsBuilder()
.ip_or_hostname("localhost")
.port(3333)
.user("username")
.db_name("db")
.wait_timeout(100)
.tcp_nodelay(True)
.compression(3)
.build()
)
conn = await pool.acquire()
def example3(pool):
with pool.acquire() as conn:
...
2. Query Execution
AsyncConn and AsyncTransaction provide the following methods.
SyncConn, SyncPooledConn and SyncTransaction provide similar API.
# Text Protocols - supports multiple statements concatenated with ';' but accepts no arguemnt
def query(self, query: str) -> PyroFuture[list[Row]]
def query_first(self, query: str) -> PyroFuture[Row | None]
def query_drop(self, query: str) -> PyroFuture[None]
def query_batch(self, query: str) -> PyroFuture[None]
# Binary Protocols - supports arguments but no multiple statement
def exec(self, query: str, params: Params) -> PyroFuture[list[Row]]
def exec_first(self, query: str, params: Params) -> PyroFuture[Row | None]
def exec_drop(self, query: str, params: Params) -> PyroFuture[None]
def exec_batch(self, query: str, params: Iterable[Params]) -> PyroFuture[None]
# Examples
rows = await conn.exec("SELECT * FROM my_table WHERE a=? AND b=?", (a, b))
rows = await conn.exec("SELECT * FROM my_table WHERE a=:x AND b=:y AND c=:y", {'x': 100, 'y': 200})
await conn.exec_batch("SELECT * FROM my_table WHERE a=? AND b=?", [(a1, b1), (a2, b2)])
PyroFuture is a Future-like object that tracks a task in the Rust thread. When an object of PyroFuture is dropped before completion or cancellation, the corresponding task in the Rust thread is cancelled.
fut = conn.exec("SELECT ...") # the Rust thread starts to execute the query before we await the Python future.
print(fut.get_loop()) # get the associated Python event loop
fut.cancel() # cancels the Rust task
del fut # this is equivalent to .cancel()
3. Transaction
# async API
async with conn.start_transaction() as tx:
await tx.exec('INSERT ..')
await tx.exec('INSERT ..')
await tx.commit() # tx cannot be used anymore
await conn.exec(..) # error
# sync API
with conn.start_transaction() as tx:
tx.exec('INSERT ..')
tx.exec('INSERT ..')
conn.exec('INSERT ..') # error
tx.commit() # tx cannot be used anymore
DataType Mapping
Python -> MySQL
| Python Type | MySQL Binary Protocol Encoding |
|---|---|
None |
NULL |
bool |
Int64 |
int |
Int64 |
float |
Double(Float64) |
str | bytearray |
Bytes |
tuple | list | set | frozenset | dict |
json-encoded string as Bytes |
datetime.datetime |
Date(year, month, day, hour, minute, second, microsecond) |
datetime.date |
Date(year, month, day, 0, 0, 0, 0) |
datetime.time |
Time(false, 0, hour, minute, second, microsecond) |
datetime.timedelta |
Time(is_negative, days, hours, minutes, seconds, microseconds) |
time.struct_time |
Date(year, month, day, hour, minute, second, 0) |
decimal.Decimal |
Bytes |
MySQL -> Python
| MySQL Column | Python |
|---|---|
NULL |
None |
INT / TINYINT / SMALLINT / MEDIUMINT / BIGINT / YEAR |
int |
FLOAT |
float |
DOUBLE |
float |
DECIMAL / NUMERIC |
decimal.Decimal |
DATE |
datetime.date |
TIME |
datetime.timedelta |
DATETIME |
datetime.datetime |
TIMESTAMP |
datetime.datetime |
CHAR / VARCHAR / TEXT / TINYTEXT / MEDIUMTEXT / LONGTEXT |
str |
BINARY / VARBINARY / BLOB / TINYBLOB / MEDIUMBLOB / LONGBLOB |
bytes |
JSON |
the result of json.loads() |
ENUM / SET |
str |
BIT |
bytes |
GEOMETRY |
bytes (WKB format) |
Logging
pyro-mysql sends the Rust logs to the Python logging system, which can be configured with logging.getLogger("pyro_mysql").
# Queries are logged with the DEBUG level
logging.getLogger("pyro_mysql").setLevel(logging.DEBUG)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyro_mysql-0.1.2.tar.gz.
File metadata
- Download URL: pyro_mysql-0.1.2.tar.gz
- Upload date:
- Size: 731.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: maturin/1.9.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
adc2d177d54ac922c55d8abcfdb72f565a1b0dfccd6efd2ee587a2dc8463814e
|
|
| MD5 |
1bb36aecb8e39a7e620d62501b461779
|
|
| BLAKE2b-256 |
64e1a75ca74fb16892a12554e8208f93aedb7d2d7da73918f686aa9679c6b013
|
File details
Details for the file pyro_mysql-0.1.2-cp314-abi3-manylinux_2_34_x86_64.whl.
File metadata
- Download URL: pyro_mysql-0.1.2-cp314-abi3-manylinux_2_34_x86_64.whl
- Upload date:
- Size: 2.1 MB
- Tags: CPython 3.14+, manylinux: glibc 2.34+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: maturin/1.9.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
13331c31e117a964014ad68e281780731cb761b3d2e176fea22e752e7fe65270
|
|
| MD5 |
83c051aa91ca33787480ae67277a8188
|
|
| BLAKE2b-256 |
e69cdb45bd1ffc491a7d828a2afc6deced35b2b9501bbd817e4b016381c770cc
|
File details
Details for the file pyro_mysql-0.1.2-cp310-abi3-manylinux_2_34_x86_64.whl.
File metadata
- Download URL: pyro_mysql-0.1.2-cp310-abi3-manylinux_2_34_x86_64.whl
- Upload date:
- Size: 2.2 MB
- Tags: CPython 3.10+, manylinux: glibc 2.34+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: maturin/1.9.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c09652a8ed1fed104d01488486aeb05f7aa95d81f38fe9f7a41b839e9c9837a4
|
|
| MD5 |
1784a40fb561406e4ed9e5de97e8b3bd
|
|
| BLAKE2b-256 |
0ecc2fba343cc6b3bd40dde808f0cde6e596afd5a264752c40a303e6b3135995
|