# This file was generated by stubgen-pyx v0.2.18 from /Users/long2ice/Developer/long2ice/asyncmy/asyncmy/connection.pyx
from typing_extensions import Self
from asyncmy.contexts import _ConnectionContextManager

from typing import Any, Optional, Type

from asyncmy import errors
from asyncmy.cursors import Cursor
from asyncmy.protocol import MysqlPacket

class Connection:
    """
    Representation of a socket with a mysql server.

    The proper way to get an instance of this class is to call
    connect().

    Establish a connection to the MySQL database. Accepts several
    arguments:

    :param host: Host where the database server is located.
    :param user: Username to log in as.
    :param password: Password to use.
    :param password_creator:
        Callable returning the password to authenticate with, consulted before
        every connection attempt — including the ones a pool makes on its own
        when it recycles or reconnects, which is the point: short-lived
        credentials such as AWS RDS IAM tokens expire while pooled connections
        outlive them, and nothing else gives you a hook at that moment.
        May be a plain function or return an awaitable. Must return ``str`` or
        ``bytes``. Takes precedence over ``password`` when both are given.
    :param database: Database to use, None to not use a particular one.
    :param port: MySQL port to use, default is usually OK. (default: 3306)
    :param unix_socket: Use a unix socket rather than TCP/IP.
    :param sock:
        An already-connected socket to speak MySQL over, instead of connecting
        to ``host``/``port`` ourselves. Combine it with ``ssl`` to hand the
        driver a connection whose TLS is set up by the caller rather than
        negotiated in-protocol — what connectors that front the server with a
        TLS proxy (e.g. Cloud SQL) need. The socket is used by a single
        connection and is closed with it, so a pool needs a fresh socket per
        connection; reconnecting one raises. Keep-alive and TCP_NODELAY are
        left to the caller.
    :param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
    :param charset: Charset to use.
    :param sql_mode: Default SQL_MODE to use.
    :param read_default_file:
        Specifies  my.cnf file to read these parameters from under the [client] section.
    :param conv:
        Conversion dictionary to use instead of the default one.
        This is used to provide custom marshalling and unmarshalling of types.
        See converters.
    :param use_unicode:
        Whether or not to default to unicode strings.
        This option defaults to true.
    :param client_flag: Custom flags to send to MySQL. Find potential values in constants.
    :param cursor_cls: Custom cursor class to use.
    :param query_callback:
        Called as ``callback(cursor, query, elapsed_ms)`` after every statement,
        with the duration as a float in milliseconds. Use it to route statement
        logging wherever you want — a different level than ``echo``'s INFO, a
        slow-query log, a tracing span. ``executemany`` and ``callproc`` report
        once for the whole call rather than per row. Independent of ``echo``:
        setting both logs and calls back.
    :param init_command: Initial SQL statement to run when connection is established.
    :param connect_timeout: The timeout for connecting to the database in seconds.
        (default: 10, min: 1, max: 31536000)
    :param ssl: Optional dict of arguments similar to mysql_ssl_set()'s parameters or SSL Context to force SSL
    :param read_default_group: Group to read from in the configuration file.
    :param autocommit: Autocommit mode. None means use server default. (default: False)
    :param local_infile: Boolean to enable the use of LOAD DATA LOCAL  (default: False)
    :param max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
        Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
    :param auth_plugin_map: A dict of plugin names to a class that processes that plugin.
        The class will take the Connection object as the argument to the constructor.
        The class needs an authenticate method taking an authentication packet as
        an argument.  For the dialog plugin, a prompt(echo, prompt) method can be used
        (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: Add _binary prefix on bytes and bytearray. (default: False)
    :param db: **DEPRECATED** Alias for database.

    See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_ in the
    specification.
    """

    Warning = errors.Warning
    Error = errors.Error
    InterfaceError = errors.InterfaceError
    DatabaseError = errors.DatabaseError
    DataError = errors.DataError
    OperationalError = errors.OperationalError
    IntegrityError = errors.IntegrityError
    InternalError = errors.InternalError
    ProgrammingError = errors.ProgrammingError
    NotSupportedError = errors.NotSupportedError

    # Injected onto the instance by BinLogStream
    # (replication/binlogstream.py), hence declared but not defined.
    _get_table_information: Any

    def __init__(
        self,
        *,
        user=None,
        password="",
        password_creator=None,
        host=None,
        database=None,
        unix_socket=None,
        sock=None,
        port=0,
        charset="",
        sql_mode=None,
        read_default_file=None,
        conv=None,
        use_unicode=True,
        client_flag=0,
        cursor_cls=Cursor,
        init_command=None,
        connect_timeout=10,
        read_default_group=None,
        autocommit=False,
        local_infile=False,
        max_allowed_packet=16 * 1024 * 1024,
        auth_plugin_map=None,
        read_timeout=None,
        binary_prefix=False,
        program_name=None,
        server_public_key=None,
        echo=False,
        query_callback=None,
        ssl=None,
        stmt_cache_size=0,
        db=None,
    ): ...
    def close(self) -> None:
        """Close socket connection"""
    @property
    def connected(self):
        """Return True if the connection is open."""
    @property
    def loop(self): ...
    @property
    def last_usage(self):
        """Return time() when connection was used."""
    async def ensure_closed(self) -> None:
        """Send QUIT message and close connection."""
    async def autocommit(self, value): ...
    def get_autocommit(self) -> bool: ...
    async def begin(self) -> None:
        """Begin transaction."""
    async def commit(self) -> None:
        """
        Commit changes to stable storage.

        See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
        in the specification.
        """
    async def rollback(self) -> None:
        """
        Roll back the current transaction.

        See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
        in the specification.
        """
    async def show_warnings(self):
        """Send the "SHOW WARNINGS" SQL"""
    async def select_db(self, db) -> None:
        """
        Set current db.

        :param db: The name of the db.
        """
    def escape(self, obj, mapping=None):
        """Escape whatever value is passed.

        Non-standard, for internal use; do not use this in your applications.
        """
    def literal(self, obj):
        """Alias for escape().

        Non-standard, for internal use; do not use this in your applications.
        """
    def escape_string(self, s) -> str: ...
    def cursor(self, cursor: Optional[Type[Cursor]] | None = None) -> Cursor:
        """
        Create a new cursor to execute queries with.

        :param cursor: The type of cursor to create. None means use Cursor.
        :type cursor: :py:class:`Cursor`, :py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
        """
    async def query(self, sql, unbuffered=False): ...
    async def next_result(self, unbuffered=False): ...
    async def prepare(self, query):
        """Create a server-side prepared statement (binary protocol).

        Returns a :class:`PreparedStatement`. Executing it skips client-side
        escaping entirely and reads results in the binary protocol, which is
        significantly faster for repeated (point) queries.

        :param query: SQL with ``?`` placeholders (native MySQL syntax).
        """
    def affected_rows(self) -> int: ...
    async def kill(self, thread_id): ...
    async def ping(self, reconnect=True) -> None:
        """
        Check if the server is alive.

        :param reconnect: If the connection is closed, reconnect.
        :type reconnect: boolean

        :raise Error: If the connection is closed and reconnect=False.
        """
    async def set_charset(self, charset) -> None: ...
    async def connect(self) -> _ConnectionContextManager[Connection]: ...
    def write_packet(self, payload: bytes):
        """
        Writes an entire "mysql packet" in its entirety to the network
        adding its length and sequence number.
        """
    async def read_packet(self, packet_type=MysqlPacket):
        """
        Read an entire "mysql packet" in its entirety from the network
        and return a MysqlPacket type that represents the results.

        :raise OperationalError: If the connection to the MySQL server is lost.
        :raise InternalError: If the packet sequence number is wrong.
        """
    def insert_id(self) -> int: ...
    async def __aenter__(self) -> Self: ...
    async def __aexit__(self, exc_type, exc_val, exc_tb): ...
    def thread_id(self) -> int: ...
    def character_set_name(self): ...
    def get_host_info(self) -> str: ...
    def get_proto_info(self) -> int: ...
    def get_transaction_status(self) -> bool: ...
    def get_server_info(self) -> str: ...

