pyro_mysql API documentation

# pyro_mysql

pyro_mysql - High-performance MySQL driver for Python.

    import asyncio
    import pyro_mysql as mysql

    mysql.init(worker_threads=1)

    async def example_select():
        conn = await mysql.Conn.new("mysql://localhost@127.0.0.1:3306/test")
        rows = await conn.exec("SELECT * from mydb.mytable")
        print(row[-1].to_dict())

    async def example_transaction():
        conn = await mysql.Conn.new("mysql://localhost@127.0.0.1:3306/test")

        async with conn.start_transaction() as tx:
            await tx.exec_drop(
                "INSERT INTO test.asyncmy(`decimal`, `date`, `datetime`, `float`, `string`, `tinyint`) VALUES (?,?,?,?,?,?)",
                (
                    1,
                    "2021-01-01",
                    "2020-07-16 22:49:54",
                    1,
                    "asyncmy",
                    1,
                ),
            )
            await tx.commit()

        await len(conn.exec('SELECT * FROM mydb.mytable')) == 100

    # The connection pool is not tied to a single event loop.
    # You can reuse the pool between event loops.
    asyncio.run(example_pool())
    asyncio.run(example_select())
    asyncio.run(example_transaction())
    ...

View Source

    1from .pyro_mysql import *
    2
    3__doc__ = pyro_mysql.__doc__
    4if hasattr(pyro_mysql, "__all__"):
    5    __all__ = pyro_mysql.__all__

def init( worker_threads: int | None = None, thread_name: str | None = None) -> None:

Initialize the Tokio runtime for async operations. This function can be called multiple times until Any async operation is called.

###### Arguments:

- worker_threads: Number of worker threads for the Tokio runtime. Defaults to the number of CPUs.
- thread_name: Name prefix for worker threads.

class Row:

A row returned from a MySQL query. to_list() / to_dict() copies the data, and should not be called many times.

def to_list(self) -> list[typing.Any]:

Convert the row to a Python list.

def to_dict(self) -> dict[str, typing.Any]:

The type of the None singleton.

class Pool:

MySQL connection pool.

Pool(url: str)

Create a new connection pool. Note: new() won't assert server availability.

###### Arguments:

- url: MySQL connection URL (e.g., 'mysql://root:password@127.0.0.1:3307/mysql').

def acquire(self, /):

The type of the None singleton.

class Conn:

MySQL connection.

The API is thread-safe. The underlying implementation is protected by RwLock.

Conn()

Direct instantiation is not allowed. Use Conn.new() instead.

async def new(url: str) -> Conn:

Create a new connection.

###### Arguments:

- url: MySQL connection URL (e.g., 'mysql://user:password@host:port/database').

###### Returns:

> New Conn instance.

def start_transaction(self, opts: pyro_mysql.TxOpts = Ellipsis) -> Transaction:

Start a new transaction.

###### Arguments:

- opts: Transaction options.

###### Returns:

> New Transaction instance.

def affected_rows(self, /):

The type of the None singleton.

async def close_prepared_statement(self, stmt: str) -> None:

Close a prepared statement (not yet implemented).

async def ping(self) -> None:

Ping the server to check connection.

async def exec( self, query: str, params: Params = None) -> list[Row]:

Execute a query and return all rows.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> List of Row objects.

async def exec_first( self, query: str, params: Params = None) -> Row | None:

Execute a query and return the first row.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> First Row or None if no results.

async def exec_drop(self, query: str, params: Params = None) -> None:

Execute a query and discard the results.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

async def exec_batch(self, query: str, params: list[Params] = []) -> None:

Execute a query multiple times with different parameters.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: List of parameter sets.

class Transaction:

Represents a MySQL transaction with async context manager support.

async def commit(self) -> None:

Commit the transaction.

async def rollback(self) -> None:

Rollback the transaction.

def affected_rows(self, /):

The type of the None singleton.

async def close_prepared_statement(self, stmt: str) -> None:

Close a prepared statement (not yet implemented).

async def ping(self) -> None:

Ping the server to check connection.

async def exec( self, query: str, params: Params = None) -> list[Row]:

Execute a query and return all rows.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> List of Row objects.

async def exec_first( self, query: str, params: Params = None) -> Row | None:

Execute a query and return the first row.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> First Row or None if no results.

async def exec_drop(self, query: str, params: Params = None) -> None:

Execute a query and discard the results.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

async def exec_batch(self, query: str, params: list[Params] = []) -> None:

Execute a query multiple times with different parameters.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: List of parameter sets.

class IsolationLevel:

Transaction isolation level enum.

def as_str(self) -> str:

Return the isolation level as a string.

ReadUncommitted: IsolationLevel = IsolationLevel.ReadUncommitted
ReadCommitted: IsolationLevel = IsolationLevel.ReadCommitted
RepeatableRead: IsolationLevel = IsolationLevel.RepeatableRead
Serializable: IsolationLevel = IsolationLevel.Serializable
class SyncConn:

Synchronous MySQL connection.

SyncConn(url: str)

Create a new synchronous connection.

###### Arguments:

- url: MySQL connection URL (e.g., 'mysql://user:password@host:port/database').

def run_transaction( self, callable: Any, consistent_snapshot: bool = False, isolation_level: IsolationLevel | None = None, readonly: bool | None = None) -> Any:

Run a transaction with a callable.

###### Arguments:

- callable: A callable that will receive the transaction object.
- consistent_snapshot: Whether to use consistent snapshot.
- isolation_level: Transaction isolation level.
- readonly: Whether the transaction is read-only.

###### Returns:

> The return value of the callable.

def affected_rows(self) -> int:

Get the number of affected rows from the last operation.

def ping(self) -> None:

Ping the server to check connection.

def exec( self, query: str, params: Params = None) -> list[Row]:

Execute a query and return all rows.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> List of Row objects.

def exec_first( self, query: str, params: Params = None) -> Row | None:

Execute a query and return the first row.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

###### Returns:

> First Row or None if no results.

def exec_drop(self, query: str, params: Params = None) -> None:

Execute a query and discard the results.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params: Query parameters.

def exec_batch(self, query: str, params_list: list[Params] = []) -> None:

Execute a query multiple times with different parameters.

###### Arguments:

- query: SQL query string with '?' placeholders.
- params_list: List of parameter sets.

def close(self) -> None:

Close the connection.

Value: 'type[None | bool | int | float | str | bytes | bytearray | tuple[Any, ...] | list[Any] | dict[str, Any] | datetime.datetime | datetime.date | datetime.time | datetime.timedelta | time.struct_time | decimal.Decimal]'

Type alias for the purpose of documenation.

These Python types can be converted to MySQL values:

- None
- bool
- int
- float
- str
- bytes
- bytearray
- tuple[Any, ...]
- list[Any]
- dict[str, Any]
- datetime.datetime
- datetime.date
- datetime.time
- datetime.timedelta
- time.struct_time
- decimal.Decimal

Params: 'type[None | tuple[Value, ...] | list[Value] | dict[str, Value]]'

Type alias for the purpose of documenation.

Parameters that can be passed to query execution methods:

- None: No parameters
- tuple[Value, ...]: Positional parameters for queries with ? placeholders
- list[Value]: List of parameters for queries with ? placeholders
- dict[str, Value]: Named parameters for queries with named placeholders

Examples:

###### No parameters:

> await conn.exec("SELECT * FROM users")

###### Positional parameters:

> await conn.exec("SELECT * FROM users WHERE id = ?", (123,))

###### Multiple positional parameters:

> await conn.exec("SELECT * FROM users WHERE age > ? AND city = ?", (18, "NYC"))

###### Named parameters:

> await conn.exec("SELECT * FROM users WHERE age > :age AND city = :city", dict(age=18, name="NYC"))