class PreparedStatement:
    """A server-side prepared statement (binary protocol).

    Created via :meth:`Connection.prepare`. Parameters are sent in binary form
    (no client-side escaping) and result rows are parsed from the binary
    protocol (no text parsing for numeric/temporal columns).

    Notes:
    - placeholders use native MySQL ``?`` syntax, not ``%s``;
    - custom ``conv`` decoders apply only to string-typed columns; numeric and
      temporal columns decode natively;
    - only the first result set is returned (extra sets are drained).
    """
    def __init__(self, connection, statement_id, parameter_count): ...
    @property
    def parameter_count(self): ...
    async def execute(self, args=()):
        """Execute with ``args`` bound to the statement's ``?`` placeholders.

        Returns the result object: ``result.rows`` (tuple of row tuples, None
        for non-SELECT), ``result.affected_rows``, ``result.insert_id``,
        ``result.description``.
        """
    async def execute_bulk(self, rows):
        """MariaDB COM_STMT_BULK_EXECUTE: bind many rows in one round-trip.

        ``rows`` is a sequence of parameter tuples. Returns the result object
        (``affected_rows``, ``insert_id``). Only usable when the server
        advertises MARIADB_CLIENT_STMT_BULK_OPERATIONS.
        """
    async def close(self) -> None:
        """Deallocate the statement on the server (no server response)."""
    async def __aenter__(self) -> Self: ...
    async def __aexit__(self, exc_type, exc_val, exc_tb): ...

class MySQLResult:
    connection: Any
    message: bytes
    warning_count: int
    field_count: int
    server_status: int
    unbuffered_active: int
    has_next: int
    affected_rows: object
    fields: list
    converters: list
    insert_id: int
    rows: tuple
    description: tuple

    def __init__(self, connection: Connection): ...
    def __del__(self): ...
    async def read(self): ...
    async def read_binary(self, stmt=None):
        """Read a COM_STMT_EXECUTE response (binary protocol result set)."""
    async def init_unbuffered_query(self):
        """
        :raise OperationalError: If the connection to the MySQL server is lost.
        :raise InternalError:
        """

class LoadLocalFile:
    def __init__(self, filename: str, connection: Connection): ...
    async def send_data(self):
        """
        Send data packets from the local file to the server
        """

def connect(
    user=None,
    password="",
    password_creator=None,
    host=None,
    database=None,
    unix_socket=None,
    sock=None,
    port=0,
    charset="",
    sql_mode=None,
    read_default_file=None,
    conv=None,
    use_unicode=True,
    client_flag=0,
    cursor_cls=Cursor,
    init_command=None,
    connect_timeout=10,
    read_default_group=None,
    autocommit=False,
    local_infile=False,
    max_allowed_packet=16 * 1024 * 1024,
    auth_plugin_map=None,
    read_timeout=None,
    binary_prefix=False,
    program_name=None,
    echo=False,
    query_callback=None,
    server_public_key=None,
    ssl=None,
    stmt_cache_size=0,
    db=None,
) -> _ConnectionContextManager[Connection]: ...
