File python36-compat.patch of Package python-mysql-connector-python.18765
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/abstracts.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/abstracts.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/abstracts.py
@@ -30,7 +30,6 @@
"""Module gathering all abstract base classes."""
-from __future__ import annotations
import os
import re
@@ -120,7 +119,7 @@ from .types import (
)
from .utils import GenericWrapper, import_object
-NAMED_TUPLE_CACHE: weakref.WeakValueDictionary[Any, Any] = weakref.WeakValueDictionary()
+NAMED_TUPLE_CACHE = weakref.WeakValueDictionary()
DUPLICATED_IN_LIST_ERROR = (
"The '{list}' list must not contain repeated values, the value "
@@ -179,10 +178,10 @@ class CMySQLPrepStmt(GenericWrapper):
class MySQLConnectionAbstract(ABC):
"""Abstract class for classes connecting to a MySQL server."""
- def __init__(self) -> None:
+ def __init__(self) :
"""Initialize"""
# private (shouldn't be manipulated directly internally)
- self.__charset_id: Optional[int] = None
+ self.__charset_id = None
"""It shouldn't be manipulated directly, even internally. If you need
to manipulate the charset ID, use the property `_charset_id` (read & write)
instead. Similarly, `_charset_id` shouldn't be manipulated externally,
@@ -190,82 +189,82 @@ class MySQLConnectionAbstract(ABC):
"""
# protected (can be manipulated directly internally)
- self._tracer: Any = None # opentelemetry related
- self._span: Any = None # opentelemetry related
- self.otel_context_propagation: bool = True # opentelemetry related
-
- self._client_flags: int = ClientFlag.get_default()
- self._sql_mode: Optional[str] = None
- self._time_zone: Optional[str] = None
- self._autocommit: bool = False
- self._server_version: Optional[Tuple[int, ...]] = None
- self._handshake: Optional[HandShakeType] = None
- self._conn_attrs: Dict[str, str] = {}
-
- self._user: str = ""
- self._password: str = ""
- self._password1: str = ""
- self._password2: str = ""
- self._password3: str = ""
- self._database: str = ""
- self._host: str = "127.0.0.1"
- self._port: int = 3306
- self._unix_socket: Optional[str] = None
- self._client_host: str = ""
- self._client_port: int = 0
- self._ssl: Dict[str, Optional[Union[str, bool, List[str]]]] = {}
- self._ssl_disabled: bool = DEFAULT_CONFIGURATION["ssl_disabled"]
- self._force_ipv6: bool = False
- self._oci_config_file: Optional[str] = None
- self._oci_config_profile: Optional[str] = None
- self._webauthn_callback: Optional[Union[str, Callable[[str], None]]] = None
- self._krb_service_principal: Optional[str] = None
- self._openid_token_file: Optional[str] = None
-
- self._use_unicode: bool = True
- self._get_warnings: bool = False
- self._raise_on_warnings: bool = False
- self._connection_timeout: Optional[int] = DEFAULT_CONFIGURATION[
+ self._tracer = None # opentelemetry related
+ self._span = None # opentelemetry related
+ self.otel_context_propagation = True # opentelemetry related
+
+ self._client_flags = ClientFlag.get_default()
+ self._sql_mode = None
+ self._time_zone = None
+ self._autocommit = False
+ self._server_version = None
+ self._handshake = None
+ self._conn_attrs = {}
+
+ self._user = ""
+ self._password = ""
+ self._password1 = ""
+ self._password2 = ""
+ self._password3 = ""
+ self._database = ""
+ self._host = "127.0.0.1"
+ self._port = 3306
+ self._unix_socket = None
+ self._client_host = ""
+ self._client_port = 0
+ self._ssl = {}
+ self._ssl_disabled = DEFAULT_CONFIGURATION["ssl_disabled"]
+ self._force_ipv6 = False
+ self._oci_config_file = None
+ self._oci_config_profile = None
+ self._webauthn_callback = None
+ self._krb_service_principal = None
+ self._openid_token_file = None
+
+ self._use_unicode = True
+ self._get_warnings = False
+ self._raise_on_warnings = False
+ self._connection_timeout = DEFAULT_CONFIGURATION[
"connect_timeout"
]
- self._buffered: bool = False
- self._unread_result: bool = False
- self._have_next_result: bool = False
- self._raw: bool = False
- self._in_transaction: bool = False
- self._allow_local_infile: bool = DEFAULT_CONFIGURATION["allow_local_infile"]
- self._allow_local_infile_in_path: Optional[str] = DEFAULT_CONFIGURATION[
+ self._buffered = False
+ self._unread_result = False
+ self._have_next_result = False
+ self._raw = False
+ self._in_transaction = False
+ self._allow_local_infile = DEFAULT_CONFIGURATION["allow_local_infile"]
+ self._allow_local_infile_in_path = DEFAULT_CONFIGURATION[
"allow_local_infile_in_path"
]
- self._prepared_statements: Any = None
- self._query_attrs: Dict[str, BinaryProtocolType] = {}
+ self._prepared_statements = None
+ self._query_attrs = {}
- self._ssl_active: bool = False
- self._auth_plugin: Optional[str] = None
- self._auth_plugin_class: Optional[str] = None
- self._pool_config_version: Any = None
- self.converter: Optional[MySQLConverter] = None
- self._converter_class: Optional[Type[MySQLConverter]] = None
- self._converter_str_fallback: bool = False
- self._compress: bool = False
-
- self._consume_results: bool = False
- self._init_command: Optional[str] = None
- self._character_set: CharacterSet = CharacterSet()
+ self._ssl_active = False
+ self._auth_plugin = None
+ self._auth_plugin_class = None
+ self._pool_config_version = None
+ self.converter = None
+ self._converter_class = None
+ self._converter_str_fallback = False
+ self._compress = False
+
+ self._consume_results = False
+ self._init_command = None
+ self._character_set = CharacterSet()
- def __enter__(self) -> MySQLConnectionAbstract:
+ def __enter__(self) :
return self
def __exit__(
self,
- exc_type: Type[BaseException],
- exc_value: BaseException,
- traceback: TracebackType,
- ) -> None:
+ exc_type ,
+ exc_value ,
+ traceback ,
+ ) :
self.close()
- def get_self(self) -> MySQLConnectionAbstract:
+ def get_self(self) :
"""Returns self for `weakref.proxy`.
This method is used when the original object is needed when using
@@ -274,23 +273,23 @@ class MySQLConnectionAbstract(ABC):
return self
@property
- def is_secure(self) -> bool:
+ def is_secure(self) :
"""Returns `True` if is a secure connection."""
return self._ssl_active or (
self._unix_socket is not None and os.name == "posix"
)
@property
- def have_next_result(self) -> bool:
+ def have_next_result(self) :
"""Returns If have next result."""
return self._have_next_result
@property
- def query_attrs(self) -> List[Tuple[str, BinaryProtocolType]]:
+ def query_attrs(self) :
"""Returns query attributes list."""
return list(self._query_attrs.items())
- def query_attrs_append(self, value: Tuple[str, BinaryProtocolType]) -> None:
+ def query_attrs_append(self, value ) :
"""Adds element to the query attributes list on the connector's side.
If an element in the query attributes list already matches
@@ -303,7 +302,7 @@ class MySQLConnectionAbstract(ABC):
if attr_name not in self._query_attrs:
self._query_attrs[attr_name] = attr_value
- def query_attrs_remove(self, name: str) -> BinaryProtocolType:
+ def query_attrs_remove(self, name ) :
"""Removes element by name from the query attributes list on the connector's side.
If no match, `None` is returned, else the corresponding value is returned.
@@ -313,11 +312,11 @@ class MySQLConnectionAbstract(ABC):
"""
return self._query_attrs.pop(name, None)
- def query_attrs_clear(self) -> None:
+ def query_attrs_clear(self) :
"""Clears query attributes list on the connector's side."""
self._query_attrs = {}
- def _validate_tls_ciphersuites(self) -> None:
+ def _validate_tls_ciphersuites(self) :
"""Validates the tls_ciphersuites option."""
tls_ciphersuites = []
tls_cs = self._ssl["tls_ciphersuites"]
@@ -357,9 +356,9 @@ class MySQLConnectionAbstract(ABC):
newer_tls_ver = tls_versions[0]
# translated_names[0] are TLSv1.2 only
# translated_names[1] are TLSv1.3 only
- translated_names: List[List[str]] = [[], []]
+ translated_names = [[], []]
iani_cipher_suites_names = {}
- ossl_cipher_suites_names: List[str] = []
+ ossl_cipher_suites_names = []
# Old ciphers can work with new TLS versions.
# Find all the ciphers introduced on previous TLS versions.
@@ -412,7 +411,7 @@ class MySQLConnectionAbstract(ABC):
":".join(translated_names[1]),
]
- def _validate_tls_versions(self) -> None:
+ def _validate_tls_versions(self) :
"""Validates the tls_versions option."""
tls_versions = []
tls_version = self._ssl["tls_versions"]
@@ -494,57 +493,57 @@ class MySQLConnectionAbstract(ABC):
raise AttributeError(TLS_VERSION_ERROR.format(tls_ver, TLS_VERSIONS))
@property
- def user(self) -> str:
+ def user(self) :
"""The user name used for connecting to the MySQL server."""
return self._user
@property
- def server_host(self) -> str:
+ def server_host(self) :
"""MySQL server IP address or name."""
return self._host
@property
- def server_port(self) -> int:
+ def server_port(self) :
"MySQL server TCP/IP port."
return self._port
@property
- def unix_socket(self) -> Optional[str]:
+ def unix_socket(self) :
"The Unix socket file for connecting to the MySQL server."
return self._unix_socket
@property
@abstractmethod
- def database(self) -> str:
+ def database(self) :
"""The current database."""
@database.setter
- def database(self, value: str) -> None:
+ def database(self, value ) :
"""Sets the current database."""
self.cmd_query(f"USE {value}")
@property
- def can_consume_results(self) -> bool:
+ def can_consume_results(self) :
"""Returns whether to consume results."""
return self._consume_results
@can_consume_results.setter
- def can_consume_results(self, value: bool) -> None:
+ def can_consume_results(self, value ) :
"""Sets if can consume results."""
assert isinstance(value, bool)
self._consume_results = value
@property
- def pool_config_version(self) -> Any:
+ def pool_config_version(self) :
"""Returns the pool configuration version."""
return self._pool_config_version
@pool_config_version.setter
- def pool_config_version(self, value: Any) -> None:
+ def pool_config_version(self, value ) :
"""Sets the pool configuration version"""
self._pool_config_version = value
- def config(self, **kwargs: Any) -> None:
+ def config(self, **kwargs ) :
"""Configures the MySQL Connection.
This method allows you to configure the `MySQLConnection`
@@ -865,13 +864,13 @@ class MySQLConnectionAbstract(ABC):
"does not exist"
)
- def _add_default_conn_attrs(self) -> None:
+ def _add_default_conn_attrs(self) :
"""Adds the default connection attributes."""
@staticmethod
def _validate_callable(
- option_name: str, callback: Union[str, Callable], num_args: int = 0
- ) -> None:
+ option_name , callback , num_args = 0
+ ) :
"""Validates if it's a Python callable.
Args:
@@ -904,7 +903,7 @@ class MySQLConnectionAbstract(ABC):
)
@staticmethod
- def _check_server_version(server_version: StrOrBytes) -> Tuple[int, ...]:
+ def _check_server_version(server_version ) :
"""Checks the MySQL version.
This method will check the MySQL version and raise an InterfaceError
@@ -929,7 +928,7 @@ class MySQLConnectionAbstract(ABC):
return version
- def get_server_version(self) -> Optional[Tuple[int, ...]]:
+ def get_server_version(self) :
"""Gets the MySQL version.
Returns:
@@ -938,7 +937,7 @@ class MySQLConnectionAbstract(ABC):
"""
return self._server_version
- def get_server_info(self) -> Optional[str]:
+ def get_server_info(self) :
"""Gets the original MySQL version information.
Returns:
@@ -952,7 +951,7 @@ class MySQLConnectionAbstract(ABC):
@property
@abstractmethod
- def in_transaction(self) -> bool:
+ def in_transaction(self) :
"""Returns bool to indicate whether a transaction is active for the connection.
The value is `True` regardless of whether you start a transaction using the
@@ -972,7 +971,7 @@ class MySQLConnectionAbstract(ABC):
```
"""
- def set_client_flags(self, flags: Union[int, Sequence[int]]) -> int:
+ def set_client_flags(self, flags ) :
"""Sets the client flags.
The flags-argument can be either an int or a list (or tuple) of
@@ -1012,7 +1011,7 @@ class MySQLConnectionAbstract(ABC):
raise ProgrammingError("set_client_flags expect integer (>0) or set")
return self._client_flags
- def shutdown(self) -> NoReturn:
+ def shutdown(self) :
"""Shuts down connection to MySQL Server.
This method closes the socket. It raises no exceptions.
@@ -1023,7 +1022,7 @@ class MySQLConnectionAbstract(ABC):
"""
raise NotImplementedError
- def isset_client_flag(self, flag: int) -> bool:
+ def isset_client_flag(self, flag ) :
"""Checks if a client flag is set.
Returns:
@@ -1032,27 +1031,27 @@ class MySQLConnectionAbstract(ABC):
return (self._client_flags & flag) > 0
@property
- def time_zone(self) -> str:
+ def time_zone(self) :
"""Gets the current time zone."""
return self.info_query("SELECT @@session.time_zone")[
0
] # type: ignore[return-value]
@time_zone.setter
- def time_zone(self, value: str) -> None:
+ def time_zone(self, value ) :
"""Sets the time zone."""
self.cmd_query(f"SET @@session.time_zone = '{value}'")
self._time_zone = value
@property
- def sql_mode(self) -> str:
+ def sql_mode(self) :
"""Gets the SQL mode."""
if self._sql_mode is None:
self._sql_mode = self.info_query("SELECT @@session.sql_mode")[0]
return self._sql_mode
@sql_mode.setter
- def sql_mode(self, value: Union[str, Sequence[int]]) -> None:
+ def sql_mode(self, value ) :
"""Sets the SQL mode.
This method sets the SQL Mode for the current connection. The value
@@ -1071,7 +1070,7 @@ class MySQLConnectionAbstract(ABC):
self._sql_mode = value
@abstractmethod
- def info_query(self, query: str) -> Optional[RowType]:
+ def info_query(self, query ) :
"""Sends a query which only returns 1 row.
Shortcut for:
@@ -1090,8 +1089,8 @@ class MySQLConnectionAbstract(ABC):
"""
def set_login(
- self, username: Optional[str] = None, password: Optional[str] = None
- ) -> None:
+ self, username = None, password = None
+ ) :
"""Sets login information for MySQL.
Sets the username and/or password for the user connecting to the MySQL Server.
@@ -1109,7 +1108,7 @@ class MySQLConnectionAbstract(ABC):
else:
self._password = ""
- def set_unicode(self, value: bool = True) -> None:
+ def set_unicode(self, value = True) :
"""Toggles unicode mode.
Sets whether we return string fields as unicode or not.
@@ -1122,20 +1121,20 @@ class MySQLConnectionAbstract(ABC):
self.converter.set_unicode(value)
@property
- def autocommit(self) -> bool:
+ def autocommit(self) :
"""Gets whether autocommit is on or off."""
value = self.info_query("SELECT @@session.autocommit")[0]
return value == 1
@autocommit.setter
- def autocommit(self, value: bool) -> None:
+ def autocommit(self, value ) :
"""Toggles autocommit."""
switch = "ON" if value else "OFF"
self.cmd_query(f"SET @@session.autocommit = {switch}")
self._autocommit = value
@property
- def get_warnings(self) -> bool:
+ def get_warnings(self) :
"""Gets whether this connection retrieves warnings automatically.
This method returns whether this connection retrieves warnings
@@ -1146,7 +1145,7 @@ class MySQLConnectionAbstract(ABC):
return self._get_warnings
@get_warnings.setter
- def get_warnings(self, value: bool) -> None:
+ def get_warnings(self, value ) :
"""Sets whether warnings should be automatically retrieved.
The toggle-argument must be a boolean. When True, cursors for this
@@ -1159,7 +1158,7 @@ class MySQLConnectionAbstract(ABC):
self._get_warnings = value
@property
- def raise_on_warnings(self) -> bool:
+ def raise_on_warnings(self) :
"""Gets whether this connection raises an error on warnings.
This method returns whether this connection will raise errors when
@@ -1170,7 +1169,7 @@ class MySQLConnectionAbstract(ABC):
return self._raise_on_warnings
@raise_on_warnings.setter
- def raise_on_warnings(self, value: bool) -> None:
+ def raise_on_warnings(self, value ) :
"""Sets whether warnings raise an error.
The toggle-argument must be a boolean. When True, cursors for this
@@ -1190,7 +1189,7 @@ class MySQLConnectionAbstract(ABC):
self._get_warnings = value
@property
- def unread_result(self) -> bool:
+ def unread_result(self) :
"""Gets whether there is an unread result.
This method is used by cursors to check whether another cursor still
@@ -1201,7 +1200,7 @@ class MySQLConnectionAbstract(ABC):
return self._unread_result
@unread_result.setter
- def unread_result(self, value: bool) -> None:
+ def unread_result(self, value ) :
"""Sets whether there is an unread result.
This method is used by cursors to let other cursors know there is
@@ -1214,7 +1213,7 @@ class MySQLConnectionAbstract(ABC):
self._unread_result = value
@property
- def collation(self) -> str:
+ def collation(self) :
"""Returns the collation for current connection.
This property returns the collation name of the current connection.
@@ -1226,7 +1225,7 @@ class MySQLConnectionAbstract(ABC):
return self._character_set.get_charset_info(self._charset_id)[2]
@property
- def charset(self) -> str:
+ def charset(self) :
"""Returns the character set for current connection.
This property returns the character set name of the current connection.
@@ -1238,7 +1237,7 @@ class MySQLConnectionAbstract(ABC):
return self._character_set.get_info(self._charset_id)[0]
@property
- def charset_id(self) -> int:
+ def charset_id(self) :
"""The charset ID utilized during the connection phase.
If the charset ID hasn't been set, the default charset ID is returned.
@@ -1246,7 +1245,7 @@ class MySQLConnectionAbstract(ABC):
return self._charset_id
@property
- def _charset_id(self) -> int:
+ def _charset_id(self) :
"""The charset ID utilized during the connection phase.
If the charset ID hasn't been set, the default charset ID is returned.
@@ -1268,12 +1267,12 @@ class MySQLConnectionAbstract(ABC):
return self.__charset_id
@_charset_id.setter
- def _charset_id(self, value: int) -> None:
+ def _charset_id(self, value ) :
"""Sets the charset ID utilized during the connection phase."""
self.__charset_id = value
@property
- def python_charset(self) -> str:
+ def python_charset(self) :
"""Returns the Python character set for current connection.
This property returns the character set name of the current connection.
@@ -1289,8 +1288,8 @@ class MySQLConnectionAbstract(ABC):
return encoding
def set_charset_collation(
- self, charset: Optional[Union[int, str]] = None, collation: Optional[str] = None
- ) -> None:
+ self, charset = None, collation = None
+ ) :
"""Sets the character set and collation for the current connection.
This method sets the character set and collation to be used for
@@ -1357,18 +1356,18 @@ class MySQLConnectionAbstract(ABC):
@property
@abstractmethod
- def connection_id(self) -> Optional[int]:
+ def connection_id(self) :
"""MySQL connection ID."""
@abstractmethod
- def _do_handshake(self) -> None:
+ def _do_handshake(self) :
"""Gathers information of the MySQL server before authentication."""
@abstractmethod
- def _open_connection(self) -> None:
+ def _open_connection(self) :
"""Opens the connection to the MySQL server."""
- def _post_connection(self) -> None:
+ def _post_connection(self) :
"""Executes commands after connection has been established.
This method executes commands after the connection has been
@@ -1385,7 +1384,7 @@ class MySQLConnectionAbstract(ABC):
self._execute_query(self._init_command)
@abstractmethod
- def disconnect(self) -> None:
+ def disconnect(self) :
"""Disconnects from the MySQL server.
This method tries to send a `QUIT` command and close the socket. It raises
@@ -1398,9 +1397,9 @@ class MySQLConnectionAbstract(ABC):
use `shutdown()`.
"""
- close: Callable[[], Any] = disconnect
+ close = disconnect
- def connect(self, **kwargs: Any) -> None:
+ def connect(self, **kwargs ) :
"""Connects to the MySQL server.
This method sets up the connection to the MySQL server. If no
@@ -1454,7 +1453,7 @@ class MySQLConnectionAbstract(ABC):
# go back to sandbox mode.
self.cmd_query("ALTER USER CURRENT_USER() PASSWORD EXPIRE")
- def reconnect(self, attempts: int = 1, delay: int = 0) -> None:
+ def reconnect(self, attempts = 1, delay = 0) :
"""Attempts to reconnect to the MySQL server.
The argument `attempts` should be the number of times a reconnect
@@ -1510,7 +1509,7 @@ class MySQLConnectionAbstract(ABC):
set_connection_span_attrs(self, self._span)
@abstractmethod
- def is_connected(self) -> bool:
+ def is_connected(self) :
"""Reports whether the connection to MySQL Server is available or not.
Checks whether the connection to MySQL is available using the `ping()` method,
@@ -1519,7 +1518,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def ping(self, reconnect: bool = False, attempts: int = 1, delay: int = 0) -> None:
+ def ping(self, reconnect = False, attempts = 1, delay = 0) :
"""Checks availability of the MySQL server.
When reconnect is set to `True`, one or more attempts are made to try
@@ -1543,7 +1542,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def commit(self) -> None:
+ def commit(self) :
"""Commits current transaction.
This method is part of PEP 249 - Python Database API Specification v2.0.
@@ -1565,13 +1564,13 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cursor(
self,
- buffered: Optional[bool] = None,
- raw: Optional[bool] = None,
- prepared: Optional[bool] = None,
- cursor_class: Optional[Type["MySQLCursorAbstract"]] = None,
- dictionary: Optional[bool] = None,
- named_tuple: Optional[bool] = None,
- ) -> "MySQLCursorAbstract":
+ buffered = None,
+ raw = None,
+ prepared = None,
+ cursor_class = None,
+ dictionary = None,
+ named_tuple = None,
+ ) :
"""Instantiates and returns a cursor.
By default, `MySQLCursor` or `CMySQLCursor` is returned. Depending on the
@@ -1612,11 +1611,11 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def _execute_query(self, query: str) -> None:
+ def _execute_query(self, query ) :
"""Executes a query."""
@abstractmethod
- def rollback(self) -> None:
+ def rollback(self) :
"""Rollbacks current transaction.
Sends a ROLLBACK statement to the MySQL server, undoing all data changes
@@ -1634,10 +1633,10 @@ class MySQLConnectionAbstract(ABC):
def start_transaction(
self,
- consistent_snapshot: bool = False,
- isolation_level: Optional[str] = None,
- readonly: Optional[bool] = None,
- ) -> None:
+ consistent_snapshot = False,
+ isolation_level = None,
+ readonly = None,
+ ) :
"""Starts a transaction.
This method explicitly starts a transaction sending the
@@ -1708,9 +1707,9 @@ class MySQLConnectionAbstract(ABC):
def reset_session(
self,
- user_variables: Optional[Dict[str, Any]] = None,
- session_variables: Optional[Dict[str, Any]] = None,
- ) -> None:
+ user_variables = None,
+ session_variables = None,
+ ) :
"""Clears the current active session.
This method resets the session state, if the MySQL server is 5.7.3
@@ -1764,7 +1763,7 @@ class MySQLConnectionAbstract(ABC):
cur.execute(f"SET SESSION `{key}` = {value}")
cur.close()
- def set_converter_class(self, convclass: Optional[Type[MySQLConverter]]) -> None:
+ def set_converter_class(self, convclass ) :
"""
Sets the converter class to be used.
@@ -1785,11 +1784,11 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def get_row(
self,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- prep_stmt: Optional[CMySQLPrepStmt] = None,
- ) -> Tuple[Optional[RowType], Optional[Dict[str, Any]]]:
+ binary = False,
+ columns = None,
+ raw = None,
+ prep_stmt = None,
+ ) :
"""Retrieves the next row of a query result set.
Args:
@@ -1814,12 +1813,12 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def get_rows(
self,
- count: Optional[int] = None,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- prep_stmt: Optional[CMySQLPrepStmt] = None,
- ) -> Tuple[List[RowType], Optional[Dict[str, Any]]]:
+ count = None,
+ binary = False,
+ columns = None,
+ raw = None,
+ prep_stmt = None,
+ ) :
"""Gets all rows returned by the MySQL server.
Args:
@@ -1844,7 +1843,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_init_db(self, database: str) -> Optional[Dict[str, Any]]:
+ def cmd_init_db(self, database ) :
"""Changes the current database.
This method makes specified database the default (current) database.
@@ -1861,11 +1860,11 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_query(
self,
- query: str,
- raw: Optional[bool] = False,
- buffered: bool = False,
- raw_as_string: bool = False,
- ) -> Optional[Dict[str, Any]]:
+ query ,
+ raw = False,
+ buffered = False,
+ raw_as_string = False,
+ ) :
"""Sends a query to the MySQL server.
This method sends the query to the MySQL server and returns the result. To send
@@ -1902,8 +1901,8 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_query_iter(
- self, statements: str
- ) -> Generator[Mapping[str, Any], None, None]:
+ self, statements
+ ) :
"""Sends one or more statements to the MySQL server.
Similar to the `cmd_query()` method, but instead returns a generator
@@ -1934,7 +1933,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_refresh(self, options: int) -> Optional[Dict[str, Any]]:
+ def cmd_refresh(self, options ) :
"""Sends the Refresh command to the MySQL server.
`WARNING: This MySQL Server functionality is deprecated.`
@@ -1963,7 +1962,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_quit(self) -> Optional[bytes]:
+ def cmd_quit(self) :
"""Closes the current connection with the server.
This method sends the `QUIT` command to the MySQL server, closing the
@@ -1976,7 +1975,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_shutdown(self, shutdown_type: Optional[int] = None) -> None:
+ def cmd_shutdown(self, shutdown_type = None) :
"""Shuts down the MySQL Server.
This method sends the SHUTDOWN command to the MySQL server.
@@ -1984,7 +1983,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_statistics(self) -> Optional[Dict[str, Any]]:
+ def cmd_statistics(self) :
"""Sends the statistics command to the MySQL Server.
Returns:
@@ -1994,7 +1993,7 @@ class MySQLConnectionAbstract(ABC):
"""
@staticmethod
- def cmd_process_info() -> NoReturn:
+ def cmd_process_info() :
"""Get the process list of the MySQL Server.
This method is a placeholder to notify that the PROCESS_INFO command
@@ -2011,7 +2010,7 @@ class MySQLConnectionAbstract(ABC):
)
@abstractmethod
- def cmd_process_kill(self, mysql_pid: int) -> Optional[Dict[str, Any]]:
+ def cmd_process_kill(self, mysql_pid ) :
"""Kills a MySQL process.
Asks the server to kill the thread specified by `mysql_pid`. Although
@@ -2031,7 +2030,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_debug(self) -> Optional[Dict[str, Any]]:
+ def cmd_debug(self) :
"""Instructs the server to write debugging information to the error log.
The connected user must have the `SUPER` privilege.
@@ -2041,7 +2040,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_ping(self) -> Optional[Dict[str, Any]]:
+ def cmd_ping(self) :
"""Checks whether the connection to the server is working.
This method is not to be used directly. Use `ping()` or
@@ -2054,17 +2053,17 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_change_user(
self,
- username: str = "",
- password: str = "",
- database: str = "",
- charset: Optional[int] = None,
- password1: str = "",
- password2: str = "",
- password3: str = "",
- oci_config_file: str = "",
- oci_config_profile: str = "",
- openid_token_file: str = "",
- ) -> Optional[Dict[str, Any]]:
+ username = "",
+ password = "",
+ database = "",
+ charset = None,
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ oci_config_file = "",
+ oci_config_profile = "",
+ openid_token_file = "",
+ ) :
"""Changes the current logged in user.
It also causes the specified database to become the default (current)
@@ -2100,8 +2099,8 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_stmt_prepare(
- self, statement: bytes
- ) -> Union[Mapping[str, Any], CMySQLPrepStmt]:
+ self, statement
+ ) :
"""Prepares a MySQL statement.
Args:
@@ -2121,11 +2120,11 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_stmt_execute(
self,
- statement_id: Union[int, CMySQLPrepStmt],
- data: Sequence[BinaryProtocolType] = (),
- parameters: Sequence = (),
- flags: int = 0,
- ) -> Optional[Union[Dict[str, Any], Tuple]]:
+ statement_id ,
+ data = (),
+ parameters = (),
+ flags = 0,
+ ) :
"""Executes a prepared MySQL statement.
Args:
@@ -2161,7 +2160,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_stmt_close(self, statement_id: Union[int, CMySQLPrepStmt]) -> None:
+ def cmd_stmt_close(self, statement_id ) :
"""Deallocates a prepared MySQL statement.
Args:
@@ -2174,8 +2173,8 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
def cmd_stmt_send_long_data(
- self, statement_id: Union[int, CMySQLPrepStmt], param_id: int, data: BinaryIO
- ) -> int:
+ self, statement_id , param_id , data
+ ) :
"""Sends data for a column.
Currently, not implemented for the C-ext.
@@ -2198,7 +2197,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_stmt_reset(self, statement_id: Union[int, CMySQLPrepStmt]) -> None:
+ def cmd_stmt_reset(self, statement_id ) :
"""Resets data for prepared statement sent as long data.
Args:
@@ -2210,7 +2209,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- def cmd_reset_connection(self) -> bool:
+ def cmd_reset_connection(self) :
"""Resets the session state without re-authenticating.
Reset command only works on MySQL server 5.7.3 or later.
@@ -2234,48 +2233,46 @@ class MySQLCursorAbstract(ABC):
required by the Python Database API Specification v2.0.
"""
- def __init__(self, connection: Optional[MySQLConnectionAbstract] = None) -> None:
+ def __init__(self, connection = None) :
"""Defines the MySQL cursor interface."""
- self._connection: Optional[MySQLConnectionAbstract] = connection
+ self._connection = connection
if connection is not None:
if not isinstance(connection, MySQLConnectionAbstract):
raise InterfaceError(errno=2048)
self._connection = weakref.proxy(connection)
- self._description: Optional[List[DescriptionType]] = None
- self._rowcount: int = -1
- self._last_insert_id: Optional[int] = None
- self._warnings: Optional[List[WarningType]] = None
- self._warning_count: int = 0
- self._executed: Optional[bytes] = None
- self._executed_list: List[StrOrBytes] = []
- self._stored_results: List[MySQLCursorAbstract] = []
- self.arraysize: int = 1
- self._binary: bool = False
- self._raw: bool = False
- self._nextrow: Tuple[
- Optional[RowType], Optional[Union[EofPacketType, CextEofPacketType]]
- ] = (
+ self._description = None
+ self._rowcount = -1
+ self._last_insert_id = None
+ self._warnings = None
+ self._warning_count = 0
+ self._executed = None
+ self._executed_list = []
+ self._stored_results = []
+ self.arraysize = 1
+ self._binary = False
+ self._raw = False
+ self._nextrow = (
None,
None,
)
- def __enter__(self) -> MySQLCursorAbstract:
+ def __enter__(self) :
return self
def __exit__(
self,
- exc_type: Type[BaseException],
- exc_value: BaseException,
- traceback: TracebackType,
- ) -> None:
+ exc_type ,
+ exc_value ,
+ traceback ,
+ ) :
self.close()
@abstractmethod
def callproc(
- self, procname: str, args: Sequence = ()
- ) -> Optional[Union[Dict[str, RowItemType], RowType]]:
+ self, procname , args = ()
+ ) :
"""Calls a stored procedure with the given arguments.
The arguments will be set during this session, meaning they will be called like
@@ -2325,7 +2322,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- def close(self) -> None:
+ def close(self) :
"""Close the cursor.
Use close() when you are done using a cursor. This method closes the cursor,
@@ -2338,12 +2335,12 @@ class MySQLCursorAbstract(ABC):
@abstractmethod
def execute(
self,
- operation: str,
- params: Union[
- Sequence[MySQLConvertibleType], Dict[str, MySQLConvertibleType]
- ] = (),
- multi: bool = False,
- ) -> Optional[Generator[MySQLCursorAbstract, None, None]]:
+ operation ,
+ params
+
+ = (),
+ multi = False,
+ ) :
"""Executes the given operation substituting any markers with the given parameters.
For example, getting all rows where id is 5:
@@ -2391,11 +2388,11 @@ class MySQLCursorAbstract(ABC):
@abstractmethod
def executemany(
self,
- operation: str,
- seq_params: Sequence[
- Union[Sequence[MySQLConvertibleType], Dict[str, MySQLConvertibleType]]
- ],
- ) -> Optional[Generator[MySQLCursorAbstract, None, None]]:
+ operation ,
+ seq_params
+
+ ,
+ ) :
"""Executes the given operation multiple times.
The `executemany()` method will execute the operation iterating
@@ -2435,7 +2432,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- def fetchone(self) -> Optional[Union[RowType, Dict[str, RowItemType]]]:
+ def fetchone(self) :
"""Retrieves next row of a query result set
Returns:
@@ -2454,7 +2451,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- def fetchmany(self, size: int = 1) -> List[Union[RowType, Dict[str, RowItemType]]]:
+ def fetchmany(self, size = 1) :
"""Fetches the next set of rows of a query result.
Args:
@@ -2468,7 +2465,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- def fetchall(self) -> List[Union[RowType, Dict[str, RowItemType]]]:
+ def fetchall(self) :
"""Fetches all (or all remaining) rows of a query result set.
Returns:
@@ -2484,7 +2481,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- def stored_results(self) -> Iterator[MySQLCursorAbstract]:
+ def stored_results(self) :
"""Returns an iterator (of MySQLCursorAbstract subclass instances) for stored results.
This method returns an iterator over results which are stored when
@@ -2503,20 +2500,20 @@ class MySQLCursorAbstract(ABC):
```
"""
- def nextset(self) -> NoReturn:
+ def nextset(self) :
"""Not Implemented."""
- def setinputsizes(self, sizes: Any) -> NoReturn:
+ def setinputsizes(self, sizes ) :
"""Not Implemented."""
- def setoutputsize(self, size: Any, column: Any = None) -> NoReturn:
+ def setoutputsize(self, size , column = None) :
"""Not Implemented."""
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
"""Resets the cursor to default"""
@property
- def description(self) -> Optional[List[DescriptionType]]:
+ def description(self) :
"""This read-only property returns a list of tuples describing the columns in a
result set.
@@ -2544,7 +2541,7 @@ class MySQLCursorAbstract(ABC):
return self._description
@property
- def rowcount(self) -> int:
+ def rowcount(self) :
"""Returns the number of rows produced or affected.
This property returns the number of rows produced by queries
@@ -2561,7 +2558,7 @@ class MySQLCursorAbstract(ABC):
return self._rowcount
@property
- def lastrowid(self) -> Optional[int]:
+ def lastrowid(self) :
"""Returns the value generated for an AUTO_INCREMENT column.
Returns the value generated for an AUTO_INCREMENT column by
@@ -2573,7 +2570,7 @@ class MySQLCursorAbstract(ABC):
return self._last_insert_id
@property
- def warnings(self) -> Optional[List[WarningType]]:
+ def warnings(self) :
"""Returns a list of tuples (WarningType) containing warnings generated
by the previously executed operation.
@@ -2590,7 +2587,7 @@ class MySQLCursorAbstract(ABC):
return self._warnings
@property
- def warning_count(self) -> int:
+ def warning_count(self) :
"""Returns the number of warnings.
This property returns the number of warnings generated by the
@@ -2600,7 +2597,7 @@ class MySQLCursorAbstract(ABC):
"""
return self._warning_count
- def fetchwarnings(self) -> Optional[List[WarningType]]:
+ def fetchwarnings(self) :
"""Returns a list of tuples (WarningType) containing warnings generated by
the previously executed operation.
@@ -2616,7 +2613,7 @@ class MySQLCursorAbstract(ABC):
"""
return self._warnings
- def get_attributes(self) -> Optional[List[Tuple[str, BinaryProtocolType]]]:
+ def get_attributes(self) :
"""Gets a list of query attributes from the connector's side.
Returns:
@@ -2626,7 +2623,7 @@ class MySQLCursorAbstract(ABC):
return self._connection.query_attrs
return None
- def add_attribute(self, name: str, value: BinaryProtocolType) -> None:
+ def add_attribute(self, name , value ) :
"""Adds a query attribute and its value into the connector's query attributes list.
Query attributes must be enabled on the server - they are disabled by default. A
@@ -2649,7 +2646,7 @@ class MySQLCursorAbstract(ABC):
if hasattr(self, "_connection"):
self._connection.query_attrs_append((name, value))
- def remove_attribute(self, name: str) -> BinaryProtocolType:
+ def remove_attribute(self, name ) :
"""Removes a query attribute by name from the connector's query attributes list.
If no match, `None` is returned, else the corresponding value is returned.
@@ -2666,7 +2663,7 @@ class MySQLCursorAbstract(ABC):
return self._connection.query_attrs_remove(name)
return None
- def clear_attributes(self) -> None:
+ def clear_attributes(self) :
"""Clears the list of query attributes on the connector's side."""
if hasattr(self, "_connection"):
self._connection.query_attrs_clear()
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/protocol.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/protocol.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/protocol.py
@@ -27,7 +27,6 @@
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Implements the MySQL Client/Server protocol."""
-from __future__ import annotations
import datetime
import struct
@@ -90,7 +89,7 @@ class MySQLProtocol:
"""
@staticmethod
- def parse_auth_more_data(pkt: bytes) -> bytes:
+ def parse_auth_more_data(pkt ) :
"""Parse a MySQL auth more data packet.
Args:
@@ -112,7 +111,7 @@ class MySQLProtocol:
return pkt[5:]
@staticmethod
- def parse_auth_switch_request(pkt: bytes) -> Tuple[str, bytes]:
+ def parse_auth_switch_request(pkt ) :
"""Parse a MySQL auth switch request packet.
Args:
@@ -139,7 +138,7 @@ class MySQLProtocol:
return plugin_name.decode(), pkt
@staticmethod
- def parse_auth_next_factor(pkt: bytes) -> Tuple[str, bytes]:
+ def parse_auth_next_factor(pkt ) :
"""Parse a MySQL auth next factor packet.
Args:
@@ -166,7 +165,7 @@ class MySQLProtocol:
return plugin_name.decode(), pkt
@staticmethod
- def make_conn_attrs(conn_attrs: Dict[str, str]) -> bytes:
+ def make_conn_attrs(conn_attrs ) :
"""Encode the connection attributes.
Args:
@@ -197,7 +196,7 @@ class MySQLProtocol:
return b"".join(conn_attrs_packet)
@staticmethod
- def connect_with_db(client_flags: int, database: Optional[str]) -> bytes:
+ def connect_with_db(client_flags , database ) :
"""Prepare database string for handshake response.
Args:
@@ -219,14 +218,14 @@ class MySQLProtocol:
@staticmethod
def auth_plugin_first_response(
- auth_data: bytes,
- username: str,
- password: str,
- auth_plugin: str,
- auth_plugin_class: Optional[str] = None,
- ssl_enabled: bool = False,
- plugin_config: Optional[Dict[str, Any]] = None,
- ) -> Tuple[bytes, MySQLAuthPlugin]:
+ auth_data ,
+ username ,
+ password ,
+ auth_plugin ,
+ auth_plugin_class = None,
+ ssl_enabled = False,
+ plugin_config = None,
+ ) :
"""Prepare the first authentication response.
Args:
@@ -280,20 +279,20 @@ class MySQLProtocol:
@staticmethod
def make_auth(
- handshake: HandShakeType,
- username: str,
- password: str,
- database: Optional[str] = None,
- charset: int = DEFAULT_CHARSET_ID,
- client_flags: int = 0,
- max_allowed_packet: int = DEFAULT_MAX_ALLOWED_PACKET,
- auth_plugin: Optional[str] = None,
- auth_plugin_class: Optional[str] = None,
- conn_attrs: Optional[Dict[str, str]] = None,
- is_change_user_request: bool = False,
- ssl_enabled: bool = False,
- plugin_config: Optional[Dict[str, Any]] = None,
- ) -> Tuple[bytes, MySQLAuthPlugin]:
+ handshake ,
+ username ,
+ password ,
+ database = None,
+ charset = DEFAULT_CHARSET_ID,
+ client_flags = 0,
+ max_allowed_packet = DEFAULT_MAX_ALLOWED_PACKET,
+ auth_plugin = None,
+ auth_plugin_class = None,
+ conn_attrs = None,
+ is_change_user_request = False,
+ ssl_enabled = False,
+ plugin_config = None,
+ ) :
"""Make a MySQL Authentication packet.
Args:
@@ -402,10 +401,10 @@ class MySQLProtocol:
@staticmethod
def make_auth_ssl(
- charset: int = DEFAULT_CHARSET_ID,
- client_flags: int = 0,
- max_allowed_packet: int = DEFAULT_MAX_ALLOWED_PACKET,
- ) -> bytes:
+ charset = DEFAULT_CHARSET_ID,
+ client_flags = 0,
+ max_allowed_packet = DEFAULT_MAX_ALLOWED_PACKET,
+ ) :
"""Make a SSL authentication packet (see [1]).
Args:
@@ -434,18 +433,18 @@ class MySQLProtocol:
)
@staticmethod
- def make_command(command: int, argument: Optional[bytes] = None) -> bytes:
+ def make_command(command , argument = None) :
"""Make a MySQL packet containing a command"""
data = utils.int1store(command)
return data if argument is None else data + argument
@staticmethod
- def make_stmt_fetch(statement_id: int, rows: int = 1) -> bytes:
+ def make_stmt_fetch(statement_id , rows = 1) :
"""Make a MySQL packet with Fetch Statement command"""
return utils.int4store(statement_id) + utils.int4store(rows)
@staticmethod
- def parse_handshake(packet: bytes) -> HandShakeType:
+ def parse_handshake(packet ) :
"""Parse a MySQL Handshake-packet."""
res = {}
res["protocol"] = struct.unpack("<xxxxB", packet[0:5])[0]
@@ -497,7 +496,7 @@ class MySQLProtocol:
return res
@staticmethod
- def parse_ok(packet: bytes) -> OkPacketType:
+ def parse_ok(packet ) :
"""Parse a MySQL OK-packet"""
if not packet[4] == 0:
raise InterfaceError("Failed parsing OK packet (invalid).")
@@ -520,7 +519,7 @@ class MySQLProtocol:
return ok_packet
@staticmethod
- def parse_column_count(packet: bytes) -> Optional[int]:
+ def parse_column_count(packet ) :
"""Parse a MySQL packet with the number of columns in result set"""
try:
count = utils.read_lc_int(packet[4:])[1]
@@ -529,7 +528,7 @@ class MySQLProtocol:
raise InterfaceError("Failed parsing column count") from err
@staticmethod
- def parse_column(packet: bytes, encoding: str = "utf-8") -> DescriptionType:
+ def parse_column(packet , encoding = "utf-8") :
"""Parse a MySQL column-packet."""
packet, _ = utils.read_lc_string(packet[4:]) # catalog
packet, _ = utils.read_lc_string(packet) # db
@@ -561,7 +560,7 @@ class MySQLProtocol:
charset,
)
- def parse_eof(self, packet: bytes) -> EofPacketType:
+ def parse_eof(self, packet ) :
"""Parse a MySQL EOF-packet"""
if packet[4] == 0:
# EOF packet deprecation
@@ -582,13 +581,13 @@ class MySQLProtocol:
return res
@staticmethod
- def parse_statistics(packet: bytes, with_header: bool = True) -> StatsPacketType:
+ def parse_statistics(packet , with_header = True) :
"""Parse the statistics packet"""
errmsg = "Failed getting COM_STATISTICS information"
- res: Dict[str, Union[int, Decimal]] = {}
+ res = {}
# Information is separated by 2 spaces
pairs = [b""]
- lbl: StrOrBytes = b""
+ lbl = b""
if with_header:
pairs = packet[4:].split(b"\x20\x20")
else:
@@ -611,11 +610,8 @@ class MySQLProtocol:
return res
def read_text_result(
- self, sock: MySQLSocket, version: Tuple[int, ...], count: int = 1
- ) -> Tuple[
- List[Tuple[Optional[bytes], ...]],
- Optional[EofPacketType],
- ]:
+ self, sock , version , count = 1
+ ) :
"""Read MySQL text result
Reads all or given number of rows from the socket.
@@ -656,8 +652,8 @@ class MySQLProtocol:
@staticmethod
def _parse_binary_integer(
- packet: bytes, field: DescriptionType
- ) -> Tuple[bytes, int]:
+ packet , field
+ ) :
"""Parse an integer from a binary packet"""
if field[1] == FieldType.TINY:
format_ = "<b"
@@ -682,8 +678,8 @@ class MySQLProtocol:
@staticmethod
def _parse_binary_float(
- packet: bytes, field: DescriptionType
- ) -> Tuple[bytes, float]:
+ packet , field
+ ) :
"""Parse a float/double from a binary packet"""
if field[1] == FieldType.DOUBLE:
length = 8
@@ -696,20 +692,20 @@ class MySQLProtocol:
@staticmethod
def _parse_binary_new_decimal(
- packet: bytes, charset: str = "utf8"
- ) -> Tuple[bytes, Decimal]:
+ packet , charset = "utf8"
+ ) :
"""Parse a New Decimal from a binary packet"""
(packet, value) = utils.read_lc_string(packet)
return (packet, Decimal(value.decode(charset)))
@staticmethod
def _parse_binary_timestamp(
- packet: bytes,
- field_type: int,
- ) -> Tuple[bytes, Optional[Union[datetime.date, datetime.datetime]]]:
+ packet ,
+ field_type ,
+ ) :
"""Parse a timestamp from a binary packet"""
length = packet[0]
- value: Optional[Union[datetime.datetime, datetime.date]] = None
+ value = None
if length == 4:
year = struct.unpack("<H", packet[1:3])[0]
month = packet[3]
@@ -735,7 +731,7 @@ class MySQLProtocol:
return (packet[length + 1 :], value)
@staticmethod
- def _parse_binary_time(packet: bytes) -> Tuple[bytes, datetime.timedelta]:
+ def _parse_binary_time(packet ) :
"""Parse a time value from a binary packet"""
length = packet[0]
if not length:
@@ -759,17 +755,17 @@ class MySQLProtocol:
def _parse_binary_values(
self,
- fields: List[DescriptionType],
- packet: bytes,
- charset: str = "utf-8",
- ) -> Tuple[BinaryProtocolType, ...]:
+ fields ,
+ packet ,
+ charset = "utf-8",
+ ) :
"""Parse values from a binary result packet"""
null_bitmap_length = (len(fields) + 7 + 2) // 8
null_bitmap = [int(i) for i in packet[0:null_bitmap_length]]
packet = packet[null_bitmap_length:]
- values: List[Any] = []
- value: BinaryProtocolType = None
+ values = []
+ value = None
for pos, field in enumerate(fields):
if null_bitmap[int((pos + 2) / 8)] & (1 << (pos + 2) % 8):
values.append(None)
@@ -817,14 +813,11 @@ class MySQLProtocol:
def read_binary_result(
self,
- sock: MySQLSocket,
- columns: List[DescriptionType],
- count: int = 1,
- charset: str = "utf-8",
- ) -> Tuple[
- List[Tuple[BinaryProtocolType, ...]],
- Optional[EofPacketType],
- ]:
+ sock ,
+ columns ,
+ count = 1,
+ charset = "utf-8",
+ ) :
"""Read MySQL binary protocol result
Reads all or given number of binary resultset rows from the socket.
@@ -853,7 +846,7 @@ class MySQLProtocol:
return (rows, eof)
@staticmethod
- def parse_binary_prepare_ok(packet: bytes) -> Dict[str, int]:
+ def parse_binary_prepare_ok(packet ) :
"""Parse a MySQL Binary Protocol OK packet."""
if not packet[4] == 0:
raise InterfaceError("Failed parsing Binary OK packet")
@@ -871,7 +864,7 @@ class MySQLProtocol:
return ok_pkt
@staticmethod
- def prepare_binary_integer(value: int) -> Tuple[bytes, int, int]:
+ def prepare_binary_integer(value ) :
"""Prepare an integer for the MySQL binary protocol"""
field_type = None
flags = 0
@@ -906,8 +899,8 @@ class MySQLProtocol:
@staticmethod
def prepare_binary_timestamp(
- value: Union[datetime.date, datetime.datetime]
- ) -> Tuple[bytes, int]:
+ value
+ ) :
"""Prepare a timestamp object for the MySQL binary protocol
This method prepares a timestamp of type datetime.datetime or
@@ -949,8 +942,8 @@ class MySQLProtocol:
@staticmethod
def prepare_binary_time(
- value: Union[datetime.timedelta, datetime.time]
- ) -> Tuple[bytes, int]:
+ value
+ ) :
"""Prepare a time object for the MySQL binary protocol
This method prepares a time object of type datetime.timedelta or
@@ -968,7 +961,7 @@ class MySQLProtocol:
field_type = FieldType.TIME
negative = 0
mcs = None
- chunks: Deque[bytes] = deque([])
+ chunks = deque([])
if isinstance(value, datetime.timedelta):
if value.days < 0:
@@ -1004,7 +997,7 @@ class MySQLProtocol:
return utils.int1store(len(packed)) + packed, field_type
@staticmethod
- def prepare_stmt_send_long_data(statement: int, param: int, data: bytes) -> bytes:
+ def prepare_stmt_send_long_data(statement , param , data ) :
"""Prepare long data for prepared statements
Returns a string.
@@ -1013,23 +1006,23 @@ class MySQLProtocol:
def make_stmt_execute(
self,
- statement_id: int,
- data: Sequence[BinaryProtocolType] = (),
- parameters: Sequence = (),
- flags: int = 0,
- long_data_used: Optional[Dict[int, Tuple[bool]]] = None,
- charset: str = "utf8",
- query_attrs: Optional[List[Tuple[str, BinaryProtocolType]]] = None,
- converter_str_fallback: bool = False,
- ) -> bytes:
+ statement_id ,
+ data = (),
+ parameters = (),
+ flags = 0,
+ long_data_used = None,
+ charset = "utf8",
+ query_attrs = None,
+ converter_str_fallback = False,
+ ) :
"""Make a MySQL packet with the Statement Execute command"""
iteration_count = 1
null_bitmap = [0] * ((len(data) + 7) // 8)
- values: List[bytes] = []
- types: List[bytes] = []
+ values = []
+ types = []
packed = b""
data_len = len(data)
- query_attr_names: List[bytes] = []
+ query_attr_names = []
flags = flags if not query_attrs else flags + PARAMETER_COUNT_AVAILABLE
if charset == "utf8mb4":
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/protobuf/__init__.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/protobuf/__init__.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/protobuf/__init__.py
@@ -32,13 +32,12 @@
# pylint: disable=c-extension-no-member, no-member
-from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple, Type, Union
from ..types import MessageType, ProtobufMessageCextType, ProtobufMessageType
-_SERVER_MESSAGES_TUPLES: Tuple[Tuple[str, str], ...] = (
+_SERVER_MESSAGES_TUPLES = (
("Mysqlx.ServerMessages.Type.OK", "Mysqlx.Ok"),
("Mysqlx.ServerMessages.Type.ERROR", "Mysqlx.Error"),
(
@@ -85,14 +84,8 @@ _SERVER_MESSAGES_TUPLES: Tuple[Tuple[str
),
)
-PROTOBUF_VERSION: Optional[str] = None
-PROTOBUF_REPEATED_TYPES: List[
- Union[
- Type[List[Dict[str, Any]]],
- Type[RepeatedCompositeContainer],
- Type[RepeatedCompositeFieldContainer],
- ]
-] = [list]
+PROTOBUF_VERSION = None
+PROTOBUF_REPEATED_TYPES = [list]
try:
import _mysqlxpb
@@ -144,7 +137,7 @@ try:
)
# Dictionary with all messages descriptors
- _MESSAGES: Dict[str, int] = {}
+ _MESSAGES = {}
# Mysqlx
for key, val in mysqlx_pb2.ClientMessages.Type.items():
@@ -273,10 +266,10 @@ try:
"""This class implements the methods in pure Python used by the
_mysqlxpb C++ extension."""
- factory: message_factory.MessageFactory = message_factory.MessageFactory()
+ factory = message_factory.MessageFactory()
@staticmethod
- def new_message(name: str) -> ProtobufMessageType:
+ def new_message(name ) :
"""Create new Protobuf message.
Args:
@@ -291,7 +284,7 @@ try:
return cls()
@staticmethod
- def enum_value(enum_key: str) -> int:
+ def enum_value(enum_key ) :
"""Return enum value.
Args:
@@ -303,7 +296,7 @@ try:
return _MESSAGES[enum_key]
@staticmethod
- def serialize_message(msg: ProtobufMessageType) -> bytes:
+ def serialize_message(msg ) :
"""Serialize message.
Args:
@@ -315,7 +308,7 @@ try:
return msg.SerializeToString()
@staticmethod
- def serialize_partial_message(msg: ProtobufMessageType) -> bytes:
+ def serialize_partial_message(msg ) :
"""Serialize partial message.
Args:
@@ -327,7 +320,7 @@ try:
return msg.SerializePartialToString()
@staticmethod
- def parse_message(msg_type_name: str, payload: bytes) -> ProtobufMessageType:
+ def parse_message(msg_type_name , payload ) :
"""Serialize partial message.
Args:
@@ -342,7 +335,7 @@ try:
return msg
@staticmethod
- def parse_server_message(msg_type: int, payload: bytes) -> ProtobufMessageType:
+ def parse_server_message(msg_type , payload ) :
"""Parse server message message.
Args:
@@ -367,7 +360,7 @@ except (ImportError, SyntaxError, TypeEr
if not HAVE_MYSQLXPB_CEXT:
raise ImportError(f"Protobuf is not available: {HAVE_PROTOBUF_ERROR}") from err
-CRUD_PREPARE_MAPPING: Dict[str, Tuple[str, str]] = {
+CRUD_PREPARE_MAPPING = {
"Mysqlx.ClientMessages.Type.CRUD_FIND": (
"Mysqlx.Prepare.Prepare.OneOfMessage.Type.FIND",
"find",
@@ -399,10 +392,10 @@ class Protobuf:
"""
mysqlxpb = _mysqlxpb if HAVE_MYSQLXPB_CEXT else _mysqlxpb_pure
- use_pure: bool = not HAVE_MYSQLXPB_CEXT
+ use_pure = not HAVE_MYSQLXPB_CEXT
@staticmethod
- def set_use_pure(use_pure: bool) -> None:
+ def set_use_pure(use_pure ) :
"""Sets whether to use the C extension or pure Python implementation.
Args:
@@ -424,7 +417,7 @@ class Message:
**kwargs: Arbitrary keyword arguments with values for the message.
"""
- def __init__(self, msg_type_name: Optional[str] = None, **kwargs: Any) -> None:
+ def __init__(self, msg_type_name = None, **kwargs ) :
# _msg is a protobuf message instance when use_pure=True,
# else is a dictionary instance.
self.__dict__["_msg"] = (
@@ -433,7 +426,7 @@ class Message:
for name, value in kwargs.items():
self.__setattr__(name, value)
- def __setattr__(self, name: str, value: Any) -> None:
+ def __setattr__(self, name , value ) :
if Protobuf.use_pure:
if isinstance(value, str):
setattr(self._msg, name, encode_to_bytes(value))
@@ -453,7 +446,7 @@ class Message:
value.get_message() if isinstance(value, Message) else value
)
- def __getattr__(self, name: str) -> Any:
+ def __getattr__(self, name ) :
try:
return (
self._msg[name] if not Protobuf.use_pure else getattr(self._msg, name)
@@ -461,13 +454,13 @@ class Message:
except KeyError:
raise AttributeError from None
- def __setitem__(self, name: str, value: Any) -> None:
+ def __setitem__(self, name , value ) :
self.__setattr__(name, value)
- def __getitem__(self, name: str) -> Any:
+ def __getitem__(self, name ) :
return self.__getattr__(name)
- def get(self, name: str, default: Any = None) -> Any:
+ def get(self, name , default = None) :
"""Returns the value of an element of the message dictionary.
Args:
@@ -484,8 +477,8 @@ class Message:
)
def set_message(
- self, msg: Union[ProtobufMessageType, ProtobufMessageCextType]
- ) -> None:
+ self, msg
+ ) :
"""Sets the message.
Args:
@@ -493,7 +486,7 @@ class Message:
"""
self.__dict__["_msg"] = msg
- def get_message(self) -> Union[ProtobufMessageType, ProtobufMessageCextType]:
+ def get_message(self) :
"""Returns the dictionary representing a message containing parsed
data.
@@ -502,7 +495,7 @@ class Message:
"""
return self.__dict__["_msg"]
- def serialize_to_string(self) -> bytes:
+ def serialize_to_string(self) :
"""Serializes a message to a string.
Returns:
@@ -510,7 +503,7 @@ class Message:
"""
return Protobuf.mysqlxpb.serialize_message(self._msg)
- def serialize_partial_to_string(self) -> bytes:
+ def serialize_partial_to_string(self) :
"""Serializes the protocol message to a binary string.
This method is similar to serialize_to_string but doesn't check if the
@@ -522,7 +515,7 @@ class Message:
return Protobuf.mysqlxpb.serialize_partial_message(self._msg)
@property
- def type(self) -> str:
+ def type(self) :
"""string: Message type name."""
return (
self._msg["_mysqlxpb_type_name"]
@@ -532,8 +525,8 @@ class Message:
@staticmethod
def parse(
- msg_type_name: str, payload: bytes
- ) -> Union[ProtobufMessageType, ProtobufMessageCextType]:
+ msg_type_name , payload
+ ) :
"""Creates a new message, initialized with parsed data.
Args:
@@ -548,7 +541,7 @@ class Message:
return Protobuf.mysqlxpb.parse_message(msg_type_name, payload)
@staticmethod
- def byte_size(msg: MessageType) -> int:
+ def byte_size(msg ) :
"""Returns the size of the message in bytes.
Args:
@@ -567,8 +560,8 @@ class Message:
@staticmethod
def parse_from_server(
- msg_type: int, payload: bytes
- ) -> Union[ProtobufMessageType, ProtobufMessageCextType]:
+ msg_type , payload
+ ) :
"""Creates a new server-side message, initialized with parsed data.
Args:
@@ -581,7 +574,7 @@ class Message:
return Protobuf.mysqlxpb.parse_server_message(msg_type, payload)
@classmethod
- def from_message(cls, msg_type_name: str, payload: bytes) -> MessageType:
+ def from_message(cls, msg_type_name , payload ) :
"""Creates a new message, initialized with parsed data and returns a
:class:`mysqlx.protobuf.Message` object.
@@ -598,7 +591,7 @@ class Message:
return msg
@classmethod
- def from_server_message(cls, msg_type: int, payload: bytes) -> MessageType:
+ def from_server_message(cls, msg_type , payload ) :
"""Creates a new server-side message, initialized with parsed data and
returns a :class:`mysqlx.protobuf.Message` object.
@@ -615,7 +608,7 @@ class Message:
return msg
-def mysqlxpb_enum(name: str) -> int:
+def mysqlxpb_enum(name ) :
"""Returns the value of a MySQL X Protobuf enumerator.
Args:
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/statement.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/statement.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/statement.py
@@ -30,7 +30,6 @@
"""Implementation of Statements."""
-from __future__ import annotations
import copy
import json
@@ -60,18 +59,18 @@ ERR_INVALID_INDEX_NAME = 'The given inde
class Expr:
"""Expression wrapper."""
- def __init__(self, expr: Any) -> None:
- self.expr: Any = expr
+ def __init__(self, expr ) :
+ self.expr = expr
-def flexible_params(*values: Any) -> Union[List, Tuple]:
+def flexible_params(*values ) :
"""Parse flexible parameters."""
if len(values) == 1 and isinstance(values[0], (list, tuple)):
return values[0]
return values
-def is_quoted_identifier(identifier: str, sql_mode: str = "") -> bool:
+def is_quoted_identifier(identifier , sql_mode = "") :
"""Check if the given identifier is quoted.
Args:
@@ -88,7 +87,7 @@ def is_quoted_identifier(identifier: str
return identifier[0] == "`" and identifier[-1] == "`"
-def quote_identifier(identifier: str, sql_mode: str = "") -> str:
+def quote_identifier(identifier , sql_mode = "") :
"""Quote the given identifier with backticks, converting backticks (`) in
the identifier name with the correct escape sequence (``).
@@ -108,7 +107,7 @@ def quote_identifier(identifier: str, sq
return f"`{quoted}`"
-def quote_multipart_identifier(identifiers: Iterable[str], sql_mode: str = "") -> str:
+def quote_multipart_identifier(identifiers , sql_mode = "") :
"""Quote the given multi-part identifier with backticks.
Args:
@@ -124,8 +123,8 @@ def quote_multipart_identifier(identifie
def parse_table_name(
- default_schema: str, table_name: str, sql_mode: str = ""
-) -> Tuple[str, str]:
+ default_schema , table_name , sql_mode = ""
+) :
"""Parse table name.
Args:
@@ -154,30 +153,30 @@ class Statement:
doc_based (bool): `True` if it is document based.
"""
- def __init__(self, target: DatabaseTargetType, doc_based: bool = True) -> None:
- self._target: DatabaseTargetType = target
- self._doc_based: bool = doc_based
- self._connection: Optional[ConnectionType] = (
+ def __init__(self, target , doc_based = True) :
+ self._target = target
+ self._doc_based = doc_based
+ self._connection = (
target.get_connection() if target else None
)
- self._stmt_id: Optional[int] = None
- self._exec_counter: int = 0
- self._changed: bool = True
- self._prepared: bool = False
- self._deallocate_prepare_execute: bool = False
+ self._stmt_id = None
+ self._exec_counter = 0
+ self._changed = True
+ self._prepared = False
+ self._deallocate_prepare_execute = False
@property
- def target(self) -> DatabaseTargetType:
+ def target(self) :
"""object: The database object target."""
return self._target
@property
- def schema(self) -> SchemaType:
+ def schema(self) :
""":class:`mysqlx.Schema`: The Schema object."""
return self._target.schema
@property
- def stmt_id(self) -> int:
+ def stmt_id(self) :
"""Returns this statement ID.
Returns:
@@ -186,47 +185,47 @@ class Statement:
return self._stmt_id
@stmt_id.setter
- def stmt_id(self, value: int) -> None:
+ def stmt_id(self, value ) :
self._stmt_id = value
@property
- def exec_counter(self) -> int:
+ def exec_counter(self) :
"""int: The number of times this statement was executed."""
return self._exec_counter
@property
- def changed(self) -> bool:
+ def changed(self) :
"""bool: `True` if this statement has changes."""
return self._changed
@changed.setter
- def changed(self, value: bool) -> None:
+ def changed(self, value ) :
self._changed = value
@property
- def prepared(self) -> bool:
+ def prepared(self) :
"""bool: `True` if this statement has been prepared."""
return self._prepared
@prepared.setter
- def prepared(self, value: bool) -> None:
+ def prepared(self, value ) :
self._prepared = value
@property
- def repeated(self) -> bool:
+ def repeated(self) :
"""bool: `True` if this statement was executed more than once."""
return self._exec_counter > 1
@property
- def deallocate_prepare_execute(self) -> bool:
+ def deallocate_prepare_execute(self) :
"""bool: `True` to deallocate + prepare + execute statement."""
return self._deallocate_prepare_execute
@deallocate_prepare_execute.setter
- def deallocate_prepare_execute(self, value: bool) -> None:
+ def deallocate_prepare_execute(self, value ) :
self._deallocate_prepare_execute = value
- def is_doc_based(self) -> bool:
+ def is_doc_based(self) :
"""Check if it is document based.
Returns:
@@ -234,15 +233,15 @@ class Statement:
"""
return self._doc_based
- def increment_exec_counter(self) -> None:
+ def increment_exec_counter(self) :
"""Increments the number of times this statement has been executed."""
self._exec_counter += 1
- def reset_exec_counter(self) -> None:
+ def reset_exec_counter(self) :
"""Resets the number of times this statement has been executed."""
self._exec_counter = 0
- def execute(self) -> Any:
+ def execute(self) :
"""Execute the statement.
Raises:
@@ -265,41 +264,35 @@ class FilterableStatement(Statement):
def __init__(
self,
- target: DatabaseTargetType,
- doc_based: bool = True,
- condition: Optional[str] = None,
- ) -> None:
+ target ,
+ doc_based = True,
+ condition = None,
+ ) :
super().__init__(target=target, doc_based=doc_based)
- self._binding_map: Dict[str, Any] = {}
- self._bindings: Union[Dict[str, Any], List] = {}
- self._having: Optional[MessageType] = None
- self._grouping_str: str = ""
- self._grouping: Optional[
- List[Union[ProtobufMessageType, ProtobufMessageCextType]]
- ] = None
- self._limit_offset: int = 0
- self._limit_row_count: int = None
- self._projection_str: str = ""
- self._projection_expr: Optional[
- List[Union[ProtobufMessageType, ProtobufMessageCextType]]
- ] = None
- self._sort_str: str = ""
- self._sort_expr: Optional[
- List[Union[ProtobufMessageType, ProtobufMessageCextType]]
- ] = None
- self._where_str: str = ""
- self._where_expr: MessageType = None
- self.has_bindings: bool = False
- self.has_limit: bool = False
- self.has_group_by: bool = False
- self.has_having: bool = False
- self.has_projection: bool = False
- self.has_sort: bool = False
- self.has_where: bool = False
+ self._binding_map = {}
+ self._bindings = {}
+ self._having = None
+ self._grouping_str = ""
+ self._grouping = None
+ self._limit_offset = 0
+ self._limit_row_count = None
+ self._projection_str = ""
+ self._projection_expr = None
+ self._sort_str = ""
+ self._sort_expr = None
+ self._where_str = ""
+ self._where_expr = None
+ self.has_bindings = False
+ self.has_limit = False
+ self.has_group_by = False
+ self.has_having = False
+ self.has_projection = False
+ self.has_sort = False
+ self.has_where = False
if condition:
self._set_where(condition)
- def _bind_single(self, obj: Union[DbDoc, Dict[str, Any], str]) -> None:
+ def _bind_single(self, obj ) :
"""Bind single object.
Args:
@@ -325,7 +318,7 @@ class FilterableStatement(Statement):
else:
raise ProgrammingError("Invalid JSON string or object to bind")
- def _sort(self, *clauses: str) -> FilterableStatement:
+ def _sort(self, *clauses ) :
"""Sets the sorting criteria.
Args:
@@ -342,7 +335,7 @@ class FilterableStatement(Statement):
self._changed = True
return self
- def _set_where(self, condition: str) -> FilterableStatement:
+ def _set_where(self, condition ) :
"""Sets the search condition to filter.
Args:
@@ -363,7 +356,7 @@ class FilterableStatement(Statement):
self._changed = True
return self
- def _set_group_by(self, *fields: str) -> None:
+ def _set_group_by(self, *fields ) :
"""Set group by.
Args:
@@ -377,7 +370,7 @@ class FilterableStatement(Statement):
).parse_expr_list()
self._changed = True
- def _set_having(self, condition: str) -> None:
+ def _set_having(self, condition ) :
"""Set having.
Args:
@@ -387,7 +380,7 @@ class FilterableStatement(Statement):
self._having = ExprParser(condition, not self._doc_based).expr()
self._changed = True
- def _set_projection(self, *fields: str) -> FilterableStatement:
+ def _set_projection(self, *fields ) :
"""Set the projection.
Args:
@@ -405,7 +398,7 @@ class FilterableStatement(Statement):
self._changed = True
return self
- def get_binding_map(self) -> Dict[str, Any]:
+ def get_binding_map(self) :
"""Returns the binding map dictionary.
Returns:
@@ -413,7 +406,7 @@ class FilterableStatement(Statement):
"""
return self._binding_map
- def get_bindings(self) -> Union[Dict[str, Any], List]:
+ def get_bindings(self) :
"""Returns the bindings list.
Returns:
@@ -421,7 +414,7 @@ class FilterableStatement(Statement):
"""
return self._bindings
- def get_grouping(self) -> List[Union[ProtobufMessageType, ProtobufMessageCextType]]:
+ def get_grouping(self) :
"""Returns the grouping expression list.
Returns:
@@ -429,7 +422,7 @@ class FilterableStatement(Statement):
"""
return self._grouping
- def get_having(self) -> MessageType:
+ def get_having(self) :
"""Returns the having expression.
Returns:
@@ -437,7 +430,7 @@ class FilterableStatement(Statement):
"""
return self._having
- def get_limit_row_count(self) -> int:
+ def get_limit_row_count(self) :
"""Returns the limit row count.
Returns:
@@ -445,7 +438,7 @@ class FilterableStatement(Statement):
"""
return self._limit_row_count
- def get_limit_offset(self) -> int:
+ def get_limit_offset(self) :
"""Returns the limit offset.
Returns:
@@ -453,7 +446,7 @@ class FilterableStatement(Statement):
"""
return self._limit_offset
- def get_where_expr(self) -> MessageType:
+ def get_where_expr(self) :
"""Returns the where expression.
Returns:
@@ -463,7 +456,7 @@ class FilterableStatement(Statement):
def get_projection_expr(
self,
- ) -> List[Union[ProtobufMessageType, ProtobufMessageCextType]]:
+ ) :
"""Returns the projection expression.
Returns:
@@ -473,7 +466,7 @@ class FilterableStatement(Statement):
def get_sort_expr(
self,
- ) -> List[Union[ProtobufMessageType, ProtobufMessageCextType]]:
+ ) :
"""Returns the sort expression.
Returns:
@@ -482,7 +475,7 @@ class FilterableStatement(Statement):
return self._sort_expr
@deprecated("8.0.12")
- def where(self, condition: str) -> FilterableStatement:
+ def where(self, condition ) :
"""Sets the search condition to filter.
Args:
@@ -497,7 +490,7 @@ class FilterableStatement(Statement):
return self._set_where(condition)
@deprecated("8.0.12")
- def sort(self, *clauses: str) -> FilterableStatement:
+ def sort(self, *clauses ) :
"""Sets the sorting criteria.
Args:
@@ -511,8 +504,8 @@ class FilterableStatement(Statement):
return self._sort(*clauses)
def limit(
- self, row_count: int, offset: Optional[int] = None
- ) -> FilterableStatement:
+ self, row_count , offset = None
+ ) :
"""Sets the maximum number of items to be returned.
Args:
@@ -545,7 +538,7 @@ class FilterableStatement(Statement):
)
return self
- def offset(self, offset: int) -> FilterableStatement:
+ def offset(self, offset ) :
"""Sets the number of items to skip.
Args:
@@ -564,7 +557,7 @@ class FilterableStatement(Statement):
self._limit_offset = offset
return self
- def bind(self, *args: Any) -> FilterableStatement:
+ def bind(self, *args ) :
"""Binds value(s) to a specific placeholder(s).
Args:
@@ -588,7 +581,7 @@ class FilterableStatement(Statement):
raise ProgrammingError("Invalid number of arguments to bind")
return self
- def execute(self) -> Any:
+ def execute(self) :
"""Execute the statement.
Raises:
@@ -605,21 +598,21 @@ class SqlStatement(Statement):
sql (string): The sql statement to be executed.
"""
- def __init__(self, connection: ConnectionType, sql: str) -> None:
+ def __init__(self, connection , sql ) :
super().__init__(target=None, doc_based=False)
- self._connection: ConnectionType = connection
- self._sql: str = sql
- self._binding_map: Optional[Dict[str, Any]] = None
- self._bindings: Union[List, Tuple] = []
- self.has_bindings: bool = False
- self.has_limit: bool = False
+ self._connection = connection
+ self._sql = sql
+ self._binding_map = None
+ self._bindings = []
+ self.has_bindings = False
+ self.has_limit = False
@property
- def sql(self) -> str:
+ def sql(self) :
"""string: The SQL text statement."""
return self._sql
- def get_binding_map(self) -> Dict[str, Any]:
+ def get_binding_map(self) :
"""Returns the binding map dictionary.
Returns:
@@ -627,7 +620,7 @@ class SqlStatement(Statement):
"""
return self._binding_map
- def get_bindings(self) -> Union[Tuple, List]:
+ def get_bindings(self) :
"""Returns the bindings list.
Returns:
@@ -635,7 +628,7 @@ class SqlStatement(Statement):
"""
return self._bindings
- def bind(self, *args: Any) -> SqlStatement:
+ def bind(self, *args ) :
"""Binds value(s) to a specific placeholder(s).
Args:
@@ -654,7 +647,7 @@ class SqlStatement(Statement):
self._bindings.append(bindings)
return self
- def execute(self) -> SqlResult:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -666,29 +659,13 @@ class SqlStatement(Statement):
class WriteStatement(Statement):
"""Provide common write operation attributes."""
- def __init__(self, target: DatabaseTargetType, doc_based: bool) -> None:
+ def __init__(self, target , doc_based ) :
super().__init__(target, doc_based)
- self._values: List[
- Union[
- int,
- str,
- DbDoc,
- Dict[str, Any],
- List[Optional[Union[str, int, float, ExprParser, Dict[str, Any]]]],
- ]
- ] = []
+ self._values = []
def get_values(
self,
- ) -> List[
- Union[
- int,
- str,
- DbDoc,
- Dict[str, Any],
- List[Optional[Union[str, int, float, ExprParser, Dict[str, Any]]]],
- ]
- ]:
+ ) :
"""Returns the list of values.
Returns:
@@ -696,7 +673,7 @@ class WriteStatement(Statement):
"""
return self._values
- def execute(self) -> Any:
+ def execute(self) :
"""Execute the statement.
Raises:
@@ -712,12 +689,12 @@ class AddStatement(WriteStatement):
collection (mysqlx.Collection): The Collection object.
"""
- def __init__(self, collection: DatabaseTargetType) -> None:
+ def __init__(self, collection ) :
super().__init__(collection, True)
- self._upsert: bool = False
- self.ids: List = []
+ self._upsert = False
+ self.ids = []
- def is_upsert(self) -> bool:
+ def is_upsert(self) :
"""Returns `True` if it's an upsert.
Returns:
@@ -725,7 +702,7 @@ class AddStatement(WriteStatement):
"""
return self._upsert
- def upsert(self, value: bool = True) -> AddStatement:
+ def upsert(self, value = True) :
"""Sets the upset flag to the boolean of the value provided.
Setting of this flag allows updating of the matched rows/documents
with the provided value.
@@ -736,7 +713,7 @@ class AddStatement(WriteStatement):
self._upsert = value
return self
- def add(self, *values: DbDoc) -> AddStatement:
+ def add(self, *values ) :
"""Adds a list of documents into a collection.
Args:
@@ -752,7 +729,7 @@ class AddStatement(WriteStatement):
self._values.append(DbDoc(val))
return self
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -776,18 +753,18 @@ class UpdateSpec:
ProgrammingError: If `source` is invalid.
"""
- def __init__(self, update_type: int, source: str, value: Any = None) -> None:
+ def __init__(self, update_type , source , value = None) :
if update_type == mysqlxpb_enum("Mysqlx.Crud.UpdateOperation.UpdateType.SET"):
self._table_set(source, value)
else:
- self.update_type: int = update_type
+ self.update_type = update_type
try:
- self.source: Any = ExprParser(source, False).document_field().identifier
+ self.source = ExprParser(source, False).document_field().identifier
except ValueError as err:
raise ProgrammingError(f"{err}") from err
- self.value: Any = value
+ self.value = value
- def _table_set(self, source: str, value: Any) -> None:
+ def _table_set(self, source , value ) :
"""Table set.
Args:
@@ -811,11 +788,11 @@ class ModifyStatement(FilterableStatemen
The ``condition`` parameter is now mandatory.
"""
- def __init__(self, collection: DatabaseTargetType, condition: str) -> None:
+ def __init__(self, collection , condition ) :
super().__init__(target=collection, condition=condition)
- self._update_ops: Dict[str, Any] = {}
+ self._update_ops = {}
- def sort(self, *clauses: str) -> ModifyStatement:
+ def sort(self, *clauses ) :
"""Sets the sorting criteria.
Args:
@@ -826,7 +803,7 @@ class ModifyStatement(FilterableStatemen
"""
return self._sort(*clauses)
- def get_update_ops(self) -> Dict[str, Any]:
+ def get_update_ops(self) :
"""Returns the list of update operations.
Returns:
@@ -834,7 +811,7 @@ class ModifyStatement(FilterableStatemen
"""
return self._update_ops
- def set(self, doc_path: str, value: Any) -> ModifyStatement:
+ def set(self, doc_path , value ) :
"""Sets or updates attributes on documents in a collection.
Args:
@@ -853,7 +830,7 @@ class ModifyStatement(FilterableStatemen
return self
@deprecated("8.0.12")
- def change(self, doc_path: str, value: Any) -> ModifyStatement:
+ def change(self, doc_path , value ) :
"""Add an update to the statement setting the field, if it exists at
the document path, to the given value.
@@ -874,7 +851,7 @@ class ModifyStatement(FilterableStatemen
self._changed = True
return self
- def unset(self, *doc_paths: str) -> ModifyStatement:
+ def unset(self, *doc_paths ) :
"""Removes attributes from documents in a collection.
Args:
@@ -892,7 +869,7 @@ class ModifyStatement(FilterableStatemen
self._changed = True
return self
- def array_insert(self, field: str, value: Any) -> ModifyStatement:
+ def array_insert(self, field , value ) :
"""Insert a value into the specified array in documents of a
collection.
@@ -912,7 +889,7 @@ class ModifyStatement(FilterableStatemen
self._changed = True
return self
- def array_append(self, doc_path: str, value: Any) -> ModifyStatement:
+ def array_append(self, doc_path , value ) :
"""Inserts a value into a specific position in an array attribute in
documents of a collection.
@@ -933,7 +910,7 @@ class ModifyStatement(FilterableStatemen
self._changed = True
return self
- def patch(self, doc: Union[Dict, DbDoc, ExprParser, str]) -> ModifyStatement:
+ def patch(self, doc ) :
"""Takes a :class:`mysqlx.DbDoc`, string JSON format or a dict with the
changes and applies it on all matching documents.
@@ -959,7 +936,7 @@ class ModifyStatement(FilterableStatemen
self._changed = True
return self
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -987,21 +964,21 @@ class ReadStatement(FilterableStatement)
def __init__(
self,
- target: DatabaseTargetType,
- doc_based: bool = True,
- condition: Optional[str] = None,
- ) -> None:
+ target ,
+ doc_based = True,
+ condition = None,
+ ) :
super().__init__(target, doc_based, condition)
- self._lock_exclusive: bool = False
- self._lock_shared: bool = False
- self._lock_contention: LockContention = LockContention.DEFAULT
+ self._lock_exclusive = False
+ self._lock_shared = False
+ self._lock_contention = LockContention.DEFAULT
@property
- def lock_contention(self) -> LockContention:
+ def lock_contention(self) :
""":class:`mysqlx.LockContention`: The lock contention value."""
return self._lock_contention
- def _set_lock_contention(self, lock_contention: LockContention) -> None:
+ def _set_lock_contention(self, lock_contention ) :
"""Set the lock contention.
Args:
@@ -1019,7 +996,7 @@ class ReadStatement(FilterableStatement)
) from err
self._lock_contention = lock_contention
- def is_lock_exclusive(self) -> bool:
+ def is_lock_exclusive(self) :
"""Returns `True` if is `EXCLUSIVE LOCK`.
Returns:
@@ -1027,7 +1004,7 @@ class ReadStatement(FilterableStatement)
"""
return self._lock_exclusive
- def is_lock_shared(self) -> bool:
+ def is_lock_shared(self) :
"""Returns `True` if is `SHARED LOCK`.
Returns:
@@ -1036,8 +1013,8 @@ class ReadStatement(FilterableStatement)
return self._lock_shared
def lock_shared(
- self, lock_contention: LockContention = LockContention.DEFAULT
- ) -> ReadStatement:
+ self, lock_contention = LockContention.DEFAULT
+ ) :
"""Execute a read operation with `SHARED LOCK`. Only one lock can be
active at a time.
@@ -1050,8 +1027,8 @@ class ReadStatement(FilterableStatement)
return self
def lock_exclusive(
- self, lock_contention: LockContention = LockContention.DEFAULT
- ) -> ReadStatement:
+ self, lock_contention = LockContention.DEFAULT
+ ) :
"""Execute a read operation with `EXCLUSIVE LOCK`. Only one lock can be
active at a time.
@@ -1063,7 +1040,7 @@ class ReadStatement(FilterableStatement)
self._set_lock_contention(lock_contention)
return self
- def group_by(self, *fields: str) -> ReadStatement:
+ def group_by(self, *fields ) :
"""Sets a grouping criteria for the resultset.
Args:
@@ -1075,7 +1052,7 @@ class ReadStatement(FilterableStatement)
self._set_group_by(*fields)
return self
- def having(self, condition: str) -> ReadStatement:
+ def having(self, condition ) :
"""Sets a condition for records to be considered in agregate function
operations.
@@ -1089,7 +1066,7 @@ class ReadStatement(FilterableStatement)
self._set_having(condition)
return self
- def execute(self) -> Union[DocResult, RowResult]:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1110,11 +1087,11 @@ class FindStatement(ReadStatement):
"""
def __init__(
- self, collection: DatabaseTargetType, condition: Optional[str] = None
- ) -> None:
+ self, collection , condition = None
+ ) :
super().__init__(collection, True, condition)
- def fields(self, *fields: str) -> FindStatement:
+ def fields(self, *fields ) :
"""Sets a document field filter.
Args:
@@ -1126,7 +1103,7 @@ class FindStatement(ReadStatement):
"""
return self._set_projection(*fields)
- def sort(self, *clauses: str) -> FindStatement:
+ def sort(self, *clauses ) :
"""Sets the sorting criteria.
Args:
@@ -1146,11 +1123,11 @@ class SelectStatement(ReadStatement):
*fields: The fields to be retrieved.
"""
- def __init__(self, table: DatabaseTargetType, *fields: str) -> None:
+ def __init__(self, table , *fields ) :
super().__init__(table, False)
self._set_projection(*fields)
- def where(self, condition: str) -> SelectStatement:
+ def where(self, condition ) :
"""Sets the search condition to filter.
Args:
@@ -1161,7 +1138,7 @@ class SelectStatement(ReadStatement):
"""
return self._set_where(condition)
- def order_by(self, *clauses: str) -> SelectStatement:
+ def order_by(self, *clauses ) :
"""Sets the order by criteria.
Args:
@@ -1172,7 +1149,7 @@ class SelectStatement(ReadStatement):
"""
return self._sort(*clauses)
- def get_sql(self) -> str:
+ def get_sql(self) :
"""Returns the generated SQL.
Returns:
@@ -1203,11 +1180,11 @@ class InsertStatement(WriteStatement):
*fields: The fields to be inserted.
"""
- def __init__(self, table: DatabaseTargetType, *fields: Any) -> None:
+ def __init__(self, table , *fields ) :
super().__init__(table, False)
- self._fields: Union[List, Tuple] = flexible_params(*fields)
+ self._fields = flexible_params(*fields)
- def values(self, *values: Any) -> InsertStatement:
+ def values(self, *values ) :
"""Set the values to be inserted.
Args:
@@ -1219,7 +1196,7 @@ class InsertStatement(WriteStatement):
self._values.append(list(flexible_params(*values)))
return self
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1238,11 +1215,11 @@ class UpdateStatement(FilterableStatemen
The ``fields`` parameters were removed.
"""
- def __init__(self, table: DatabaseTargetType) -> None:
+ def __init__(self, table ) :
super().__init__(target=table, doc_based=False)
- self._update_ops: Dict[str, Any] = {}
+ self._update_ops = {}
- def where(self, condition: str) -> UpdateStatement:
+ def where(self, condition ) :
"""Sets the search condition to filter.
Args:
@@ -1253,7 +1230,7 @@ class UpdateStatement(FilterableStatemen
"""
return self._set_where(condition)
- def order_by(self, *clauses: str) -> UpdateStatement:
+ def order_by(self, *clauses ) :
"""Sets the order by criteria.
Args:
@@ -1264,7 +1241,7 @@ class UpdateStatement(FilterableStatemen
"""
return self._sort(*clauses)
- def get_update_ops(self) -> Dict[str, Any]:
+ def get_update_ops(self) :
"""Returns the list of update operations.
Returns:
@@ -1272,7 +1249,7 @@ class UpdateStatement(FilterableStatemen
"""
return self._update_ops
- def set(self, field: str, value: Any) -> UpdateStatement:
+ def set(self, field , value ) :
"""Updates the column value on records in a table.
Args:
@@ -1290,7 +1267,7 @@ class UpdateStatement(FilterableStatemen
self._changed = True
return self
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1316,10 +1293,10 @@ class RemoveStatement(FilterableStatemen
The ``condition`` parameter was added.
"""
- def __init__(self, collection: DatabaseTargetType, condition: str) -> None:
+ def __init__(self, collection , condition ) :
super().__init__(target=collection, condition=condition)
- def sort(self, *clauses: str) -> RemoveStatement:
+ def sort(self, *clauses ) :
"""Sets the sorting criteria.
Args:
@@ -1330,7 +1307,7 @@ class RemoveStatement(FilterableStatemen
"""
return self._sort(*clauses)
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1354,10 +1331,10 @@ class DeleteStatement(FilterableStatemen
The ``condition`` parameter was removed.
"""
- def __init__(self, table: DatabaseTargetType) -> None:
+ def __init__(self, table ) :
super().__init__(target=table, doc_based=False)
- def where(self, condition: str) -> DeleteStatement:
+ def where(self, condition ) :
"""Sets the search condition to filter.
Args:
@@ -1368,7 +1345,7 @@ class DeleteStatement(FilterableStatemen
"""
return self._set_where(condition)
- def order_by(self, *clauses: str) -> DeleteStatement:
+ def order_by(self, *clauses ) :
"""Sets the order by criteria.
Args:
@@ -1379,7 +1356,7 @@ class DeleteStatement(FilterableStatemen
"""
return self._sort(*clauses)
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1418,16 +1395,16 @@ class CreateCollectionIndexStatement(Sta
def __init__(
self,
- collection: DatabaseTargetType,
- index_name: str,
- index_desc: Dict[str, Any],
- ) -> None:
+ collection ,
+ index_name ,
+ index_desc ,
+ ) :
super().__init__(target=collection)
- self._index_desc: Dict[str, Any] = copy.deepcopy(index_desc)
- self._index_name: str = index_name
- self._fields_desc: List[Dict[str, Any]] = self._index_desc.pop("fields", [])
+ self._index_desc = copy.deepcopy(index_desc)
+ self._index_name = index_name
+ self._fields_desc = self._index_desc.pop("fields", [])
- def execute(self) -> Result:
+ def execute(self) :
"""Execute the statement.
Returns:
@@ -1465,7 +1442,7 @@ class CreateCollectionIndexStatement(Sta
if not isinstance(self._fields_desc, list):
raise ProgrammingError("Required member 'fields' must contain a list")
- args: Dict[str, Any] = {}
+ args = {}
args["name"] = self._index_name
args["collection"] = self._target.name
args["schema"] = self._target.schema.name
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/aio/abstracts.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/aio/abstracts.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/aio/abstracts.py
@@ -31,7 +31,6 @@
"""Module gathering all abstract base classes."""
-from __future__ import annotations
__all__ = ["MySQLConnectionAbstract", "MySQLCursorAbstract", "ServerInfo"]
@@ -115,7 +114,7 @@ if TYPE_CHECKING:
IS_POSIX = os.name == "posix"
-NAMED_TUPLE_CACHE: weakref.WeakValueDictionary[Any, Any] = weakref.WeakValueDictionary()
+NAMED_TUPLE_CACHE = weakref.WeakValueDictionary()
@dataclass
@@ -125,18 +124,18 @@ class ServerInfo:
Also parses and validates the server version, storing it as a tuple.
"""
- protocol: int
- version: str
- version_tuple: Tuple[int, ...] = field(init=False)
- thread_id: int
- charset: int
- status_flags: int
- auth_plugin: str
- auth_data: bytes
- capabilities: int
- query_attrs_is_supported: bool = False
+ #protocol: int
+ #version: str
+ version_tuple = field(init=False)
+ #thread_id: int
+ #charset: int
+ #status_flags: int
+ #auth_plugin: str
+ #auth_data: bytes
+ #capabilities: int
+ query_attrs_is_supported = False
- def __post_init__(self) -> None:
+ def __post_init__(self) :
"""Parse and validate server version.
Raises:
@@ -159,144 +158,144 @@ class MySQLConnectionAbstract(ABC):
def __init__(
self,
*,
- user: Optional[str] = None,
- password: str = "",
- host: str = "127.0.0.1",
- port: int = 3306,
- database: Optional[str] = None,
- password1: str = "",
- password2: str = "",
- password3: str = "",
- charset: str = "",
- collation: str = "",
- auth_plugin: Optional[str] = None,
- client_flags: Optional[int] = None,
- compress: bool = False,
- consume_results: bool = False,
- autocommit: bool = False,
- time_zone: Optional[str] = None,
- conn_attrs: Dict[str, str] = {},
- sql_mode: Optional[str] = None,
- init_command: Optional[str] = None,
- get_warnings: bool = False,
- raise_on_warnings: bool = False,
- buffered: bool = False,
- raw: bool = False,
- kerberos_auth_mode: Optional[str] = None,
- krb_service_principal: Optional[str] = None,
- openid_token_file: Optional[str] = None,
- webauthn_callback: Optional[Union[str, Callable[[str], None]]] = None,
- allow_local_infile: bool = DEFAULT_CONFIGURATION["allow_local_infile"],
- allow_local_infile_in_path: Optional[str] = DEFAULT_CONFIGURATION[
+ user = None,
+ password = "",
+ host = "127.0.0.1",
+ port = 3306,
+ database = None,
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ charset = "",
+ collation = "",
+ auth_plugin = None,
+ client_flags = None,
+ compress = False,
+ consume_results = False,
+ autocommit = False,
+ time_zone = None,
+ conn_attrs = {},
+ sql_mode = None,
+ init_command = None,
+ get_warnings = False,
+ raise_on_warnings = False,
+ buffered = False,
+ raw = False,
+ kerberos_auth_mode = None,
+ krb_service_principal = None,
+ openid_token_file = None,
+ webauthn_callback = None,
+ allow_local_infile = DEFAULT_CONFIGURATION["allow_local_infile"],
+ allow_local_infile_in_path = DEFAULT_CONFIGURATION[
"allow_local_infile_in_path"
],
- converter_class: Optional[MySQLConverter] = None,
- converter_str_fallback: bool = False,
- connection_timeout: int = DEFAULT_CONFIGURATION["connect_timeout"],
- unix_socket: Optional[str] = None,
- use_unicode: Optional[bool] = True,
- ssl_ca: Optional[str] = None,
- ssl_cert: Optional[str] = None,
- ssl_key: Optional[str] = None,
- ssl_verify_cert: Optional[bool] = False,
- ssl_verify_identity: Optional[bool] = False,
- ssl_disabled: Optional[bool] = DEFAULT_CONFIGURATION["ssl_disabled"],
- tls_versions: Optional[List[str]] = None,
- tls_ciphersuites: Optional[List[str]] = None,
- loop: Optional[asyncio.AbstractEventLoop] = None,
+ converter_class = None,
+ converter_str_fallback = False,
+ connection_timeout = DEFAULT_CONFIGURATION["connect_timeout"],
+ unix_socket = None,
+ use_unicode = True,
+ ssl_ca = None,
+ ssl_cert = None,
+ ssl_key = None,
+ ssl_verify_cert = False,
+ ssl_verify_identity = False,
+ ssl_disabled = DEFAULT_CONFIGURATION["ssl_disabled"],
+ tls_versions = None,
+ tls_ciphersuites = None,
+ loop = None,
):
# private (shouldn't be manipulated directly internally)
- self.__charset: Optional[Charset] = None
+ self.__charset = None
"""It shouldn't be manipulated directly, even internally. If you need
to manipulate the charset object, use the property `_charset` (read & write)
instead. Similarly, `_charset` shouldn't be manipulated externally.
"""
# protected (can be manipulated directly internally)
- self._user: str = user
- self._password: str = password
- self._host: str = host
- self._port: int = port
- self._database: str = database
- self._password1: str = password1
- self._password2: str = password2
- self._password3: str = password3
- self._unix_socket: str = unix_socket
- self._connection_timeout: int = connection_timeout
- self._connection_attrs: Dict[str, str] = conn_attrs
- self._compress: bool = compress
- self._consume_results: bool = consume_results
- self._autocommit: bool = autocommit
- self._time_zone: Optional[str] = time_zone
- self._sql_mode: Optional[str] = sql_mode
- self._init_command: Optional[str] = init_command
- self._protocol: MySQLProtocol = MySQLProtocol()
- self._socket: Optional[Union[MySQLTcpSocket, MySQLUnixSocket]] = None
- self._charset_name: Optional[str] = charset
+ self._user = user
+ self._password = password
+ self._host = host
+ self._port = port
+ self._database = database
+ self._password1 = password1
+ self._password2 = password2
+ self._password3 = password3
+ self._unix_socket = unix_socket
+ self._connection_timeout = connection_timeout
+ self._connection_attrs = conn_attrs
+ self._compress = compress
+ self._consume_results = consume_results
+ self._autocommit = autocommit
+ self._time_zone = time_zone
+ self._sql_mode = sql_mode
+ self._init_command = init_command
+ self._protocol = MySQLProtocol()
+ self._socket = None
+ self._charset_name = charset
"""Charset name provided by the user at connection time."""
- self._charset_collation: Optional[str] = collation
+ self._charset_collation = collation
"""Collation provided by the user at connection time."""
- self._ssl_active: bool = False
- self._ssl_disabled: bool = ssl_disabled
- self._ssl_ca: Optional[str] = ssl_ca
- self._ssl_cert: Optional[str] = ssl_cert
- self._ssl_key: Optional[str] = ssl_key
- self._ssl_verify_cert: Optional[bool] = ssl_verify_cert
- self._ssl_verify_identity: Optional[bool] = ssl_verify_identity
- self._tls_versions: Optional[List[str]] = tls_versions
- self._tls_ciphersuites: Optional[List[str]] = tls_ciphersuites
- self._auth_plugin: Optional[str] = auth_plugin
- self._auth_plugin_class: Optional[str] = None
- self._handshake: Optional[HandShakeType] = None
- self._loop: Optional[asyncio.AbstractEventLoop] = (
+ self._ssl_active = False
+ self._ssl_disabled = ssl_disabled
+ self._ssl_ca = ssl_ca
+ self._ssl_cert = ssl_cert
+ self._ssl_key = ssl_key
+ self._ssl_verify_cert = ssl_verify_cert
+ self._ssl_verify_identity = ssl_verify_identity
+ self._tls_versions = tls_versions
+ self._tls_ciphersuites = tls_ciphersuites
+ self._auth_plugin = auth_plugin
+ self._auth_plugin_class = None
+ self._handshake = None
+ self._loop = (
loop or asyncio.get_event_loop()
)
- self._client_flags: int = client_flags or ClientFlag.get_default()
- self._server_info: Optional[ServerInfo] = None
- self._cursors: weakref.WeakSet = weakref.WeakSet()
- self._query_attrs: Dict[str, BinaryProtocolType] = {}
- self._query_attrs_supported: int = False
- self._columns_desc: List[DescriptionType] = []
- self._authenticator: MySQLAuthenticator = MySQLAuthenticator()
- self._converter_class: Type[MySQLConverter] = converter_class or MySQLConverter
- self._converter_str_fallback: bool = converter_str_fallback
- self._kerberos_auth_mode: Optional[str] = kerberos_auth_mode
- self._krb_service_principal: Optional[str] = krb_service_principal
- self._openid_token_file: Optional[str] = openid_token_file
- self._allow_local_infile: bool = allow_local_infile
- self._allow_local_infile_in_path: Optional[str] = allow_local_infile_in_path
- self._get_warnings: bool = get_warnings
- self.raise_on_warnings: bool = raise_on_warnings
- self._buffered: bool = buffered
- self._raw: bool = raw
- self._use_unicode: bool = use_unicode
- self._have_next_result: bool = False
- self._unread_result: bool = False
- self._in_transaction: bool = False
- self._oci_config_file: Optional[str] = None
- self._oci_config_profile: Optional[str] = None
- self._webauthn_callback: Optional[Union[str, Callable[[str], None]]] = (
+ self._client_flags = client_flags or ClientFlag.get_default()
+ self._server_info = None
+ self._cursors = weakref.WeakSet()
+ self._query_attrs = {}
+ self._query_attrs_supported = False
+ self._columns_desc = []
+ self._authenticator = MySQLAuthenticator()
+ self._converter_class = converter_class or MySQLConverter
+ self._converter_str_fallback = converter_str_fallback
+ self._kerberos_auth_mode = kerberos_auth_mode
+ self._krb_service_principal = krb_service_principal
+ self._openid_token_file = openid_token_file
+ self._allow_local_infile = allow_local_infile
+ self._allow_local_infile_in_path = allow_local_infile_in_path
+ self._get_warnings = get_warnings
+ self.raise_on_warnings = raise_on_warnings
+ self._buffered = buffered
+ self._raw = raw
+ self._use_unicode = use_unicode
+ self._have_next_result = False
+ self._unread_result = False
+ self._in_transaction = False
+ self._oci_config_file = None
+ self._oci_config_profile = None
+ self._webauthn_callback = (
webauthn_callback
)
- self.converter: Optional[MySQLConverter] = None
+ self.converter = None
self._validate_connection_options()
- async def __aenter__(self) -> MySQLConnectionAbstract:
+ async def __aenter__(self) :
if not self.is_socket_connected():
await self.connect()
return self
async def __aexit__(
self,
- exc_type: Optional[Type[BaseException]] = None,
- exc_value: Optional[BaseException] = None,
- traceback: Optional[TracebackType] = None,
- ) -> None:
+ exc_type = None,
+ exc_value = None,
+ traceback = None,
+ ) :
await self.close()
- def _validate_connection_options(self) -> None:
+ def _validate_connection_options(self) :
"""Validate connection options."""
if self._user:
try:
@@ -453,7 +452,7 @@ class MySQLConnectionAbstract(ABC):
"does not exist"
)
- def _validate_tls_ciphersuites(self) -> None:
+ def _validate_tls_ciphersuites(self) :
"""Validates the tls_ciphersuites option."""
tls_ciphersuites = []
tls_cs = self._tls_ciphersuites
@@ -491,9 +490,9 @@ class MySQLConnectionAbstract(ABC):
newer_tls_ver = tls_versions[0]
# translated_names[0] are TLSv1.2 only
# translated_names[1] are TLSv1.3 only
- translated_names: List[List[str]] = [[], []]
+ translated_names = [[], []]
iani_cipher_suites_names = {}
- ossl_cipher_suites_names: List[str] = []
+ ossl_cipher_suites_names = []
# Old ciphers can work with new TLS versions.
# Find all the ciphers introduced on previous TLS versions.
@@ -546,7 +545,7 @@ class MySQLConnectionAbstract(ABC):
":".join(translated_names[1]),
]
- def _validate_tls_versions(self) -> None:
+ def _validate_tls_versions(self) :
"""Validates the tls_versions option."""
tls_versions = []
tls_version = self._tls_versions
@@ -629,8 +628,8 @@ class MySQLConnectionAbstract(ABC):
@staticmethod
def _validate_callable(
- option_name: str, callback: Union[str, Callable], num_args: int = 0
- ) -> None:
+ option_name , callback , num_args = 0
+ ) :
"""Validates if it's a Python callable.
Args:
@@ -664,31 +663,31 @@ class MySQLConnectionAbstract(ABC):
@property
@abstractmethod
- def connection_id(self) -> Optional[int]:
+ def connection_id(self) :
"""MySQL connection ID."""
@property
- def user(self) -> str:
+ def user(self) :
"""User used while connecting to MySQL."""
return self._user
@property
- def server_host(self) -> str:
+ def server_host(self) :
"""MySQL server IP address or name."""
return self._host
@property
- def server_port(self) -> int:
+ def server_port(self) :
"MySQL server TCP/IP port."
return self._port
@property
- def unix_socket(self) -> Optional[str]:
+ def unix_socket(self) :
"MySQL Unix socket file location."
return self._unix_socket
@property
- def database(self) -> str:
+ def database(self) :
"""Get the current database."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
@@ -696,60 +695,60 @@ class MySQLConnectionAbstract(ABC):
)
@database.setter
- def database(self, value: str) -> None:
+ def database(self, value ) :
"""Set the current database."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
"Use `await set_database(name)` to set the database instead"
)
- async def get_database(self) -> str:
+ async def get_database(self) :
"""Get the current database."""
result = await self.info_query("SELECT DATABASE()")
return result[0] # type: ignore[return-value]
- async def set_database(self, value: str) -> None:
+ async def set_database(self, value ) :
"""Set the current database."""
await self.cmd_query(f"USE {value}")
@property
- def can_consume_results(self) -> bool:
+ def can_consume_results(self) :
"""Returns whether to consume results"""
return self._consume_results
@can_consume_results.setter
- def can_consume_results(self, value: bool) -> None:
+ def can_consume_results(self, value ) :
"""Set if can consume results."""
assert isinstance(value, bool)
self._consume_results = value
@property
- def in_transaction(self) -> bool:
+ def in_transaction(self) :
"""MySQL session has started a transaction."""
return self._in_transaction
@property
- def loop(self) -> asyncio.AbstractEventLoop:
+ def loop(self) :
"""Return the event loop."""
return self._loop
@property
- def is_secure(self) -> bool:
+ def is_secure(self) :
"""Return True if is a secure connection."""
return self._ssl_active or (self._unix_socket is not None and IS_POSIX)
@property
- def query_attrs(self) -> List[Tuple[str, BinaryProtocolType]]:
+ def query_attrs(self) :
"""Returns query attributes list."""
return list(self._query_attrs.items())
@property
- def have_next_result(self) -> bool:
+ def have_next_result(self) :
"""Return if have next result."""
return self._have_next_result
@property
- def autocommit(self) -> bool:
+ def autocommit(self) :
"""Get whether autocommit is on or off."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
@@ -757,26 +756,26 @@ class MySQLConnectionAbstract(ABC):
)
@autocommit.setter
- def autocommit(self, value: bool) -> None:
+ def autocommit(self, value ) :
"""Toggle autocommit."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
"Use `await set_autocommit(value)` to set the autocommit instead"
)
- async def get_autocommit(self) -> bool:
+ async def get_autocommit(self) :
"""Get whether autocommit is on or off."""
value = await self.info_query("SELECT @@session.autocommit")
return value[0] == 1
- async def set_autocommit(self, value: bool) -> None:
+ async def set_autocommit(self, value ) :
"""Toggle autocommit."""
switch = "ON" if value else "OFF"
await self.cmd_query(f"SET @@session.autocommit = {switch}")
self._autocommit = value
@property
- def time_zone(self) -> str:
+ def time_zone(self) :
"""Gets the current time zone."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
@@ -784,25 +783,25 @@ class MySQLConnectionAbstract(ABC):
)
@time_zone.setter
- def time_zone(self, value: str) -> None:
+ def time_zone(self, value ) :
"""Sets the time zone."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
"Use `await get_autocommit(value)` to get the autocommit instead"
)
- async def get_time_zone(self) -> str:
+ async def get_time_zone(self) :
"""Gets the current time zone."""
value = await self.info_query("SELECT @@session.time_zone")
return value[0] # type: ignore[return-value]
- async def set_time_zone(self, value: str) -> None:
+ async def set_time_zone(self, value ) :
"""Sets the time zone."""
await self.cmd_query(f"SET @@session.time_zone = '{value}'")
self._time_zone = value
@property
- async def sql_mode(self) -> str:
+ async def sql_mode(self) :
"""Gets the SQL mode."""
raise ProgrammingError(
"The use of async properties are not supported by Python. "
@@ -810,7 +809,7 @@ class MySQLConnectionAbstract(ABC):
)
@sql_mode.setter
- async def sql_mode(self, value: Union[str, Sequence[int]]) -> None:
+ async def sql_mode(self, value ) :
"""Sets the SQL mode.
This method sets the SQL Mode for the current connection. The value
@@ -828,13 +827,13 @@ class MySQLConnectionAbstract(ABC):
"Use `await set_sql_mode(value)` to set the SQL mode instead"
)
- async def get_sql_mode(self) -> str:
+ async def get_sql_mode(self) :
"""Gets the SQL mode."""
if self._sql_mode is None:
self._sql_mode = (await self.info_query("SELECT @@session.sql_mode"))[0]
return self._sql_mode
- async def set_sql_mode(self, value: Union[str, Sequence[int]]) -> None:
+ async def set_sql_mode(self, value ) :
"""Sets the SQL mode.
This method sets the SQL Mode for the current connection. The value
@@ -853,7 +852,7 @@ class MySQLConnectionAbstract(ABC):
self._sql_mode = value
@property
- def get_warnings(self) -> bool:
+ def get_warnings(self) :
"""Get whether this connection retrieves warnings automatically.
This method returns whether this connection retrieves warnings automatically.
@@ -861,7 +860,7 @@ class MySQLConnectionAbstract(ABC):
return self._get_warnings
@get_warnings.setter
- def get_warnings(self, value: bool) -> None:
+ def get_warnings(self, value ) :
"""Set whether warnings should be automatically retrieved.
The toggle-argument must be a boolean. When True, cursors for this connection
@@ -875,7 +874,7 @@ class MySQLConnectionAbstract(ABC):
self._get_warnings = value
@property
- def raise_on_warnings(self) -> bool:
+ def raise_on_warnings(self) :
"""Get whether this connection raises an error on warnings.
This method returns whether this connection will raise errors when MySQL
@@ -884,7 +883,7 @@ class MySQLConnectionAbstract(ABC):
return self._raise_on_warnings
@raise_on_warnings.setter
- def raise_on_warnings(self, value: bool) -> None:
+ def raise_on_warnings(self, value ) :
"""Set whether warnings raise an error.
The toggle-argument must be a boolean. When True, cursors for this connection
@@ -905,7 +904,7 @@ class MySQLConnectionAbstract(ABC):
self._get_warnings = value
@property
- def unread_result(self) -> bool:
+ def unread_result(self) :
"""Get whether there is an unread result.
This method is used by cursors to check whether another cursor still needs to
@@ -914,7 +913,7 @@ class MySQLConnectionAbstract(ABC):
return self._unread_result
@unread_result.setter
- def unread_result(self, value: bool) -> None:
+ def unread_result(self, value ) :
"""Set whether there is an unread result.
This method is used by cursors to let other cursors know there is still a
@@ -928,7 +927,7 @@ class MySQLConnectionAbstract(ABC):
self._unread_result = value
@property
- def collation(self) -> str:
+ def collation(self) :
"""Returns the collation for current connection.
This property returns the collation name of the current connection.
@@ -940,7 +939,7 @@ class MySQLConnectionAbstract(ABC):
return self._charset.collation
@property
- def charset(self) -> str:
+ def charset(self) :
"""Return the character set for current connection.
This property returns the character set name of the current connection.
@@ -950,7 +949,7 @@ class MySQLConnectionAbstract(ABC):
return self._charset.name
@property
- def charset_id(self) -> int:
+ def charset_id(self) :
"""The charset ID utilized during the connection phase.
If the charset ID hasn't been set, the default charset ID is returned.
@@ -958,7 +957,7 @@ class MySQLConnectionAbstract(ABC):
return self._charset.charset_id
@property
- def _charset(self) -> Charset:
+ def _charset(self) :
"""The charset object encapsulates charset and collation information."""
if self.__charset is None:
if self._server_info is None:
@@ -978,12 +977,12 @@ class MySQLConnectionAbstract(ABC):
return self.__charset
@_charset.setter
- def _charset(self, value: Charset) -> None:
+ def _charset(self, value ) :
"""The charset object encapsulates charset and collation information."""
self.__charset = value
@property
- def python_charset(self) -> str:
+ def python_charset(self) :
"""Return the Python character set for current connection.
This property returns the character set name of the current connection.
@@ -1000,11 +999,11 @@ class MySQLConnectionAbstract(ABC):
return self._charset.name
@abstractmethod
- def _add_default_conn_attrs(self) -> None:
+ def _add_default_conn_attrs(self) :
"""Add the default connection attributes."""
@abstractmethod
- async def _execute_query(self, query: str) -> ResultType:
+ async def _execute_query(self, query ) :
"""Execute a query.
This method simply calls cmd_query() after checking for unread result. If there
@@ -1012,7 +1011,7 @@ class MySQLConnectionAbstract(ABC):
cmd_query() returns is returned.
"""
- async def _post_connection(self) -> None:
+ async def _post_connection(self) :
"""Executes commands after connection has been established.
This method executes commands after the connection has been established.
@@ -1029,8 +1028,8 @@ class MySQLConnectionAbstract(ABC):
await self._execute_query(self._init_command)
async def set_charset_collation(
- self, charset: Optional[Union[int, str]] = None, collation: Optional[str] = None
- ) -> None:
+ self, charset = None, collation = None
+ ) :
"""Set the character set and collation for the current connection.
This method sets the character set and collation to be used for the current
@@ -1060,7 +1059,7 @@ class MySQLConnectionAbstract(ABC):
raise ValueError("collation should be either string or None")
if charset and collation:
- charset_str: str = (
+ charset_str = (
charsets.get_by_id(charset).name
if isinstance(charset, int)
else charset
@@ -1086,7 +1085,7 @@ class MySQLConnectionAbstract(ABC):
if self.converter:
self.converter.set_charset(self._charset.name)
- def isset_client_flag(self, flag: int) -> bool:
+ def isset_client_flag(self, flag ) :
"""Checks if a client flag is set.
Returns:
@@ -1094,7 +1093,7 @@ class MySQLConnectionAbstract(ABC):
"""
return (self._client_flags & flag) > 0
- def set_allow_local_infile_in_path(self, path: str) -> None:
+ def set_allow_local_infile_in_path(self, path ) :
"""Set the path that user can upload files.
Args:
@@ -1103,7 +1102,7 @@ class MySQLConnectionAbstract(ABC):
self._allow_local_infile_in_path = path
- def get_self(self) -> MySQLConnectionAbstract:
+ def get_self(self) :
"""Return self for weakref.proxy.
This method is used when the original object is needed when using
@@ -1111,7 +1110,7 @@ class MySQLConnectionAbstract(ABC):
"""
return self
- def get_server_version(self) -> Optional[Tuple[int, ...]]:
+ def get_server_version(self) :
"""Gets the MySQL version.
Returns:
@@ -1122,7 +1121,7 @@ class MySQLConnectionAbstract(ABC):
return self._server_info.version # type: ignore[return-value]
return None
- def get_server_info(self) -> Optional[str]:
+ def get_server_info(self) :
"""Gets the original MySQL version information.
Returns:
@@ -1135,7 +1134,7 @@ class MySQLConnectionAbstract(ABC):
return None
@abstractmethod
- def is_socket_connected(self) -> bool:
+ def is_socket_connected(self) :
"""Reports whether the socket is connected.
Instead of ping the server like ``is_connected()``, it only checks if the
@@ -1143,7 +1142,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def is_connected(self) -> bool:
+ async def is_connected(self) :
"""Reports whether the connection to MySQL Server is available.
This method checks whether the connection to MySQL is available.
@@ -1153,8 +1152,8 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def ping(
- self, reconnect: bool = False, attempts: int = 1, delay: int = 0
- ) -> bool:
+ self, reconnect = False, attempts = 1, delay = 0
+ ) :
"""Check availability of the MySQL server.
When reconnect is set to `True`, one or more attempts are made to try to
@@ -1170,7 +1169,7 @@ class MySQLConnectionAbstract(ABC):
InterfaceError: On errors.
"""
- def set_client_flags(self, flags: Union[int, Sequence[int]]) -> int:
+ def set_client_flags(self, flags ) :
"""Set the client flags.
The flags-argument can be either an int or a list (or tuple) of ClientFlag
@@ -1195,7 +1194,7 @@ class MySQLConnectionAbstract(ABC):
raise ProgrammingError("set_client_flags expect integer (>0) or set")
return self._client_flags
- def set_converter_class(self, convclass: Optional[Type[MySQLConverter]]) -> None:
+ def set_converter_class(self, convclass ) :
"""Set the converter class to be used.
This should be a class overloading methods and members of
@@ -1213,7 +1212,7 @@ class MySQLConnectionAbstract(ABC):
"Converter class should be a subclass of conversion.MySQLConverter"
)
- def query_attrs_append(self, value: Tuple[str, BinaryProtocolType]) -> None:
+ def query_attrs_append(self, value ) :
"""Add element to the query attributes list on the connector's side.
If an element in the query attributes list already matches
@@ -1226,7 +1225,7 @@ class MySQLConnectionAbstract(ABC):
if attr_name not in self._query_attrs:
self._query_attrs[attr_name] = attr_value
- def query_attrs_remove(self, name: str) -> BinaryProtocolType:
+ def query_attrs_remove(self, name ) :
"""Remove element by name from the query attributes list.
If no match, `None` is returned, else the corresponding value is returned.
@@ -1236,11 +1235,11 @@ class MySQLConnectionAbstract(ABC):
"""
return self._query_attrs.pop(name, None)
- def query_attrs_clear(self) -> None:
+ def query_attrs_clear(self) :
"""Clears query attributes list on the connector's side."""
self._query_attrs = {}
- async def handle_unread_result(self) -> None:
+ async def handle_unread_result(self) :
"""Handle unread result.
Consume pending results if is configured for it.
@@ -1253,30 +1252,30 @@ class MySQLConnectionAbstract(ABC):
elif self.unread_result:
raise InternalError("Unread result found")
- async def consume_results(self) -> None:
+ async def consume_results(self) :
"""Consume pending results."""
if self.unread_result:
await self.get_rows()
- async def info_query(self, query: StrOrBytes) -> Optional[RowType]:
+ async def info_query(self, query ) :
"""Send a query which only returns 1 row."""
async with await self.cursor(buffered=True) as cursor:
await cursor.execute(query)
return await cursor.fetchone()
- def add_cursor(self, cursor: MySQLCursorAbstract) -> None:
+ def add_cursor(self, cursor ) :
"""Add cursor to the weakref set."""
self._cursors.add(cursor)
- def remove_cursor(self, cursor: MySQLCursorAbstract) -> None:
+ def remove_cursor(self, cursor ) :
"""Remove cursor from the weakref set."""
self._cursors.remove(cursor)
@abstractmethod
- async def connect(self) -> None:
+ async def connect(self) :
"""Connect to the MySQL server."""
- async def reconnect(self, attempts: int = 1, delay: int = 0) -> None:
+ async def reconnect(self, attempts = 1, delay = 0) :
"""Attempts to reconnect to the MySQL server.
The argument `attempts` should be the number of times a reconnect is tried.
@@ -1311,7 +1310,7 @@ class MySQLConnectionAbstract(ABC):
if delay > 0:
await asyncio.sleep(delay)
- async def shutdown(self) -> NoReturn:
+ async def shutdown(self) :
"""Shuts down connection to MySQL Server.
This method closes the socket. It raises no exceptions.
@@ -1323,7 +1322,7 @@ class MySQLConnectionAbstract(ABC):
raise NotImplementedError
@abstractmethod
- async def close(self) -> None:
+ async def close(self) :
"""Close the connection.
It closes any opened cursor associated to this connection, and closes the
@@ -1336,18 +1335,18 @@ class MySQLConnectionAbstract(ABC):
no exceptions.
"""
- disconnect: Callable[[], Any] = close
+ disconnect = close
@abstractmethod
async def cursor(
self,
- buffered: Optional[bool] = None,
- raw: Optional[bool] = None,
- prepared: Optional[bool] = None,
- cursor_class: Optional[Type[MySQLCursorAbstract]] = None,
- dictionary: Optional[bool] = None,
- named_tuple: Optional[bool] = None,
- ) -> MySQLCursorAbstract:
+ buffered = None,
+ raw = None,
+ prepared = None,
+ cursor_class = None,
+ dictionary = None,
+ named_tuple = None,
+ ) :
"""Instantiate and return a cursor.
By default, MySQLCursor is returned. Depending on the options while
@@ -1368,10 +1367,10 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def get_row(
self,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- ) -> Tuple[Optional[RowType], Optional[EofPacketType]]:
+ binary = False,
+ columns = None,
+ raw = None,
+ ) :
"""Get the next rows returned by the MySQL server.
This method gets one row from the result set after sending, for example, the
@@ -1382,12 +1381,12 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def get_rows(
self,
- count: Optional[int] = None,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- prep_stmt: Any = None,
- ) -> Tuple[List[RowType], Optional[EofPacketType]]:
+ count = None,
+ binary = False,
+ columns = None,
+ raw = None,
+ prep_stmt = None,
+ ) :
"""Get all rows returned by the MySQL server.
This method gets all rows returned by the MySQL server after sending, for
@@ -1396,15 +1395,15 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def commit(self) -> None:
+ async def commit(self) :
"""Commit current transaction."""
@abstractmethod
- async def rollback(self) -> None:
+ async def rollback(self) :
"""Rollback current transaction."""
@abstractmethod
- async def cmd_reset_connection(self) -> bool:
+ async def cmd_reset_connection(self) :
"""Resets the session state without re-authenticating.
Reset command only works on MySQL server 5.7.3 or later.
@@ -1412,7 +1411,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_init_db(self, database: str) -> OkPacketType:
+ async def cmd_init_db(self, database ) :
"""Change the current database.
This method changes the current (default) database by sending the INIT_DB
@@ -1422,11 +1421,11 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def cmd_query(
self,
- query: StrOrBytes,
- raw: bool = False,
- buffered: bool = False,
- raw_as_string: bool = False,
- ) -> ResultType:
+ query ,
+ raw = False,
+ buffered = False,
+ raw_as_string = False,
+ ) :
"""Send a query to the MySQL server.
This method send the query to the MySQL server and returns the result.
@@ -1440,8 +1439,8 @@ class MySQLConnectionAbstract(ABC):
"""
async def cmd_query_iter(
- self, statements: StrOrBytes
- ) -> Generator[ResultType, None, None]:
+ self, statements
+ ) :
"""Send one or more statements to the MySQL server.
Similar to the cmd_query method, but instead returns a generator
@@ -1458,7 +1457,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_stmt_fetch(self, statement_id: int, rows: int = 1) -> None:
+ async def cmd_stmt_fetch(self, statement_id , rows = 1) :
"""Fetch a MySQL statement Result Set.
This method will send the FETCH command to MySQL together with the given
@@ -1467,8 +1466,8 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def cmd_stmt_prepare(
- self, statement: bytes
- ) -> Mapping[str, Union[int, List[DescriptionType]]]:
+ self, statement
+ ) :
"""Prepare a MySQL statement.
This method will send the PREPARE command to MySQL together with the given
@@ -1478,22 +1477,22 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def cmd_stmt_execute(
self,
- statement_id: Union[int, CMySQLPrepStmt],
- data: Sequence[BinaryProtocolType] = (),
- parameters: Sequence = (),
- flags: int = 0,
- ) -> Optional[Union[Dict[str, Any], Tuple]]:
+ statement_id ,
+ data = (),
+ parameters = (),
+ flags = 0,
+ ) :
"""Execute a prepared MySQL statement."""
@abstractmethod
- async def cmd_stmt_reset(self, statement_id: int) -> None:
+ async def cmd_stmt_reset(self, statement_id ) :
"""Reset data for prepared statement sent as long data.
The result is a dictionary with OK packet information.
"""
@abstractmethod
- async def cmd_stmt_close(self, statement_id: int) -> None:
+ async def cmd_stmt_close(self, statement_id ) :
"""Deallocate a prepared MySQL statement.
This method deallocates the prepared statement using the statement_id.
@@ -1501,7 +1500,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_refresh(self, options: int) -> OkPacketType:
+ async def cmd_refresh(self, options ) :
"""Send the Refresh command to the MySQL server.
This method sends the Refresh command to the MySQL server. The options
@@ -1514,8 +1513,8 @@ class MySQLConnectionAbstract(ABC):
"""
async def cmd_stmt_send_long_data(
- self, statement_id: int, param_id: int, data: BinaryIO
- ) -> int:
+ self, statement_id , param_id , data
+ ) :
"""Send data for a column.
This methods send data for a column (for example BLOB) for statement identified
@@ -1531,14 +1530,14 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_quit(self) -> bytes:
+ async def cmd_quit(self) :
"""Close the current connection with the server.
Send the QUIT command to the MySQL server, closing the current connection.
"""
@abstractmethod
- async def cmd_shutdown(self, shutdown_type: Optional[int] = None) -> None:
+ async def cmd_shutdown(self, shutdown_type = None) :
"""Shut down the MySQL Server.
This method sends the SHUTDOWN command to the MySQL server.
@@ -1546,7 +1545,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_statistics(self) -> StatsPacketType:
+ async def cmd_statistics(self) :
"""Send the statistics command to the MySQL Server.
This method sends the STATISTICS command to the MySQL server. The result is a
@@ -1554,7 +1553,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_process_kill(self, mysql_pid: int) -> OkPacketType:
+ async def cmd_process_kill(self, mysql_pid ) :
"""Kill a MySQL process.
This method send the PROCESS_KILL command to the server along with the
@@ -1562,7 +1561,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_debug(self) -> EofPacketType:
+ async def cmd_debug(self) :
"""Send the DEBUG command.
This method sends the DEBUG command to the MySQL server, which requires the
@@ -1572,7 +1571,7 @@ class MySQLConnectionAbstract(ABC):
"""
@abstractmethod
- async def cmd_ping(self) -> OkPacketType:
+ async def cmd_ping(self) :
"""Send the PING command.
This method sends the PING command to the MySQL server. It is used to check
@@ -1583,17 +1582,17 @@ class MySQLConnectionAbstract(ABC):
@abstractmethod
async def cmd_change_user(
self,
- username: str = "",
- password: str = "",
- database: str = "",
- charset: Optional[int] = None,
- password1: str = "",
- password2: str = "",
- password3: str = "",
- oci_config_file: str = "",
- oci_config_profile: str = "",
- openid_token_file: str = "",
- ) -> Optional[OkPacketType]:
+ username = "",
+ password = "",
+ database = "",
+ charset = None,
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ oci_config_file = "",
+ oci_config_profile = "",
+ openid_token_file = "",
+ ) :
"""Changes the current logged in user.
It also causes the specified database to become the default (current)
@@ -1631,38 +1630,38 @@ class MySQLConnectionAbstract(ABC):
class MySQLCursorAbstract(ABC):
"""Defines the MySQL cursor interface."""
- def __init__(self, connection: MySQLConnectionAbstract):
- self._connection: MySQLConnectionAbstract = connection
- self._loop: asyncio.AbstractEventLoop = connection.loop
- self._description: Optional[List[DescriptionType]] = None
- self._last_insert_id: Optional[int] = None
- self._warnings: Optional[List[WarningType]] = None
- self._warning_count: int = 0
- self._executed: Optional[StrOrBytes] = None
- self._executed_list: List[StrOrBytes] = []
- self._stored_results: List[Any] = []
- self._binary: bool = False
- self._raw: bool = False
- self._rowcount: int = -1
- self._nextrow: Tuple[Optional[RowType], Optional[EofPacketType]] = (
+ def __init__(self, connection ):
+ self._connection = connection
+ self._loop = connection.loop
+ self._description = None
+ self._last_insert_id = None
+ self._warnings = None
+ self._warning_count = 0
+ self._executed = None
+ self._executed_list = []
+ self._stored_results = []
+ self._binary = False
+ self._raw = False
+ self._rowcount = -1
+ self._nextrow = (
None,
None,
)
- self.arraysize: int = 1
+ self.arraysize = 1
self._connection.add_cursor(self)
- async def __aenter__(self) -> MySQLCursorAbstract:
+ async def __aenter__(self) :
return self
async def __aexit__(
self,
- exc_type: Optional[Type[BaseException]] = None,
- exc_value: Optional[BaseException] = None,
- traceback: Optional[TracebackType] = None,
- ) -> None:
+ exc_type = None,
+ exc_value = None,
+ traceback = None,
+ ) :
await self.close()
- async def __aiter__(self) -> Iterator[RowType]:
+ async def __aiter__(self) :
"""Iterate over result set.
Iteration over the result set which calls self.fetchone()
@@ -1670,7 +1669,7 @@ class MySQLCursorAbstract(ABC):
"""
return self # type: ignore[return-value]
- async def __next__(self) -> RowType:
+ async def __next__(self) :
"""
Used for iterating over the result set. Calles self.fetchone()
to get the next row.
@@ -1684,7 +1683,7 @@ class MySQLCursorAbstract(ABC):
return row
@property
- def description(self) -> Optional[List[DescriptionType]]:
+ def description(self) :
"""Return description of columns in a result.
This property returns a list of tuples describing the columns in in a result
@@ -1704,7 +1703,7 @@ class MySQLCursorAbstract(ABC):
return self._description
@property
- def rowcount(self) -> int:
+ def rowcount(self) :
"""Return the number of rows produced or affected.
This property returns the number of rows produced by queries such as a
@@ -1717,7 +1716,7 @@ class MySQLCursorAbstract(ABC):
return self._rowcount
@property
- def lastrowid(self) -> Optional[int]:
+ def lastrowid(self) :
"""Return the value generated for an AUTO_INCREMENT column.
Returns the value generated for an AUTO_INCREMENT column by the previous
@@ -1726,16 +1725,16 @@ class MySQLCursorAbstract(ABC):
return self._last_insert_id
@property
- def warnings(self) -> Optional[List[WarningType]]:
+ def warnings(self) :
"""Return warnings."""
return self._warnings
- def fetchwarnings(self) -> Optional[List[WarningType]]:
+ def fetchwarnings(self) :
"""Returns Warnings."""
return self._warnings
@property
- def warning_count(self) -> int:
+ def warning_count(self) :
"""Return the number of warnings.
This property returns the number of warnings generated by the previously
@@ -1744,7 +1743,7 @@ class MySQLCursorAbstract(ABC):
return self._warning_count
@property
- def column_names(self) -> Tuple[str, ...]:
+ def column_names(self) :
"""Returns column names.
This property returns the columns names as a tuple.
@@ -1754,7 +1753,7 @@ class MySQLCursorAbstract(ABC):
return tuple(d[0] for d in self.description)
@property
- def statement(self) -> Optional[str]:
+ def statement(self) :
"""Returns the executed statement
This property returns the executed statement.
@@ -1769,7 +1768,7 @@ class MySQLCursorAbstract(ABC):
return self._executed.strip() # type: ignore[return-value]
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
"""Returns whether the cursor could have rows returned.
This property returns True when column descriptions are available and possibly
@@ -1778,7 +1777,7 @@ class MySQLCursorAbstract(ABC):
return bool(self._description)
@abstractmethod
- def stored_results(self) -> Iterator[MySQLCursorAbstract]:
+ def stored_results(self) :
"""Returns an iterator for stored results.
This method returns an iterator over results which are stored when callproc()
@@ -1788,10 +1787,10 @@ class MySQLCursorAbstract(ABC):
@abstractmethod
async def execute(
self,
- operation: StrOrBytes,
- params: Union[Sequence[Any], Dict[str, Any]] = (),
- multi: bool = False,
- ) -> None:
+ operation ,
+ params = (),
+ multi = False,
+ ) :
"""Executes the given operation.
Executes the given operation substituting any markers with the given
@@ -1812,9 +1811,9 @@ class MySQLCursorAbstract(ABC):
async def executemulti(
self,
- operation: StrOrBytes,
- params: Union[Sequence[Any], Dict[str, Any]] = (),
- ) -> AsyncGenerator[MySQLCursorAbstract, None]:
+ operation ,
+ params = (),
+ ) :
"""Execute multiple statements.
Executes the given operation substituting any markers with the given
@@ -1824,9 +1823,9 @@ class MySQLCursorAbstract(ABC):
@abstractmethod
async def executemany(
self,
- operation: str,
- seq_params: Sequence[ParamsSequenceType],
- ) -> None:
+ operation ,
+ seq_params ,
+ ) :
"""Prepare and execute a MySQL Prepared Statement many times.
This method will prepare the given operation and execute with each tuple found
@@ -1838,7 +1837,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- async def fetchone(self) -> Optional[RowType]:
+ async def fetchone(self) :
"""Return next row of a query result set.
Raises:
@@ -1849,7 +1848,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- async def fetchall(self) -> List[RowType]:
+ async def fetchall(self) :
"""Return all rows of a query result set.
Raises:
@@ -1860,7 +1859,7 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- async def fetchmany(self, size: int = 1) -> List[Sequence[Any]]:
+ async def fetchmany(self, size = 1) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1872,10 +1871,10 @@ class MySQLCursorAbstract(ABC):
"""
@abstractmethod
- async def close(self) -> bool:
+ async def close(self) :
"""Close the cursor."""
- def getlastrowid(self) -> Optional[int]:
+ def getlastrowid(self) :
"""Return the value generated for an AUTO_INCREMENT column.
Returns the value generated for an AUTO_INCREMENT column by the previous
@@ -1883,10 +1882,10 @@ class MySQLCursorAbstract(ABC):
"""
return self._last_insert_id
- async def reset(self, free: bool = True) -> Any:
+ async def reset(self, free = True) :
"""Reset the cursor to default."""
- def get_attributes(self) -> Optional[List[Tuple[str, BinaryProtocolType]]]:
+ def get_attributes(self) :
"""Gets a list of query attributes from the connector's side.
Returns:
@@ -1896,7 +1895,7 @@ class MySQLCursorAbstract(ABC):
return self._connection.query_attrs
return None
- def add_attribute(self, name: str, value: BinaryProtocolType) -> None:
+ def add_attribute(self, name , value ) :
"""Add a query attribute and its value into the connector's query attributes.
Query attributes must be enabled on the server - they are disabled by default. A
@@ -1918,7 +1917,7 @@ class MySQLCursorAbstract(ABC):
)
self._connection.query_attrs_append((name, value))
- def remove_attribute(self, name: str) -> BinaryProtocolType:
+ def remove_attribute(self, name ) :
"""Removes a query attribute by name from the connector's query attributes.
If no match, `None` is returned, else the corresponding value is returned.
@@ -1933,7 +1932,7 @@ class MySQLCursorAbstract(ABC):
raise ProgrammingError("Parameter `name` must be a string type")
return self._connection.query_attrs_remove(name)
- def clear_attributes(self) -> None:
+ def clear_attributes(self) :
"""Clears the list of query attributes on the connector's side."""
self._connection.query_attrs_clear()
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/aio/authentication.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/aio/authentication.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/aio/authentication.py
@@ -28,7 +28,6 @@
"""Implementing support for MySQL Authentication Plugins."""
-from __future__ import annotations
__all__ = ["MySQLAuthenticator"]
@@ -56,22 +55,22 @@ if TYPE_CHECKING:
class MySQLAuthenticator:
"""Implements the authentication phase."""
- def __init__(self) -> None:
+ def __init__(self) :
"""Constructor."""
- self._username: str = ""
- self._passwords: Dict[int, str] = {}
- self._plugin_config: Dict[str, Any] = {}
- self._ssl_enabled: bool = False
- self._auth_strategy: Optional[MySQLAuthPlugin] = None
- self._auth_plugin_class: Optional[str] = None
+ self._username = ""
+ self._passwords = {}
+ self._plugin_config = {}
+ self._ssl_enabled = False
+ self._auth_strategy = None
+ self._auth_plugin_class = None
@property
- def ssl_enabled(self) -> bool:
+ def ssl_enabled(self) :
"""Signals whether or not SSL is enabled."""
return self._ssl_enabled
@property
- def plugin_config(self) -> Dict[str, Any]:
+ def plugin_config(self) :
"""Custom arguments that are being provided to the authentication plugin.
The parameters defined here will override the ones defined in the
@@ -87,17 +86,17 @@ class MySQLAuthenticator:
"""
return self._plugin_config
- def update_plugin_config(self, config: Dict[str, Any]) -> None:
+ def update_plugin_config(self, config ) :
"""Update the 'plugin_config' instance variable"""
self._plugin_config.update(config)
def _switch_auth_strategy(
self,
- new_strategy_name: str,
- strategy_class: Optional[str] = None,
- username: Optional[str] = None,
- password_factor: int = 1,
- ) -> None:
+ new_strategy_name ,
+ strategy_class = None,
+ username = None,
+ password_factor = 1,
+ ) :
"""Switch the authorization plugin.
Args:
@@ -127,9 +126,9 @@ class MySQLAuthenticator:
async def _mfa_n_factor(
self,
- sock: MySQLSocket,
- pkt: bytes,
- ) -> Optional[bytes]:
+ sock ,
+ pkt ,
+ ) :
"""Handle MFA (Multi-Factor Authentication) response.
Up to three levels of authentication (MFA) are allowed.
@@ -181,9 +180,9 @@ class MySQLAuthenticator:
async def _handle_server_response(
self,
- sock: MySQLSocket,
- pkt: bytes,
- ) -> Optional[bytes]:
+ sock ,
+ pkt ,
+ ) :
"""Handle server's response.
Args:
@@ -236,22 +235,22 @@ class MySQLAuthenticator:
async def authenticate(
self,
- sock: MySQLSocket,
- handshake: HandShakeType,
- username: str = "",
- password1: str = "",
- password2: str = "",
- password3: str = "",
- database: Optional[str] = None,
- charset: int = DEFAULT_CHARSET_ID,
- client_flags: int = 0,
- ssl_enabled: bool = False,
- max_allowed_packet: int = DEFAULT_MAX_ALLOWED_PACKET,
- auth_plugin: Optional[str] = None,
- auth_plugin_class: Optional[str] = None,
- conn_attrs: Optional[Dict[str, str]] = None,
- is_change_user_request: bool = False,
- ) -> bytes:
+ sock ,
+ handshake ,
+ username = "",
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ database = None,
+ charset = DEFAULT_CHARSET_ID,
+ client_flags = 0,
+ ssl_enabled = False,
+ max_allowed_packet = DEFAULT_MAX_ALLOWED_PACKET,
+ auth_plugin = None,
+ auth_plugin_class = None,
+ conn_attrs = None,
+ is_change_user_request = False,
+ ) :
"""Perform the authentication phase.
During re-authentication you must set `is_change_user_request` to True.
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/authentication.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/authentication.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/authentication.py
@@ -27,7 +27,6 @@
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Implementing support for MySQL Authentication Plugins"""
-from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Optional
@@ -53,22 +52,22 @@ if TYPE_CHECKING:
class MySQLAuthenticator:
"""Implements the authentication phase."""
- def __init__(self) -> None:
+ def __init__(self) :
"""Constructor."""
- self._username: str = ""
- self._passwords: Dict[int, str] = {}
- self._plugin_config: Dict[str, Any] = {}
- self._ssl_enabled: bool = False
- self._auth_strategy: Optional[MySQLAuthPlugin] = None
- self._auth_plugin_class: Optional[str] = None
+ self._username = ""
+ self._passwords = {}
+ self._plugin_config = {}
+ self._ssl_enabled = False
+ self._auth_strategy = None
+ self._auth_plugin_class = None
@property
- def ssl_enabled(self) -> bool:
+ def ssl_enabled(self) :
"""Signals whether or not SSL is enabled."""
return self._ssl_enabled
@property
- def plugin_config(self) -> Dict[str, Any]:
+ def plugin_config(self) :
"""Custom arguments that are being provided to the authentication plugin when called.
The parameters defined here will override the ones defined in the
@@ -84,19 +83,19 @@ class MySQLAuthenticator:
"""
return self._plugin_config
- def update_plugin_config(self, config: Dict[str, Any]) -> None:
+ def update_plugin_config(self, config ) :
"""Update the 'plugin_config' instance variable"""
self._plugin_config.update(config)
def setup_ssl(
self,
- sock: MySQLSocket,
- host: str,
- ssl_options: Optional[Dict[str, Any]],
- charset: int = DEFAULT_CHARSET_ID,
- client_flags: int = 0,
- max_allowed_packet: int = DEFAULT_MAX_ALLOWED_PACKET,
- ) -> bytes:
+ sock ,
+ host ,
+ ssl_options ,
+ charset = DEFAULT_CHARSET_ID,
+ client_flags = 0,
+ max_allowed_packet = DEFAULT_MAX_ALLOWED_PACKET,
+ ) :
"""Sets up an SSL communication channel.
Args:
@@ -147,11 +146,11 @@ class MySQLAuthenticator:
def _switch_auth_strategy(
self,
- new_strategy_name: str,
- strategy_class: Optional[str] = None,
- username: Optional[str] = None,
- password_factor: int = 1,
- ) -> None:
+ new_strategy_name ,
+ strategy_class = None,
+ username = None,
+ password_factor = 1,
+ ) :
"""Switches the authorization plugin.
Args:
@@ -181,9 +180,9 @@ class MySQLAuthenticator:
def _mfa_n_factor(
self,
- sock: MySQLSocket,
- pkt: bytes,
- ) -> Optional[bytes]:
+ sock ,
+ pkt ,
+ ) :
"""Handles MFA (Multi-Factor Authentication) response.
Up to three levels of authentication (MFA) are allowed.
@@ -235,9 +234,9 @@ class MySQLAuthenticator:
def _handle_server_response(
self,
- sock: MySQLSocket,
- pkt: bytes,
- ) -> Optional[bytes]:
+ sock ,
+ pkt ,
+ ) :
"""Handles server's response.
Args:
@@ -290,21 +289,21 @@ class MySQLAuthenticator:
def authenticate(
self,
- sock: MySQLSocket,
- handshake: HandShakeType,
- username: str = "",
- password1: str = "",
- password2: str = "",
- password3: str = "",
- database: Optional[str] = None,
- charset: int = DEFAULT_CHARSET_ID,
- client_flags: int = 0,
- max_allowed_packet: int = DEFAULT_MAX_ALLOWED_PACKET,
- auth_plugin: Optional[str] = None,
- auth_plugin_class: Optional[str] = None,
- conn_attrs: Optional[Dict[str, str]] = None,
- is_change_user_request: bool = False,
- ) -> bytes:
+ sock ,
+ handshake ,
+ username = "",
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ database = None,
+ charset = DEFAULT_CHARSET_ID,
+ client_flags = 0,
+ max_allowed_packet = DEFAULT_MAX_ALLOWED_PACKET,
+ auth_plugin = None,
+ auth_plugin_class = None,
+ conn_attrs = None,
+ is_change_user_request = False,
+ ) :
"""Performs the authentication phase.
During re-authentication you must set `is_change_user_request` to True.
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/connection.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/connection.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/connection.py
@@ -29,7 +29,6 @@
# mypy: disable-error-code="arg-type,operator,attr-defined,assignment"
"""Implementing communication with MySQL servers."""
-from __future__ import annotations
import datetime
import getpass
@@ -128,51 +127,51 @@ if OTEL_ENABLED:
class MySQLConnection(MySQLConnectionAbstract):
"""Connection to a MySQL Server"""
- def __init__(self, **kwargs: Any) -> None:
- self._protocol: Optional[MySQLProtocol] = None
- self._socket: Optional[MySQLSocket] = None
- self._handshake: Optional[HandShakeType] = None
+ def __init__(self, **kwargs ) :
+ self._protocol = None
+ self._socket = None
+ self._handshake = None
super().__init__()
- self._converter_class: Type[MySQLConverter] = MySQLConverter
+ self._converter_class = MySQLConverter
- self._client_flags: int = ClientFlag.get_default()
- self._sql_mode: Optional[str] = None
- self._time_zone: Optional[str] = None
- self._autocommit: bool = False
-
- self._user: str = ""
- self._password: str = ""
- self._database: str = ""
- self._host: str = "127.0.0.1"
- self._port: int = 3306
- self._unix_socket: Optional[str] = None
- self._client_host: str = ""
- self._client_port: int = 0
- self._ssl: Dict[str, Optional[Union[str, bool, List[str]]]] = {}
- self._force_ipv6: bool = False
-
- self._use_unicode: bool = True
- self._get_warnings: bool = False
- self._raise_on_warnings: bool = False
- self._buffered: bool = False
- self._unread_result: bool = False
- self._have_next_result: bool = False
- self._raw: bool = False
- self._in_transaction: bool = False
-
- self._prepared_statements: Any = None
-
- self._ssl_active: bool = False
- self._auth_plugin: Optional[str] = None
- self._krb_service_principal: Optional[str] = None
- self._pool_config_version: Any = None
- self._query_attrs_supported: int = False
+ self._client_flags = ClientFlag.get_default()
+ self._sql_mode = None
+ self._time_zone = None
+ self._autocommit = False
+
+ self._user = ""
+ self._password = ""
+ self._database = ""
+ self._host = "127.0.0.1"
+ self._port = 3306
+ self._unix_socket = None
+ self._client_host = ""
+ self._client_port = 0
+ self._ssl = {}
+ self._force_ipv6 = False
+
+ self._use_unicode = True
+ self._get_warnings = False
+ self._raise_on_warnings = False
+ self._buffered = False
+ self._unread_result = False
+ self._have_next_result = False
+ self._raw = False
+ self._in_transaction = False
+
+ self._prepared_statements = None
+
+ self._ssl_active = False
+ self._auth_plugin = None
+ self._krb_service_principal = None
+ self._pool_config_version = None
+ self._query_attrs_supported = False
- self._columns_desc: List[DescriptionType] = []
- self._mfa_nfactor: int = 1
+ self._columns_desc = []
+ self._mfa_nfactor = 1
- self._authenticator: MySQLAuthenticator = MySQLAuthenticator()
+ self._authenticator = MySQLAuthenticator()
if kwargs:
try:
@@ -183,7 +182,7 @@ class MySQLConnection(MySQLConnectionAbs
self._socket = None
raise
- def _add_default_conn_attrs(self) -> None:
+ def _add_default_conn_attrs(self) :
"""Add the default connection attributes."""
platform = get_platform()
license_chunks = version.LICENSE.split(" ")
@@ -203,7 +202,7 @@ class MySQLConnection(MySQLConnectionAbs
self._conn_attrs.update((default_conn_attrs))
- def _do_handshake(self) -> None:
+ def _do_handshake(self) :
"""Get the handshake from the MySQL server"""
packet = bytes(self._socket.recv())
if packet[4] == 255:
@@ -256,13 +255,13 @@ class MySQLConnection(MySQLConnectionAbs
def _do_auth(
self,
- username: Optional[str] = None,
- password: Optional[str] = None,
- database: Optional[str] = None,
- client_flags: int = 0,
- ssl_options: Optional[Dict[str, Optional[Union[str, bool, List[str]]]]] = None,
- conn_attrs: Optional[Dict[str, str]] = None,
- ) -> bool:
+ username = None,
+ password = None,
+ database = None,
+ client_flags = 0,
+ ssl_options = None,
+ conn_attrs = None,
+ ) :
"""Authenticate with the MySQL server
Authentication happens in two parts. We first send a response to the
@@ -332,7 +331,7 @@ class MySQLConnection(MySQLConnectionAbs
return True
- def _get_connection(self) -> MySQLSocket:
+ def _get_connection(self) :
"""Get connection based on configuration
This method will return the appropriated connection object using
@@ -353,7 +352,7 @@ class MySQLConnection(MySQLConnectionAbs
conn.set_connection_timeout(self._connection_timeout)
return conn
- def _open_connection(self) -> None:
+ def _open_connection(self) :
"""Open the connection to the MySQL server
This method sets up and opens the connection to the MySQL server.
@@ -408,7 +407,7 @@ class MySQLConnection(MySQLConnectionAbs
warn_tls_version_deprecated(tls_version)
warn_ciphersuites_deprecated(cipher, tls_version)
- def shutdown(self) -> None:
+ def shutdown(self) :
"""Shut down connection to MySQL Server.
This method closes the socket. It raises no exceptions.
@@ -425,7 +424,7 @@ class MySQLConnection(MySQLConnectionAbs
except (AttributeError, Error):
pass # Getting an exception would mean we are disconnected.
- def close(self) -> None:
+ def close(self) :
"""Disconnect from the MySQL server"""
if self._span and self._span.is_recording():
# pylint: disable=possibly-used-before-assignment
@@ -455,13 +454,13 @@ class MySQLConnection(MySQLConnectionAbs
def _send_cmd(
self,
- command: int,
- argument: Optional[bytes] = None,
- packet_number: int = 0,
- packet: Optional[bytes] = None,
- expect_response: bool = True,
- compressed_packet_number: int = 0,
- ) -> Optional[bytearray]:
+ command ,
+ argument = None,
+ packet_number = 0,
+ packet = None,
+ expect_response = True,
+ compressed_packet_number = 0,
+ ) :
"""Send a command to the MySQL server
This method sends a command with an optional argument.
@@ -491,8 +490,8 @@ class MySQLConnection(MySQLConnectionAbs
return self._socket.recv() if expect_response else None
def _send_data(
- self, data_file: BinaryIO, send_empty_packet: bool = False
- ) -> bytearray:
+ self, data_file , send_empty_packet = False
+ ) :
"""Send data to the MySQL server
This method accepts a file-like object and sends its data
@@ -524,7 +523,7 @@ class MySQLConnection(MySQLConnectionAbs
return self._socket.recv()
- def _handle_server_status(self, flags: int) -> None:
+ def _handle_server_status(self, flags ) :
"""Handle the server flags found in MySQL packets
This method handles the server flags send by MySQL OK and EOF
@@ -535,11 +534,11 @@ class MySQLConnection(MySQLConnectionAbs
self._in_transaction = flag_is_set(ServerFlag.STATUS_IN_TRANS, flags)
@property
- def in_transaction(self) -> bool:
+ def in_transaction(self) :
"""MySQL session has started a transaction"""
return self._in_transaction
- def _handle_ok(self, packet: bytes) -> OkPacketType:
+ def _handle_ok(self, packet ) :
"""Handle a MySQL OK packet
This method handles a MySQL OK packet. When the packet is found to
@@ -556,7 +555,7 @@ class MySQLConnection(MySQLConnectionAbs
raise get_exception(packet)
raise InterfaceError("Expected OK packet")
- def _handle_eof(self, packet: bytes) -> EofPacketType:
+ def _handle_eof(self, packet ) :
"""Handle a MySQL EOF packet
This method handles a MySQL EOF packet. When the packet is found to
@@ -573,7 +572,7 @@ class MySQLConnection(MySQLConnectionAbs
raise get_exception(packet)
raise InterfaceError("Expected EOF packet")
- def _handle_load_data_infile(self, filename: str) -> OkPacketType:
+ def _handle_load_data_infile(self, filename ) :
"""Handle a LOAD DATA INFILE LOCAL request"""
file_name = os.path.abspath(filename)
if os.path.islink(file_name):
@@ -621,7 +620,7 @@ class MySQLConnection(MySQLConnectionAbs
except (IOError, NameError):
pass
- def _handle_result(self, packet: bytes) -> ResultType:
+ def _handle_result(self, packet ) :
"""Handle a MySQL Result
This method handles a MySQL result, for example, after sending the
@@ -666,11 +665,11 @@ class MySQLConnection(MySQLConnectionAbs
def get_row(
self,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- prep_stmt: Optional[CMySQLPrepStmt] = None,
- ) -> Tuple[Optional[RowType], Optional[EofPacketType]]:
+ binary = False,
+ columns = None,
+ raw = None,
+ prep_stmt = None,
+ ) :
"""Get the next rows returned by the MySQL server
This method gets one row from the result set after sending, for
@@ -687,12 +686,12 @@ class MySQLConnection(MySQLConnectionAbs
def get_rows(
self,
- count: Optional[int] = None,
- binary: bool = False,
- columns: Optional[List[DescriptionType]] = None,
- raw: Optional[bool] = None,
- prep_stmt: Optional[CMySQLPrepStmt] = None,
- ) -> Tuple[List[RowType], Optional[EofPacketType]]:
+ count = None,
+ binary = False,
+ columns = None,
+ raw = None,
+ prep_stmt = None,
+ ) :
"""Get all rows returned by the MySQL server
This method gets all rows returned by the MySQL server after sending,
@@ -707,7 +706,7 @@ class MySQLConnection(MySQLConnectionAbs
if not self.unread_result:
raise InternalError("No result set available")
- rows: Tuple[List[Tuple], Optional[EofPacketType]] = ([], None)
+ rows = ([], None)
try:
if binary:
charset = self.charset
@@ -744,12 +743,12 @@ class MySQLConnection(MySQLConnectionAbs
return rows, eof_p
- def consume_results(self) -> None:
+ def consume_results(self) :
"""Consume results"""
if self.unread_result:
self.get_rows()
- def cmd_init_db(self, database: str) -> OkPacketType:
+ def cmd_init_db(self, database ) :
"""Change the current database
This method changes the current (default) database by sending the
@@ -765,11 +764,11 @@ class MySQLConnection(MySQLConnectionAbs
@with_context_propagation
def cmd_query(
self,
- query: StrOrBytes,
- raw: bool = False,
- buffered: bool = False,
- raw_as_string: bool = False,
- ) -> ResultType:
+ query ,
+ raw = False,
+ buffered = False,
+ raw_as_string = False,
+ ) :
"""Send a query to the MySQL server
This method send the query to the MySQL server and returns the result.
@@ -799,7 +798,7 @@ class MySQLConnection(MySQLConnectionAbs
if self._client_flags & ClientFlag.CLIENT_QUERY_ATTRIBUTES:
names = []
types = []
- values: List[bytes] = []
+ values = []
null_bitmap = [0] * ((len(self._query_attrs) + 7) // 8)
for pos, attr_tuple in enumerate(self._query_attrs.items()):
value = attr_tuple[1]
@@ -886,8 +885,8 @@ class MySQLConnection(MySQLConnectionAbs
return result
def cmd_query_iter(
- self, statements: StrOrBytes
- ) -> Generator[ResultType, None, None]:
+ self, statements
+ ) :
"""Send one or more statements to the MySQL server
Similar to the cmd_query method, but instead returns a generator
@@ -927,7 +926,7 @@ class MySQLConnection(MySQLConnectionAbs
self.handle_unread_result()
yield self._handle_result(self._socket.recv())
- def cmd_refresh(self, options: int) -> OkPacketType:
+ def cmd_refresh(self, options ) :
"""Send the Refresh command to the MySQL server
This method sends the Refresh command to the MySQL server. The options
@@ -965,7 +964,7 @@ class MySQLConnection(MySQLConnectionAbs
return res
- def cmd_quit(self) -> bytes:
+ def cmd_quit(self) :
"""Close the current connection with the server
This method sends the `QUIT` command to the MySQL server, closing the
@@ -980,7 +979,7 @@ class MySQLConnection(MySQLConnectionAbs
self._socket.send(packet, 0, 0)
return packet
- def cmd_shutdown(self, shutdown_type: Optional[int] = None) -> None:
+ def cmd_shutdown(self, shutdown_type = None) :
"""Shut down the MySQL Server
This method sends the SHUTDOWN command to the MySQL server.
@@ -988,7 +987,7 @@ class MySQLConnection(MySQLConnectionAbs
"""
self.cmd_query("SHUTDOWN")
- def cmd_statistics(self) -> StatsPacketType:
+ def cmd_statistics(self) :
"""Send the statistics command to the MySQL Server
This method sends the STATISTICS command to the MySQL server. The
@@ -1002,7 +1001,7 @@ class MySQLConnection(MySQLConnectionAbs
self._socket.send(packet, 0, 0)
return self._protocol.parse_statistics(self._socket.recv())
- def cmd_process_kill(self, mysql_pid: int) -> OkPacketType:
+ def cmd_process_kill(self, mysql_pid ) :
"""Kill a MySQL process
This method send the PROCESS_KILL command to the server along with
@@ -1013,7 +1012,7 @@ class MySQLConnection(MySQLConnectionAbs
raise ValueError("MySQL PID must be int")
return self.cmd_query(f"KILL {mysql_pid}")
- def cmd_debug(self) -> EofPacketType:
+ def cmd_debug(self) :
"""Send the DEBUG command
This method sends the DEBUG command to the MySQL server, which
@@ -1025,7 +1024,7 @@ class MySQLConnection(MySQLConnectionAbs
"""
return self._handle_eof(self._send_cmd(ServerCmd.DEBUG))
- def cmd_ping(self) -> OkPacketType:
+ def cmd_ping(self) :
"""Send the PING command
This method sends the PING command to the MySQL server. It is used to
@@ -1038,17 +1037,17 @@ class MySQLConnection(MySQLConnectionAbs
def cmd_change_user(
self,
- username: str = "",
- password: str = "",
- database: str = "",
- charset: Optional[int] = None,
- password1: str = "",
- password2: str = "",
- password3: str = "",
- oci_config_file: str = "",
- oci_config_profile: str = "",
- openid_token_file: str = "",
- ) -> Optional[OkPacketType]:
+ username = "",
+ password = "",
+ database = "",
+ charset = None,
+ password1 = "",
+ password2 = "",
+ password3 = "",
+ oci_config_file = "",
+ oci_config_profile = "",
+ openid_token_file = "",
+ ) :
"""Change the current logged in user
This method allows to change the current logged in user information.
@@ -1120,16 +1119,16 @@ class MySQLConnection(MySQLConnectionAbs
return self._handle_ok(ok_pkt)
@property
- def database(self) -> str:
+ def database(self) :
"""Get the current database"""
return self.info_query("SELECT DATABASE()")[0] # type: ignore[return-value]
@database.setter
- def database(self, value: str) -> None:
+ def database(self, value ) :
"""Set the current database"""
self.cmd_init_db(value)
- def is_connected(self) -> bool:
+ def is_connected(self) :
"""Reports whether the connection to MySQL Server is available
This method checks whether the connection to MySQL is available.
@@ -1144,7 +1143,7 @@ class MySQLConnection(MySQLConnectionAbs
return False # This method does not raise
return True
- def set_allow_local_infile_in_path(self, path: str) -> None:
+ def set_allow_local_infile_in_path(self, path ) :
"""Set the path that user can upload files.
Args:
@@ -1154,9 +1153,9 @@ class MySQLConnection(MySQLConnectionAbs
def reset_session(
self,
- user_variables: Optional[Dict[str, Any]] = None,
- session_variables: Optional[Dict[str, Any]] = None,
- ) -> None:
+ user_variables = None,
+ session_variables = None,
+ ) :
"""Clears the current active session
This method resets the session state, if the MySQL server is 5.7.3
@@ -1200,7 +1199,7 @@ class MySQLConnection(MySQLConnectionAbs
for key, value in session_variables.items():
cur.execute(f"SET SESSION `{key}` = %s", (value,))
- def ping(self, reconnect: bool = False, attempts: int = 1, delay: int = 0) -> None:
+ def ping(self, reconnect = False, attempts = 1, delay = 0) :
"""Check availability of the MySQL server
When reconnect is set to True, one or more attempts are made to try
@@ -1223,7 +1222,7 @@ class MySQLConnection(MySQLConnectionAbs
raise InterfaceError("Connection to MySQL is not available") from err
@property
- def connection_id(self) -> Optional[int]:
+ def connection_id(self) :
"""MySQL connection ID"""
if self._handshake:
return self._handshake.get("server_threadid") # type: ignore[return-value]
@@ -1231,13 +1230,13 @@ class MySQLConnection(MySQLConnectionAbs
def cursor(
self,
- buffered: Optional[bool] = None,
- raw: Optional[bool] = None,
- prepared: Optional[bool] = None,
- cursor_class: Optional[Type[MySQLCursor]] = None, # type: ignore[override]
- dictionary: Optional[bool] = None,
- named_tuple: Optional[bool] = None,
- ) -> MySQLCursor:
+ buffered = None,
+ raw = None,
+ prepared = None,
+ cursor_class = None, # type: ignore[override]
+ dictionary = None,
+ named_tuple = None,
+ ) :
"""Instantiates and returns a cursor
By default, MySQLCursor is returned. Depending on the options
@@ -1309,18 +1308,18 @@ class MySQLConnection(MySQLConnectionAbs
+ ", ".join([args[i] for i in range(5) if cursor_type & (1 << i) != 0])
) from None
- def commit(self) -> None:
+ def commit(self) :
"""Commit current transaction"""
self._execute_query("COMMIT")
- def rollback(self) -> None:
+ def rollback(self) :
"""Rollback current transaction"""
if self.unread_result:
self.get_rows()
self._execute_query("ROLLBACK")
- def _execute_query(self, query: str) -> None:
+ def _execute_query(self, query ) :
"""Execute a query
This method simply calls cmd_query() after checking for unread
@@ -1332,13 +1331,13 @@ class MySQLConnection(MySQLConnectionAbs
self.handle_unread_result()
self.cmd_query(query)
- def info_query(self, query: str) -> Optional[RowType]:
+ def info_query(self, query ) :
"""Send a query which only returns 1 row"""
cursor = self.cursor(buffered=True)
cursor.execute(query)
return cursor.fetchone()
- def _handle_binary_ok(self, packet: bytes) -> Dict[str, int]:
+ def _handle_binary_ok(self, packet ) :
"""Handle a MySQL Binary Protocol OK packet
This method handles a MySQL Binary Protocol OK packet. When the
@@ -1355,8 +1354,8 @@ class MySQLConnection(MySQLConnectionAbs
raise InterfaceError("Expected Binary OK packet")
def _handle_binary_result(
- self, packet: bytes
- ) -> Union[OkPacketType, Tuple[int, List[DescriptionType], EofPacketType]]:
+ self, packet
+ ) :
"""Handle a MySQL Result
This method handles a MySQL result, for example, after sending the
@@ -1384,7 +1383,7 @@ class MySQLConnection(MySQLConnectionAbs
if not column_count or not isinstance(column_count, int):
raise InterfaceError("Illegal result set.")
- columns: List[DescriptionType] = [None] * column_count
+ columns = [None] * column_count
for i in range(0, column_count):
columns[i] = self._protocol.parse_column(
self._socket.recv(), self.python_charset
@@ -1393,7 +1392,7 @@ class MySQLConnection(MySQLConnectionAbs
eof = self._handle_eof(self._socket.recv())
return (column_count, columns, eof)
- def cmd_stmt_fetch(self, statement_id: int, rows: int = 1) -> None:
+ def cmd_stmt_fetch(self, statement_id , rows = 1) :
"""Fetch a MySQL statement Result Set
This method will send the FETCH command to MySQL together with the
@@ -1405,8 +1404,8 @@ class MySQLConnection(MySQLConnectionAbs
self.unread_result = True
def cmd_stmt_prepare(
- self, statement: bytes
- ) -> Mapping[str, Union[int, List[DescriptionType]]]:
+ self, statement
+ ) :
"""Prepare a MySQL statement
This method will send the PREPARE command to MySQL together with the
@@ -1441,11 +1440,11 @@ class MySQLConnection(MySQLConnectionAbs
@with_context_propagation
def cmd_stmt_execute(
self,
- statement_id: int,
- data: Sequence[BinaryProtocolType] = (),
- parameters: Sequence = (),
- flags: int = 0,
- ) -> Union[OkPacketType, Tuple[int, List[DescriptionType], EofPacketType]]:
+ statement_id ,
+ data = (),
+ parameters = (),
+ flags = 0,
+ ) :
"""Execute a prepared MySQL statement"""
parameters = list(parameters)
long_data_used = {}
@@ -1490,7 +1489,7 @@ class MySQLConnection(MySQLConnectionAbs
result = self._handle_binary_result(packet)
return result
- def cmd_stmt_close(self, statement_id: int) -> None: # type: ignore[override]
+ def cmd_stmt_close(self, statement_id ) : # type: ignore[override]
"""Deallocate a prepared MySQL statement
This method deallocates the prepared statement using the
@@ -1504,8 +1503,8 @@ class MySQLConnection(MySQLConnectionAbs
)
def cmd_stmt_send_long_data(
- self, statement_id: int, param_id: int, data: BinaryIO # type: ignore[override]
- ) -> int:
+ self, statement_id , param_id , data # type: ignore[override]
+ ) :
"""Send data for a column
This methods send data for a column (for example BLOB) for statement
@@ -1542,7 +1541,7 @@ class MySQLConnection(MySQLConnectionAbs
return total_sent
- def cmd_stmt_reset(self, statement_id: int) -> None: # type: ignore[override]
+ def cmd_stmt_reset(self, statement_id ) : # type: ignore[override]
"""Reset data for prepared statement sent as long data
The result is a dictionary with OK packet information.
@@ -1551,7 +1550,7 @@ class MySQLConnection(MySQLConnectionAbs
"""
self._handle_ok(self._send_cmd(ServerCmd.STMT_RESET, int4store(statement_id)))
- def cmd_reset_connection(self) -> bool:
+ def cmd_reset_connection(self) :
"""Resets the session state without re-authenticating
Reset command only works on MySQL server 5.7.3 or later.
@@ -1566,7 +1565,7 @@ class MySQLConnection(MySQLConnectionAbs
except (NotSupportedError, OperationalError):
return False
- def handle_unread_result(self) -> None:
+ def handle_unread_result(self) :
"""Check whether there is an unread result"""
if self.can_consume_results:
self.consume_results()
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/cursor.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/cursor.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/cursor.py
@@ -29,7 +29,6 @@
# mypy: disable-error-code="assignment,arg-type,attr-defined,index,override,call-overload"
"""Cursor classes."""
-from __future__ import annotations
import re
import unicodedata
@@ -116,7 +115,7 @@ ERR_NO_RESULT_TO_FETCH = "No result set
MAX_RESULTS = 4294967295
-def is_eol_comment(stmt: bytes) -> bool:
+def is_eol_comment(stmt ) :
"""Checks if statement is an end-of-line comment.
Double-dash comment style requires the second dash to be
@@ -144,7 +143,7 @@ def is_eol_comment(stmt: bytes) -> bool:
return is_double_dash_comment or is_hash_comment
-def parse_multi_statement_query(multi_stmt: bytes) -> Deque[bytes]:
+def parse_multi_statement_query(multi_stmt ) :
"""Parses a multi-statement query/operation.
Parsing consists of removing empty (which includes just whitespaces and/or control
@@ -165,7 +164,7 @@ def parse_multi_statement_query(multi_st
ASCII whitespaces. Also, they aren't EOL comments except
perhaps for the last one.
"""
- executed_list: Deque[bytes] = deque(RE_SQL_SPLIT_STMTS.split(multi_stmt))
+ executed_list = deque(RE_SQL_SPLIT_STMTS.split(multi_stmt))
stmt, num_stms = b"", len(executed_list)
while num_stms > 0:
num_stms -= 1
@@ -186,11 +185,11 @@ class _ParamSubstitutor:
Substitutes parameters into SQL statement.
"""
- def __init__(self, params: Sequence[bytes]) -> None:
- self.params: Sequence[bytes] = params
- self.index: int = 0
+ def __init__(self, params ) :
+ self.params = params
+ self.index = 0
- def __call__(self, matchobj: re.Match) -> bytes:
+ def __call__(self, matchobj ) :
index = self.index
self.index += 1
try:
@@ -201,12 +200,12 @@ class _ParamSubstitutor:
) from None
@property
- def remaining(self) -> int:
+ def remaining(self) :
"""Returns number of parameters remaining to be substituted"""
return len(self.params) - self.index
-def _bytestr_format_dict(bytestr: bytes, value_dict: Dict[bytes, bytes]) -> bytes:
+def _bytestr_format_dict(bytestr , value_dict ) :
"""
>>> _bytestr_format_dict(b'%(a)s', {b'a': b'foobar'})
b'foobar
@@ -219,9 +218,9 @@ def _bytestr_format_dict(bytestr: bytes,
b'x=%(y)s y=%(x)s'
"""
- def replace(matchobj: re.Match) -> bytes:
+ def replace(matchobj ) :
"""Replace pattern."""
- value: Optional[bytes] = None
+ value = None
groups = matchobj.groupdict()
if groups["conversion_type"] == b"%":
value = b"%"
@@ -251,38 +250,38 @@ class MySQLCursor(MySQLCursorAbstract):
Implements the Python Database API Specification v2.0 (PEP-249)
"""
- def __init__(self, connection: Optional[MySQLConnection] = None) -> None:
+ def __init__(self, connection = None) :
"""Initialize"""
super().__init__(connection)
- self._connection: MySQLConnection = cast("MySQLConnection", self._connection)
+ self._connection = cast("MySQLConnection", self._connection)
- def __iter__(self) -> Iterator[RowType]:
+ def __iter__(self) :
"""
Iteration over the result set which calls self.fetchone()
and returns the next row.
"""
return iter(self.fetchone, None)
- def _reset_result(self) -> None:
+ def _reset_result(self) :
"""Reset the cursor to default"""
- self._rowcount: int = -1
+ self._rowcount = -1
self._nextrow = (None, None)
- self._stored_results: List[MySQLCursor] = []
- self._warnings: Optional[List[WarningType]] = None
- self._warning_count: int = 0
- self._description: Optional[List[DescriptionType]] = None
- self._executed: Optional[bytes] = None
- self._executed_list: List[bytes] = []
+ self._stored_results = []
+ self._warnings = None
+ self._warning_count = 0
+ self._description = None
+ self._executed = None
+ self._executed_list = []
self.reset()
- def _have_unread_result(self) -> bool:
+ def _have_unread_result(self) :
"""Check whether there is an unread result"""
try:
return self._connection.unread_result
except AttributeError:
return False
- def _check_executed(self) -> None:
+ def _check_executed(self) :
"""Check if the statement has been executed.
Raises an error if the statement has not been executed.
@@ -290,7 +289,7 @@ class MySQLCursor(MySQLCursorAbstract):
if self._executed is None:
raise InterfaceError(ERR_NO_RESULT_TO_FETCH)
- def __next__(self) -> RowType:
+ def __next__(self) :
"""
Used for iterating over the result set. Calles self.fetchone()
to get the next row.
@@ -303,7 +302,7 @@ class MySQLCursor(MySQLCursorAbstract):
raise StopIteration
return row
- def close(self) -> bool:
+ def close(self) :
"""Close the cursor
Returns True when successful, otherwise False.
@@ -318,10 +317,10 @@ class MySQLCursor(MySQLCursorAbstract):
return True
def _process_params_dict(
- self, params: ParamsDictType
- ) -> Dict[bytes, Union[bytes, Decimal]]:
+ self, params
+ ) :
"""Process query parameters given as dictionary"""
- res: Dict[bytes, Any] = {}
+ res = {}
try:
sql_mode = self._connection.sql_mode
to_mysql = self._connection.converter.to_mysql
@@ -341,8 +340,8 @@ class MySQLCursor(MySQLCursorAbstract):
return res
def _process_params(
- self, params: ParamsSequenceType
- ) -> Tuple[Union[bytes, Decimal], ...]:
+ self, params
+ ) :
"""Process query parameters."""
res = params[:]
try:
@@ -362,7 +361,7 @@ class MySQLCursor(MySQLCursorAbstract):
) from err
return tuple(res)
- def _handle_noresultset(self, res: ResultType) -> None:
+ def _handle_noresultset(self, res ) :
"""Handles result of execute() when there is no result set"""
try:
self._rowcount = res["affected_rows"]
@@ -373,7 +372,7 @@ class MySQLCursor(MySQLCursorAbstract):
self._handle_warnings()
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
"""Handles result set
This method handles the result set and is called after reading
@@ -381,7 +380,7 @@ class MySQLCursor(MySQLCursorAbstract):
cursors, this method is usually doing nothing.
"""
- def _handle_result(self, result: ResultType) -> None:
+ def _handle_result(self, result ) :
"""
Handle the result after a command was send. The result can be either
an OK-packet or a dictionary containing column/eof information.
@@ -405,8 +404,8 @@ class MySQLCursor(MySQLCursorAbstract):
raise InterfaceError("Invalid result")
def _execute_iter(
- self, query_iter: Generator[ResultType, None, None]
- ) -> Generator[MySQLCursor, None, None]:
+ self, query_iter
+ ) :
"""Generator returns MySQLCursor objects for multiple statements
This method is only used when multiple statements are executed
@@ -469,10 +468,10 @@ class MySQLCursor(MySQLCursorAbstract):
def execute(
self,
- operation: StrOrBytes,
- params: Optional[ParamsSequenceOrDictType] = None,
- multi: bool = False,
- ) -> Optional[Generator[MySQLCursor, None, None]]:
+ operation ,
+ params = None,
+ multi = False,
+ ) :
"""Executes the given operation
Executes the given operation substituting any markers with
@@ -502,7 +501,7 @@ class MySQLCursor(MySQLCursorAbstract):
self._connection.handle_unread_result()
self._reset_result()
- stmt: StrOrBytes = ""
+ stmt = ""
try:
if not isinstance(operation, (bytes, bytearray)):
@@ -544,11 +543,11 @@ class MySQLCursor(MySQLCursorAbstract):
return None
def _batch_insert(
- self, operation: str, seq_params: Sequence[ParamsSequenceOrDictType]
- ) -> Optional[bytes]:
+ self, operation , seq_params
+ ) :
"""Implements multi row insert"""
- def remove_comments(match: re.Match) -> str:
+ def remove_comments(match ) :
"""Remove comments from INSERT statements.
This function is used while removing comments from INSERT
@@ -600,8 +599,8 @@ class MySQLCursor(MySQLCursorAbstract):
raise InterfaceError(f"Failed executing the operation; {err}") from None
def executemany(
- self, operation: str, seq_params: Sequence[ParamsSequenceOrDictType]
- ) -> Optional[Generator[MySQLCursor, None, None]]:
+ self, operation , seq_params
+ ) :
"""Execute the given operation multiple times
The executemany() method will execute the operation iterating
@@ -654,7 +653,7 @@ class MySQLCursor(MySQLCursorAbstract):
self._rowcount = rowcnt
return None
- def stored_results(self) -> Iterator[MySQLCursor]:
+ def stored_results(self) :
"""Returns an iterator for stored results
This method returns an iterator over results which are stored when
@@ -667,9 +666,9 @@ class MySQLCursor(MySQLCursorAbstract):
def callproc(
self,
- procname: str,
- args: Sequence = (),
- ) -> Optional[Union[Dict[str, RowItemType], RowType]]:
+ procname ,
+ args = (),
+ ) :
"""Calls a stored procedure with the given arguments
The arguments will be set during this session, meaning
@@ -788,7 +787,7 @@ class MySQLCursor(MySQLCursorAbstract):
except Exception as err:
raise InterfaceError(f"Failed calling stored routine; {err}") from None
- def getlastrowid(self) -> Optional[int]:
+ def getlastrowid(self) :
"""Returns the value generated for an AUTO_INCREMENT column
Returns the value generated for an AUTO_INCREMENT column by
@@ -798,7 +797,7 @@ class MySQLCursor(MySQLCursorAbstract):
"""
return self._last_insert_id
- def _fetch_warnings(self) -> Optional[List[WarningType]]:
+ def _fetch_warnings(self) :
"""
Fetch warnings doing a SHOW WARNINGS. Can be called after getting
the result.
@@ -819,7 +818,7 @@ class MySQLCursor(MySQLCursorAbstract):
return None
- def _handle_warnings(self) -> None:
+ def _handle_warnings(self) :
"""Handle possible warnings after all results are consumed.
Raises:
@@ -842,14 +841,14 @@ class MySQLCursor(MySQLCursorAbstract):
warnings.warn(err, stacklevel=4)
- def _handle_eof(self, eof: EofPacketType) -> None:
+ def _handle_eof(self, eof ) :
"""Handle EOF packet"""
self._connection.unread_result = False
self._nextrow = (None, None)
self._warning_count = eof["warning_count"]
self._handle_warnings()
- def _fetch_row(self, raw: bool = False) -> Optional[RowType]:
+ def _fetch_row(self, raw = False) :
"""Returns the next row in the result set
Returns a tuple or None.
@@ -881,7 +880,7 @@ class MySQLCursor(MySQLCursorAbstract):
return row
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -890,7 +889,7 @@ class MySQLCursor(MySQLCursorAbstract):
self._check_executed()
return self._fetch_row()
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -910,7 +909,7 @@ class MySQLCursor(MySQLCursorAbstract):
res.append(row)
return res
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -932,7 +931,7 @@ class MySQLCursor(MySQLCursorAbstract):
return rows
@property
- def column_names(self) -> Tuple[str, ...]:
+ def column_names(self) :
"""Returns column names
This property returns the columns names as a tuple.
@@ -944,7 +943,7 @@ class MySQLCursor(MySQLCursorAbstract):
return tuple(d[0] for d in self.description)
@property
- def statement(self) -> Optional[str]:
+ def statement(self) :
"""Returns the executed statement
This property returns the executed statement. When multiple
@@ -959,7 +958,7 @@ class MySQLCursor(MySQLCursorAbstract):
return self._executed.strip() # type: ignore[return-value]
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
"""Returns whether the cursor could have rows returned
This property returns True when column descriptions are available
@@ -971,7 +970,7 @@ class MySQLCursor(MySQLCursorAbstract):
return False
return True
- def __str__(self) -> str:
+ def __str__(self) :
fmt = "{class_name}: {stmt}"
if self._executed:
try:
@@ -988,12 +987,12 @@ class MySQLCursor(MySQLCursorAbstract):
class MySQLCursorBuffered(MySQLCursor):
"""Cursor which fetches rows within execute()"""
- def __init__(self, connection: Optional[MySQLConnection] = None) -> None:
+ def __init__(self, connection = None) :
super().__init__(connection)
- self._rows: Optional[List[RowType]] = None
- self._next_row: int = 0
+ self._rows = None
+ self._next_row = 0
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
(self._rows, eof) = self._connection.get_rows()
self._rowcount = len(self._rows)
self._handle_eof(eof)
@@ -1003,10 +1002,10 @@ class MySQLCursorBuffered(MySQLCursor):
except AttributeError:
pass
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
self._rows = None
- def _fetch_row(self, raw: bool = False) -> Optional[RowType]:
+ def _fetch_row(self, raw = False) :
row = None
try:
row = self._rows[self._next_row]
@@ -1015,7 +1014,7 @@ class MySQLCursorBuffered(MySQLCursor):
self._next_row += 1
return row
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1024,7 +1023,7 @@ class MySQLCursorBuffered(MySQLCursor):
self._check_executed()
return self._fetch_row()
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1037,7 +1036,7 @@ class MySQLCursorBuffered(MySQLCursor):
self._next_row = len(self._rows)
return res
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1059,7 +1058,7 @@ class MySQLCursorBuffered(MySQLCursor):
return res
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
return self._rows is not None
@@ -1068,11 +1067,11 @@ class MySQLCursorRaw(MySQLCursor):
Skips conversion from MySQL datatypes to Python types when fetching rows.
"""
- def __init__(self, connection: Optional[MySQLConnection] = None) -> None:
+ def __init__(self, connection = None) :
super().__init__(connection)
- self._raw: bool = True
+ self._raw = True
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1081,7 +1080,7 @@ class MySQLCursorRaw(MySQLCursor):
self._check_executed()
return self._fetch_row(raw=self._raw)
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1107,11 +1106,11 @@ class MySQLCursorBufferedRaw(MySQLCursor
fetching rows and fetches rows within execute().
"""
- def __init__(self, connection: Optional[MySQLConnection] = None) -> None:
+ def __init__(self, connection = None) :
super().__init__(connection)
- self._raw: bool = True
+ self._raw = True
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
(self._rows, eof) = self._connection.get_rows(raw=self._raw)
self._rowcount = len(self._rows)
self._handle_eof(eof)
@@ -1121,7 +1120,7 @@ class MySQLCursorBufferedRaw(MySQLCursor
except AttributeError:
pass
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1130,7 +1129,7 @@ class MySQLCursorBufferedRaw(MySQLCursor
self._check_executed()
return self._fetch_row()
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1140,24 +1139,24 @@ class MySQLCursorBufferedRaw(MySQLCursor
return list(self._rows[self._next_row :])
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
return self._rows is not None
class MySQLCursorPrepared(MySQLCursor):
"""Cursor using MySQL Prepared Statements"""
- def __init__(self, connection: Optional[MySQLConnection] = None):
+ def __init__(self, connection = None):
super().__init__(connection)
- self._rows: Optional[List[RowType]] = None
- self._next_row: int = 0
- self._prepared: Optional[Dict[str, Union[int, List[DescriptionType]]]] = None
- self._binary: bool = True
- self._have_result: Optional[bool] = None
- self._last_row_sent: bool = False
- self._cursor_exists: bool = False
+ self._rows = None
+ self._next_row = 0
+ self._prepared = None
+ self._binary = True
+ self._have_result = None
+ self._last_row_sent = False
+ self._cursor_exists = False
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
if self._prepared:
try:
self._connection.cmd_stmt_close(self._prepared["statement_id"])
@@ -1168,29 +1167,29 @@ class MySQLCursorPrepared(MySQLCursor):
self._last_row_sent = False
self._cursor_exists = False
- def _handle_noresultset(self, res: ResultType) -> None:
+ def _handle_noresultset(self, res ) :
self._handle_server_status(res.get("status_flag", res.get("server_status", 0)))
super()._handle_noresultset(res)
- def _handle_server_status(self, flags: int) -> None:
+ def _handle_server_status(self, flags ) :
"""Check for SERVER_STATUS_CURSOR_EXISTS and
SERVER_STATUS_LAST_ROW_SENT flags set by the server.
"""
self._cursor_exists = flags & ServerFlag.STATUS_CURSOR_EXISTS != 0
self._last_row_sent = flags & ServerFlag.STATUS_LAST_ROW_SENT != 0
- def _handle_eof(self, eof: EofPacketType) -> None:
+ def _handle_eof(self, eof ) :
self._handle_server_status(eof.get("status_flag", eof.get("server_status", 0)))
super()._handle_eof(eof)
- def callproc(self, procname: Any, args: Any = ()) -> NoReturn:
+ def callproc(self, procname , args = ()) :
"""Calls a stored procedue
Not supported with MySQLCursorPrepared.
"""
raise NotSupportedError()
- def close(self) -> None:
+ def close(self) :
"""Close the cursor
This method will try to deallocate the prepared statement and close
@@ -1199,14 +1198,14 @@ class MySQLCursorPrepared(MySQLCursor):
self.reset()
super().close()
- def _row_to_python(self, rowdata: Any, desc: Any = None) -> Any:
+ def _row_to_python(self, rowdata , desc = None) :
"""Convert row data from MySQL to Python types
The conversion is done while reading binary data in the
protocol module.
"""
- def _handle_result(self, result: ResultType) -> None:
+ def _handle_result(self, result ) :
"""Handle result after execution"""
if isinstance(result, dict):
self._connection.unread_result = False
@@ -1224,10 +1223,10 @@ class MySQLCursorPrepared(MySQLCursor):
def execute(
self,
- operation: StrOrBytes,
- params: Optional[ParamsSequenceOrDictType] = None,
- multi: bool = False,
- ) -> None: # multi is unused
+ operation ,
+ params = None,
+ multi = False,
+ ) : # multi is unused
"""Prepare and execute a MySQL Prepared Statement
This method will prepare the given operation and execute it using
@@ -1309,9 +1308,9 @@ class MySQLCursorPrepared(MySQLCursor):
def executemany(
self,
- operation: str,
- seq_params: Sequence[ParamsSequenceType],
- ) -> None:
+ operation ,
+ seq_params ,
+ ) :
"""Prepare and execute a MySQL Prepared Statement many times
This method will prepare the given operation and execute with each
@@ -1333,7 +1332,7 @@ class MySQLCursorPrepared(MySQLCursor):
raise InterfaceError(f"Failed executing the operation; {err}") from None
self._rowcount = rowcnt
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1344,7 +1343,7 @@ class MySQLCursorPrepared(MySQLCursor):
self._connection.cmd_stmt_fetch(self._prepared["statement_id"])
return self._fetch_row() or None
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1364,7 +1363,7 @@ class MySQLCursorPrepared(MySQLCursor):
res.append(row)
return res
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1402,16 +1401,16 @@ class MySQLCursorDict(MySQLCursor):
def _row_to_python(
self,
- rowdata: RowType,
- desc: Optional[List[DescriptionType]] = None, # pylint: disable=unused-argument
- ) -> Optional[Dict[str, RowItemType]]:
+ rowdata ,
+ desc = None, # pylint: disable=unused-argument
+ ) :
"""Convert a MySQL text result row to Python types
Returns a dictionary.
"""
return dict(zip(self.column_names, rowdata)) if rowdata else None
- def fetchone(self) -> Optional[Dict[str, RowItemType]]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1419,7 +1418,7 @@ class MySQLCursorDict(MySQLCursor):
"""
return self._row_to_python(super().fetchone(), self.description)
- def fetchall(self) -> List[Optional[Dict[str, RowItemType]]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1444,9 +1443,9 @@ class MySQLCursorNamedTuple(MySQLCursor)
def _row_to_python(
self,
- rowdata: RowType,
- desc: Optional[List[DescriptionType]] = None, # pylint: disable=unused-argument
- ) -> Optional[RowType]:
+ rowdata ,
+ desc = None, # pylint: disable=unused-argument
+ ) :
"""Convert a MySQL text result row to Python types
Returns a named tuple.
@@ -1463,7 +1462,7 @@ class MySQLCursorNamedTuple(MySQLCursor)
return named_tuple(*row)
return None
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1478,7 +1477,7 @@ class MySQLCursorNamedTuple(MySQLCursor)
else row
)
- def fetchall(self) -> List[Optional[RowType]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1496,7 +1495,7 @@ class MySQLCursorBufferedDict(MySQLCurso
Buffered Cursor fetching rows as dictionaries.
"""
- def fetchone(self) -> Optional[Dict[str, RowItemType]]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1508,7 +1507,7 @@ class MySQLCursorBufferedDict(MySQLCurso
return self._row_to_python(row, self.description)
return None
- def fetchall(self) -> List[Optional[Dict[str, RowItemType]]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1528,7 +1527,7 @@ class MySQLCursorBufferedNamedTuple(MySQ
Buffered Cursor fetching rows as named tuple.
"""
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1540,7 +1539,7 @@ class MySQLCursorBufferedNamedTuple(MySQ
return self._row_to_python(row, self.description)
return None
- def fetchall(self) -> List[Optional[RowType]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1573,7 +1572,7 @@ class MySQLCursorPreparedDict(MySQLCurso
4. MySQLCursor (base class)
"""
- def fetchmany(self, size: Optional[int] = None) -> List[Dict[str, RowItemType]]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1596,7 +1595,7 @@ class MySQLCursorPreparedNamedTuple(MySQ
This class is a blend of features from MySQLCursorNamedTuple and MySQLCursorPrepared
"""
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1619,11 +1618,11 @@ class MySQLCursorPreparedRaw(MySQLCursor
This class is a blend of features from MySQLCursorRaw and MySQLCursorPrepared
"""
- def __init__(self, connection: Optional[MySQLConnection] = None) -> None:
+ def __init__(self, connection = None) :
super().__init__(connection)
- self._raw: bool = True
+ self._raw = True
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1634,7 +1633,7 @@ class MySQLCursorPreparedRaw(MySQLCursor
self._connection.cmd_stmt_fetch(self._prepared["statement_id"])
return self._fetch_row(raw=self._raw) or None
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1654,7 +1653,7 @@ class MySQLCursorPreparedRaw(MySQLCursor
res.append(row)
return res
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/cursor_cext.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/cursor_cext.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/cursor_cext.py
@@ -29,7 +29,6 @@
# mypy: disable-error-code="assignment,override,union-attr"
"""Cursor classes using the C Extension."""
-from __future__ import annotations
import re
import warnings
@@ -102,11 +101,11 @@ class _ParamSubstitutor:
Substitutes parameters into SQL statement.
"""
- def __init__(self, params: Sequence[bytes]) -> None:
- self.params: Sequence[bytes] = params
- self.index: int = 0
+ def __init__(self, params ) :
+ self.params = params
+ self.index = 0
- def __call__(self, matchobj: object) -> bytes:
+ def __call__(self, matchobj ) :
index = self.index
self.index += 1
try:
@@ -117,7 +116,7 @@ class _ParamSubstitutor:
) from None
@property
- def remaining(self) -> int:
+ def remaining(self) :
"""Returns number of parameters remaining to be substituted"""
return len(self.params) - self.index
@@ -125,16 +124,16 @@ class _ParamSubstitutor:
class CMySQLCursor(MySQLCursorAbstract):
"""Default cursor for interacting with MySQL using C Extension"""
- def __init__(self, connection: CMySQLConnection) -> None:
+ def __init__(self, connection ) :
"""Initialize"""
super().__init__(connection)
- self._affected_rows: int = -1
- self._raw_as_string: bool = False
- self._buffered: bool = False
- self._connection: CMySQLConnection = cast("CMySQLConnection", self._connection)
+ self._affected_rows = -1
+ self._raw_as_string = False
+ self._buffered = False
+ self._connection = cast("CMySQLConnection", self._connection)
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
"""Reset the cursor
When free is True (default) the result will be freed.
@@ -142,18 +141,18 @@ class CMySQLCursor(MySQLCursorAbstract):
self._rowcount = -1
self._nextrow = None
self._affected_rows = -1
- self._last_insert_id: int = 0
- self._warning_count: int = 0
- self._warnings: Optional[List[WarningType]] = None
+ self._last_insert_id = 0
+ self._warning_count = 0
+ self._warnings = None
self._warnings = None
self._warning_count = 0
- self._description: Optional[List[DescriptionType]] = None
- self._executed_list: List[StrOrBytes] = []
+ self._description = None
+ self._executed_list = []
if free and self._connection:
self._connection.free_result()
super().reset()
- def _check_executed(self) -> None:
+ def _check_executed(self) :
"""Check if the statement has been executed.
Raises an error if the statement has not been executed.
@@ -161,7 +160,7 @@ class CMySQLCursor(MySQLCursorAbstract):
if self._executed is None:
raise InterfaceError(ERR_NO_RESULT_TO_FETCH)
- def _fetch_warnings(self) -> Optional[List[WarningType]]:
+ def _fetch_warnings(self) :
"""Fetch warnings
Fetch warnings doing a SHOW WARNINGS. Can be called after getting
@@ -192,7 +191,7 @@ class CMySQLCursor(MySQLCursorAbstract):
return None
- def _handle_warnings(self) -> None:
+ def _handle_warnings(self) :
"""Handle possible warnings after all results are consumed.
Raises:
@@ -212,7 +211,7 @@ class CMySQLCursor(MySQLCursorAbstract):
warnings.warn(str(err), stacklevel=4)
- def _handle_result(self, result: Union[CextEofPacketType, CextResultType]) -> None:
+ def _handle_result(self, result ) :
"""Handles the result after statement execution"""
if "columns" in result:
self._description = result["columns"]
@@ -225,10 +224,10 @@ class CMySQLCursor(MySQLCursorAbstract):
self._rowcount = -1
self._handle_warnings()
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
"""Handle a result set"""
- def _handle_eof(self) -> None:
+ def _handle_eof(self) :
"""Handle end of reading the result
Raises an Error on errors.
@@ -238,7 +237,7 @@ class CMySQLCursor(MySQLCursorAbstract):
if not self._connection.more_results:
self._connection.free_result()
- def _execute_iter(self) -> Generator[CMySQLCursor, None, None]:
+ def _execute_iter(self) :
"""Generator returns MySQLCursor objects for multiple statements.
This method is only used when multiple statements are executed
@@ -283,7 +282,7 @@ class CMySQLCursor(MySQLCursorAbstract):
executed_list = parse_multi_statement_query(multi_stmt=self._executed)
self._executed = None
stmt = b""
- result: bool = False
+ result = False
while True:
try:
if not stmt.upper().startswith(b"CALL") or not result:
@@ -311,10 +310,10 @@ class CMySQLCursor(MySQLCursorAbstract):
def execute(
self,
- operation: StrOrBytes,
- params: ParamsSequenceOrDictType = (),
- multi: bool = False,
- ) -> Optional[Generator[CMySQLCursor, None, None]]:
+ operation ,
+ params = (),
+ multi = False,
+ ) :
"""Execute given statement using given parameters
Deprecated: The multi argument is not needed and nextset() should
@@ -375,12 +374,12 @@ class CMySQLCursor(MySQLCursorAbstract):
def _batch_insert(
self,
- operation: str,
- seq_params: Sequence[ParamsSequenceOrDictType],
- ) -> Optional[bytes]:
+ operation ,
+ seq_params ,
+ ) :
"""Implements multi row insert"""
- def remove_comments(match: re.Match) -> str:
+ def remove_comments(match ) :
"""Remove comments from INSERT statements.
This function is used while removing comments from INSERT
@@ -433,9 +432,9 @@ class CMySQLCursor(MySQLCursorAbstract):
def executemany(
self,
- operation: str,
- seq_params: Sequence[ParamsSequenceOrDictType],
- ) -> Optional[Generator[CMySQLCursor, None, None]]:
+ operation ,
+ seq_params ,
+ ) :
"""Execute the given operation multiple times
The executemany() method will execute the operation iterating
@@ -499,18 +498,18 @@ class CMySQLCursor(MySQLCursorAbstract):
return None
@property
- def description(self) -> Optional[List[DescriptionType]]:
+ def description(self) :
"""Returns description of columns in a result"""
return self._description
@property
- def rowcount(self) -> int:
+ def rowcount(self) :
"""Returns the number of rows produced or affected"""
if self._rowcount == -1:
return self._affected_rows
return self._rowcount
- def close(self) -> bool:
+ def close(self) :
"""Close the cursor
The result will be freed.
@@ -525,9 +524,9 @@ class CMySQLCursor(MySQLCursorAbstract):
def callproc(
self,
- procname: str,
- args: Sequence = (),
- ) -> Optional[Union[Dict[str, RowItemType], RowType]]:
+ procname ,
+ args = (),
+ ) :
"""Calls a stored procedure with the given arguments"""
if not procname or not isinstance(procname, str):
raise ValueError("procname must be a string")
@@ -611,7 +610,7 @@ class CMySQLCursor(MySQLCursorAbstract):
except Exception as err:
raise InterfaceError(f"Failed calling stored routine; {err}") from None
- def nextset(self) -> Optional[bool]:
+ def nextset(self) :
"""Skip to the next available result set"""
if not self._connection.next_result():
self.reset(free=True)
@@ -626,7 +625,7 @@ class CMySQLCursor(MySQLCursorAbstract):
self._handle_result(self._connection.fetch_eof_columns())
return True
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -649,7 +648,7 @@ class CMySQLCursor(MySQLCursorAbstract):
# self._connection.handle_unread_result()
return rows[0]
- def fetchmany(self, size: int = 1) -> List[RowType]:
+ def fetchmany(self, size = 1) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -688,7 +687,7 @@ class CMySQLCursor(MySQLCursorAbstract):
self._rowcount += len(rows)
return rows
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -709,7 +708,7 @@ class CMySQLCursor(MySQLCursorAbstract):
self._rowcount += 1
return row[0]
- def __iter__(self) -> Iterator[RowType]:
+ def __iter__(self) :
"""Iteration over the result set
Iteration over the result set which calls self.fetchone()
@@ -717,7 +716,7 @@ class CMySQLCursor(MySQLCursorAbstract):
"""
return iter(self.fetchone, None)
- def stored_results(self) -> Generator[CMySQLCursor, None, None]:
+ def stored_results(self) :
"""Returns an iterator for stored results
This method returns an iterator over results which are stored when
@@ -731,7 +730,7 @@ class CMySQLCursor(MySQLCursorAbstract):
yield result # type: ignore[misc]
self._stored_results = []
- def __next__(self) -> RowType:
+ def __next__(self) :
"""Iteration over the result set
Used for iterating over the result set. Calls self.fetchone()
to get the next row.
@@ -747,7 +746,7 @@ class CMySQLCursor(MySQLCursorAbstract):
return row
@property
- def column_names(self) -> Tuple[str, ...]:
+ def column_names(self) :
"""Returns column names
This property returns the columns names as a tuple.
@@ -759,7 +758,7 @@ class CMySQLCursor(MySQLCursorAbstract):
return tuple(d[0] for d in self.description)
@property
- def statement(self) -> str:
+ def statement(self) :
"""Returns the executed statement
This property returns the executed statement. When multiple
@@ -772,7 +771,7 @@ class CMySQLCursor(MySQLCursorAbstract):
return self._executed.strip() # type: ignore[return-value]
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
"""Returns whether the cursor could have rows returned
This property returns True when column descriptions are available
@@ -784,7 +783,7 @@ class CMySQLCursor(MySQLCursorAbstract):
return True
return False
- def __str__(self) -> str:
+ def __str__(self) :
fmt = "{class_name}: {stmt}"
if self._executed:
try:
@@ -802,27 +801,27 @@ class CMySQLCursor(MySQLCursorAbstract):
class CMySQLCursorBuffered(CMySQLCursor):
"""Cursor using C Extension buffering results"""
- def __init__(self, connection: CMySQLConnection):
+ def __init__(self, connection ):
"""Initialize"""
super().__init__(connection)
- self._rows: Optional[List[RowType]] = None
- self._next_row: int = 0
+ self._rows = None
+ self._next_row = 0
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
"""Handle a result set"""
self._rows = self._connection.get_rows()[0]
self._next_row = 0
- self._rowcount: int = len(self._rows)
+ self._rowcount = len(self._rows)
self._handle_eof()
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
"""Reset the cursor to default"""
self._rows = None
self._next_row = 0
super().reset(free=free)
- def _fetch_row(self) -> Optional[RowType]:
+ def _fetch_row(self) :
"""Returns the next row in the result set
Returns a tuple or None.
@@ -835,7 +834,7 @@ class CMySQLCursorBuffered(CMySQLCursor)
self._next_row += 1
return row
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -846,7 +845,7 @@ class CMySQLCursorBuffered(CMySQLCursor)
self._next_row = len(self._rows)
return res
- def fetchmany(self, size: int = 1) -> List[RowType]:
+ def fetchmany(self, size = 1) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -868,7 +867,7 @@ class CMySQLCursorBuffered(CMySQLCursor)
break
return res
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -878,7 +877,7 @@ class CMySQLCursorBuffered(CMySQLCursor)
return self._fetch_row()
@property
- def with_rows(self) -> bool:
+ def with_rows(self) :
"""Returns whether the cursor could have rows returned
This property returns True when rows are available,
@@ -892,7 +891,7 @@ class CMySQLCursorBuffered(CMySQLCursor)
class CMySQLCursorRaw(CMySQLCursor):
"""Cursor using C Extension return raw results"""
- def __init__(self, connection: CMySQLConnection) -> None:
+ def __init__(self, connection ) :
super().__init__(connection)
self._raw = True
@@ -900,7 +899,7 @@ class CMySQLCursorRaw(CMySQLCursor):
class CMySQLCursorBufferedRaw(CMySQLCursorBuffered):
"""Cursor using C Extension buffering raw results"""
- def __init__(self, connection: CMySQLConnection):
+ def __init__(self, connection ):
super().__init__(connection)
self._raw = True
@@ -908,7 +907,7 @@ class CMySQLCursorBufferedRaw(CMySQLCurs
class CMySQLCursorDict(CMySQLCursor):
"""Cursor using C Extension returning rows as dictionaries"""
- def fetchone(self) -> Optional[Dict[str, RowItemType]]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -917,7 +916,7 @@ class CMySQLCursorDict(CMySQLCursor):
row = super().fetchone()
return dict(zip(self.column_names, row)) if row else None
- def fetchmany(self, size: int = 1) -> List[Dict[str, RowItemType]]:
+ def fetchmany(self, size = 1) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -931,7 +930,7 @@ class CMySQLCursorDict(CMySQLCursor):
res = super().fetchmany(size=size)
return [dict(zip(self.column_names, row)) for row in res]
- def fetchall(self) -> List[Dict[str, RowItemType]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -945,13 +944,13 @@ class CMySQLCursorDict(CMySQLCursor):
class CMySQLCursorBufferedDict(CMySQLCursorBuffered):
"""Cursor using C Extension buffering and returning rows as dictionaries"""
- def _fetch_row(self) -> Optional[Dict[str, RowItemType]]:
+ def _fetch_row(self) :
row = super()._fetch_row()
if row:
return dict(zip(self.column_names, row))
return None
- def fetchall(self) -> List[Dict[str, RowItemType]]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -964,9 +963,9 @@ class CMySQLCursorBufferedDict(CMySQLCur
class CMySQLCursorNamedTuple(CMySQLCursor):
"""Cursor using C Extension returning rows as named tuples"""
- named_tuple: Any = None
+ named_tuple = None
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
"""Handle a result set"""
super()._handle_resultset()
columns = tuple(self.column_names)
@@ -976,7 +975,7 @@ class CMySQLCursorNamedTuple(CMySQLCurso
self.named_tuple = namedtuple("Row", columns) # type: ignore[misc]
NAMED_TUPLE_CACHE[columns] = self.named_tuple
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -987,7 +986,7 @@ class CMySQLCursorNamedTuple(CMySQLCurso
return self.named_tuple(*row)
return None
- def fetchmany(self, size: int = 1) -> List[RowType]:
+ def fetchmany(self, size = 1) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1002,7 +1001,7 @@ class CMySQLCursorNamedTuple(CMySQLCurso
return []
return [self.named_tuple(*row) for row in res]
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1015,19 +1014,19 @@ class CMySQLCursorNamedTuple(CMySQLCurso
class CMySQLCursorBufferedNamedTuple(CMySQLCursorBuffered):
"""Cursor using C Extension buffering and returning rows as named tuples"""
- named_tuple: Any = None
+ named_tuple = None
- def _handle_resultset(self) -> None:
+ def _handle_resultset(self) :
super()._handle_resultset()
self.named_tuple = namedtuple("Row", self.column_names) # type: ignore[misc]
- def _fetch_row(self) -> Optional[RowType]:
+ def _fetch_row(self) :
row = super()._fetch_row()
if row:
return self.named_tuple(*row)
return None
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1040,20 +1039,20 @@ class CMySQLCursorBufferedNamedTuple(CMy
class CMySQLCursorPrepared(CMySQLCursor):
"""Cursor using MySQL Prepared Statements"""
- def __init__(self, connection: CMySQLConnection):
+ def __init__(self, connection ):
super().__init__(connection)
- self._rows: Optional[List[RowType]] = None
- self._rowcount: int = 0
- self._next_row: int = 0
- self._binary: bool = True
- self._stmt: Optional[CMySQLPrepStmt] = None
+ self._rows = None
+ self._rowcount = 0
+ self._next_row = 0
+ self._binary = True
+ self._stmt = None
- def _handle_eof(self) -> None:
+ def _handle_eof(self) :
"""Handle EOF packet"""
self._nextrow = (None, None)
self._handle_warnings()
- def _fetch_row(self, raw: bool = False) -> Optional[RowType]:
+ def _fetch_row(self, raw = False) :
"""Returns the next row in the result set
Returns a tuple or None.
@@ -1093,14 +1092,14 @@ class CMySQLCursorPrepared(CMySQLCursor)
return row
- def callproc(self, procname: Any, args: Any = None) -> NoReturn:
+ def callproc(self, procname , args = None) :
"""Calls a stored procedue
Not supported with CMySQLCursorPrepared.
"""
raise NotSupportedError()
- def close(self) -> None:
+ def close(self) :
"""Close the cursor
This method will try to deallocate the prepared statement and close
@@ -1112,7 +1111,7 @@ class CMySQLCursorPrepared(CMySQLCursor)
self._stmt = None
super().close()
- def reset(self, free: bool = True) -> None:
+ def reset(self, free = True) :
"""Resets the prepared statement."""
if self._stmt:
self._connection.cmd_stmt_reset(self._stmt)
@@ -1120,10 +1119,10 @@ class CMySQLCursorPrepared(CMySQLCursor)
def execute(
self,
- operation: StrOrBytes,
- params: Optional[ParamsSequenceOrDictType] = None,
- multi: bool = False,
- ) -> None: # multi is unused
+ operation ,
+ params = None,
+ multi = False,
+ ) : # multi is unused
"""Prepare and execute a MySQL Prepared Statement
This method will prepare the given operation and execute it using
@@ -1213,8 +1212,8 @@ class CMySQLCursorPrepared(CMySQLCursor)
self._handle_result(res)
def executemany(
- self, operation: str, seq_params: Sequence[ParamsSequenceType]
- ) -> None:
+ self, operation , seq_params
+ ) :
"""Prepare and execute a MySQL Prepared Statement many times
This method will prepare the given operation and execute with each
@@ -1234,7 +1233,7 @@ class CMySQLCursorPrepared(CMySQLCursor)
raise InterfaceError(f"Failed executing the operation; {err}") from err
self._rowcount = rowcnt
- def fetchone(self) -> Optional[RowType]:
+ def fetchone(self) :
"""Return next row of a query result set.
Returns:
@@ -1243,7 +1242,7 @@ class CMySQLCursorPrepared(CMySQLCursor)
self._check_executed()
return self._fetch_row() or None
- def fetchmany(self, size: Optional[int] = None) -> List[RowType]:
+ def fetchmany(self, size = None) :
"""Return the next set of rows of a query result set.
When no more rows are available, it returns an empty list.
@@ -1263,7 +1262,7 @@ class CMySQLCursorPrepared(CMySQLCursor)
res.append(row)
return res
- def fetchall(self) -> List[RowType]:
+ def fetchall(self) :
"""Return all rows of a query result set.
Returns:
@@ -1311,6 +1310,6 @@ class CMySQLCursorPreparedNamedTuple(CMy
class CMySQLCursorPreparedRaw(CMySQLCursorPrepared):
"""This class is a blend of features from CMySQLCursorRaw and CMySQLCursorPrepared"""
- def __init__(self, connection: CMySQLConnection):
+ def __init__(self, connection ):
super().__init__(connection)
self._raw = True
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/custom_types.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/custom_types.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/custom_types.py
@@ -27,7 +27,6 @@
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Custom Python types used by MySQL Connector/Python"""
-from __future__ import annotations
from typing import Type
@@ -35,15 +34,15 @@ from typing import Type
class HexLiteral(str):
"""Class holding MySQL hex literals"""
- charset: str = ""
- original: str = ""
+ charset = ""
+ original = ""
- def __new__(cls: Type[HexLiteral], str_: str, charset: str = "utf8") -> HexLiteral:
+ def __new__(cls , str_ , charset = "utf8") :
hexed = [f"{i:02x}" for i in str_.encode(charset)]
obj = str.__new__(cls, "".join(hexed))
obj.charset = charset
obj.original = str_
return obj
- def __str__(self) -> str:
+ def __str__(self) :
return "0x" + self
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/opentelemetry/instrumentation.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/opentelemetry/instrumentation.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/opentelemetry/instrumentation.py
@@ -30,7 +30,6 @@
# mypy: disable-error-code="no-redef"
# pylint: disable=protected-access,global-statement,invalid-name,unused-argument
-from __future__ import annotations
import functools
import re
@@ -82,10 +81,10 @@ from .constants import (
OPTION_CNX_TRACER,
)
-leading_comment_remover: re.Pattern = re.compile(r"^/\*.*?\*/")
+leading_comment_remover = re.compile(r"^/\*.*?\*/")
-def record_exception_event(span: trace.Span, exc: Optional[Exception]) -> None:
+def record_exception_event(span , exc ) :
"""Records an exeception event."""
if not span or not span.is_recording() or not exc:
return
@@ -94,7 +93,7 @@ def record_exception_event(span: trace.S
span.record_exception(exc)
-def end_span(span: trace.Span) -> None:
+def end_span(span ) :
"""Ends span."""
if not span or not span.is_recording():
return
@@ -102,7 +101,7 @@ def end_span(span: trace.Span) -> None:
span.end()
-def get_operation_name(operation: str) -> str:
+def get_operation_name(operation ) :
"""Parse query to extract operation name."""
if operation and isinstance(operation, str):
# Strip leading comments so we get the operation name.
@@ -111,10 +110,10 @@ def get_operation_name(operation: str) -
def set_connection_span_attrs(
- cnx: Optional["MySQLConnectionAbstract"],
- cnx_span: trace.Span,
- cnx_kwargs: Optional[Dict[str, Any]] = None,
-) -> None:
+ cnx ,
+ cnx_span ,
+ cnx_kwargs = None,
+) :
"""Defines connection span attributes. If `cnx` is None then we use `cnx_kwargs`
to get basic net information. Basic net attributes are defined such as:
@@ -146,7 +145,7 @@ def set_connection_span_attrs(
is_tcp = not cnx._unix_socket if cnx else "unix_socket" not in cnx_kwargs
- attrs: Dict[str, Any] = {
+ attrs = {
SpanAttributes.DB_SYSTEM: DB_SYSTEM,
SpanAttributes.NET_TRANSPORT: "ip_tcp" if is_tcp else "inproc",
NET_SOCK_FAMILY: "inet" if is_tcp else "unix",
@@ -195,10 +194,10 @@ def set_connection_span_attrs(
cnx_span.set_attributes(attrs)
-def with_cnx_span_attached(method: Callable) -> Callable:
+def with_cnx_span_attached(method ) :
"""Attach the connection span while executing the connection method."""
- def wrapper(cnx: "MySQLConnectionAbstract", *args: Any, **kwargs: Any) -> Any:
+ def wrapper(cnx , *args , **kwargs ) :
"""Connection span attacher decorator."""
with trace.use_span(
cnx._span, end_on_exit=False
@@ -208,14 +207,14 @@ def with_cnx_span_attached(method: Calla
return wrapper
-def with_cnx_query_span(method: Callable) -> Callable:
+def with_cnx_query_span(method ) :
"""Create a query span while executing the connection method."""
- def wrapper(cnx: TracedMySQLConnection, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(cnx , *args , **kwargs ) :
"""Query span creator decorator."""
logger.info("Creating query span for connection.%s", method.__name__)
- query_span_attributes: Dict = {
+ query_span_attributes = {
SpanAttributes.DB_SYSTEM: DB_SYSTEM,
SpanAttributes.DB_USER: cnx._user,
SpanAttributes.THREAD_ID: DEFAULT_THREAD_ID,
@@ -234,20 +233,20 @@ def with_cnx_query_span(method: Callable
return wrapper
-def with_cursor_query_span(method: Callable) -> Callable:
+def with_cursor_query_span(method ) :
"""Create a query span while executing the cursor method."""
- def wrapper(cur: TracedMySQLCursor, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(cur , *args , **kwargs ) :
"""Query span creator decorator."""
logger.info("Creating query span for cursor.%s", method.__name__)
- connection: "MySQLConnectionAbstract" = (
+ connection = (
getattr(cur._wrapped, "_connection")
if hasattr(cur._wrapped, "_connection")
else getattr(cur._wrapped, "_cnx")
)
- query_span_attributes: Dict = {
+ query_span_attributes = {
SpanAttributes.DB_SYSTEM: DB_SYSTEM,
SpanAttributes.DB_USER: connection._user,
SpanAttributes.THREAD_ID: DEFAULT_THREAD_ID,
@@ -270,10 +269,10 @@ class BaseMySQLTracer(ABC):
"""Base class that provides basic object wrapper functionality."""
@abstractmethod
- def __init__(self) -> None:
+ def __init__(self) :
"""Must be implemented by subclasses."""
- def __getattr__(self, attr: str) -> Any:
+ def __getattr__(self, attr ) :
"""Gets an attribute.
Attributes defined in the wrapper object have higher precedence
@@ -286,7 +285,7 @@ class BaseMySQLTracer(ABC):
# proxy to the wrapped object
return getattr(self._wrapped, attr)
- def __setattr__(self, name: str, value: Any) -> None:
+ def __setattr__(self, name , value ) :
if "_wrapped" not in self.__dict__:
self.__dict__["_wrapped"] = value
return
@@ -298,16 +297,16 @@ class BaseMySQLTracer(ABC):
# proxy to the wrapped object
self._wrapped.__setattr__(name, value)
- def __enter__(self) -> Any:
+ def __enter__(self) :
"""Magic method."""
self._wrapped.__enter__()
return self
- def __exit__(self, *args: Any, **kwargs: Any) -> None:
+ def __exit__(self, *args , **kwargs ) :
"""Magic method."""
self._wrapped.__exit__(*args, **kwargs)
- def get_wrapped_class(self) -> str:
+ def get_wrapped_class(self) :
"""Gets the wrapped class name."""
return self._wrapped.__class__.__name__
@@ -317,29 +316,29 @@ class TracedMySQLCursor(BaseMySQLTracer)
def __init__(
self,
- wrapped: "MySQLCursorAbstract",
- tracer: trace.Tracer,
- connection_span: trace.Span,
+ wrapped ,
+ tracer ,
+ connection_span ,
):
"""Constructor."""
- self._wrapped: "MySQLCursorAbstract" = wrapped
- self._tracer: trace.Tracer = tracer
- self._connection_span_link: trace.Link = trace.Link(
+ self._wrapped = wrapped
+ self._tracer = tracer
+ self._connection_span_link = trace.Link(
connection_span.get_span_context()
)
@with_cursor_query_span
- def execute(self, *args: Any, **kwargs: Any) -> Any:
+ def execute(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.execute(*args, **kwargs)
@with_cursor_query_span
- def executemany(self, *args: Any, **kwargs: Any) -> Any:
+ def executemany(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.executemany(*args, **kwargs)
@with_cursor_query_span
- def callproc(self, *args: Any, **kwargs: Any) -> Any:
+ def callproc(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.callproc(*args, **kwargs)
@@ -347,15 +346,15 @@ class TracedMySQLCursor(BaseMySQLTracer)
class TracedMySQLConnection(BaseMySQLTracer):
"""Wrapper class for a `MySQLConnection` or `CMySQLConnection` object."""
- def __init__(self, wrapped: "MySQLConnectionAbstract") -> None:
+ def __init__(self, wrapped ) :
"""Constructor."""
- self._wrapped: "MySQLConnectionAbstract" = wrapped
+ self._wrapped = wrapped
# call `sql_mode` so its value is cached internally and querying it does not
# interfere when recording query span events later.
_ = self._wrapped.sql_mode
- def cursor(self, *args: Any, **kwargs: Any) -> TracedMySQLCursor:
+ def cursor(self, *args , **kwargs ) :
"""Wraps the object method."""
return TracedMySQLCursor(
wrapped=self._wrapped.cursor(*args, **kwargs),
@@ -364,167 +363,167 @@ class TracedMySQLConnection(BaseMySQLTra
)
@with_cnx_query_span
- def cmd_change_user(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_change_user(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_change_user(*args, **kwargs)
@with_cnx_query_span
- def commit(self, *args: Any, **kwargs: Any) -> Any:
+ def commit(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.commit(*args, **kwargs)
@with_cnx_query_span
- def rollback(self, *args: Any, **kwargs: Any) -> Any:
+ def rollback(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.rollback(*args, **kwargs)
@with_cnx_query_span
- def cmd_query(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_query(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_query(*args, **kwargs)
@with_cnx_query_span
- def cmd_init_db(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_init_db(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_init_db(*args, **kwargs)
@with_cnx_query_span
- def cmd_refresh(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_refresh(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_refresh(*args, **kwargs)
@with_cnx_query_span
- def cmd_quit(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_quit(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_quit(*args, **kwargs)
@with_cnx_query_span
- def cmd_shutdown(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_shutdown(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_shutdown(*args, **kwargs)
@with_cnx_query_span
- def cmd_statistics(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_statistics(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_statistics(*args, **kwargs)
@with_cnx_query_span
- def cmd_process_kill(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_process_kill(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_process_kill(*args, **kwargs)
@with_cnx_query_span
- def cmd_debug(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_debug(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_debug(*args, **kwargs)
@with_cnx_query_span
- def cmd_ping(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_ping(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_ping(*args, **kwargs)
@property
@with_cnx_query_span
- def database(self) -> str:
+ def database(self) :
"""Instrument method."""
return self._wrapped.database
@with_cnx_query_span
- def is_connected(self, *args: Any, **kwargs: Any) -> Any:
+ def is_connected(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.is_connected(*args, **kwargs)
@with_cnx_query_span
- def reset_session(self, *args: Any, **kwargs: Any) -> Any:
+ def reset_session(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.reset_session(*args, **kwargs)
@with_cnx_query_span
- def ping(self, *args: Any, **kwargs: Any) -> Any:
+ def ping(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.ping(*args, **kwargs)
@with_cnx_query_span
- def info_query(self, *args: Any, **kwargs: Any) -> Any:
+ def info_query(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.info_query(*args, **kwargs)
@with_cnx_query_span
- def cmd_stmt_prepare(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_stmt_prepare(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_stmt_prepare(*args, **kwargs)
@with_cnx_query_span
- def cmd_stmt_execute(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_stmt_execute(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_stmt_execute(*args, **kwargs)
@with_cnx_query_span
- def cmd_stmt_close(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_stmt_close(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_stmt_close(*args, **kwargs)
@with_cnx_query_span
- def cmd_stmt_send_long_data(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_stmt_send_long_data(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_stmt_send_long_data(*args, **kwargs)
@with_cnx_query_span
- def cmd_stmt_reset(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_stmt_reset(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_stmt_reset(*args, **kwargs)
@with_cnx_query_span
- def cmd_reset_connection(self, *args: Any, **kwargs: Any) -> Any:
+ def cmd_reset_connection(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.cmd_reset_connection(*args, **kwargs)
@property
@with_cnx_query_span
- def time_zone(self) -> str:
+ def time_zone(self) :
"""Instrument method."""
return self._wrapped.time_zone
@property
@with_cnx_query_span
- def sql_mode(self) -> str:
+ def sql_mode(self) :
"""Instrument method."""
return self._wrapped.sql_mode
@property
@with_cnx_query_span
- def autocommit(self) -> bool:
+ def autocommit(self) :
"""Instrument method."""
return self._wrapped.autocommit
@autocommit.setter
@with_cnx_query_span
- def autocommit(self, value: bool) -> None:
+ def autocommit(self, value ) :
"""Instrument method."""
self._wrapped.autocommit = value
@with_cnx_query_span
- def set_charset_collation(self, *args: Any, **kwargs: Any) -> Any:
+ def set_charset_collation(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.set_charset_collation(*args, **kwargs)
@with_cnx_query_span
- def start_transaction(self, *args: Any, **kwargs: Any) -> Any:
+ def start_transaction(self, *args , **kwargs ) :
"""Instrument method."""
return self._wrapped.start_transaction(*args, **kwargs)
def _instrument_connect(
- connect: Callable[..., Union["MySQLConnectionAbstract", "PooledMySQLConnection"]],
- tracer_provider: Optional[trace.TracerProvider] = None,
-) -> Callable[..., Union["MySQLConnectionAbstract", "PooledMySQLConnection"]]:
+ connect ,
+ tracer_provider = None,
+) :
"""Retrurn the instrumented version of `connect`."""
# let's preserve `connect` identity.
@functools.wraps(connect)
def wrapper(
- *args: Any, **kwargs: Any
- ) -> Union["MySQLConnectionAbstract", "PooledMySQLConnection"]:
+ *args , **kwargs
+ ) :
"""Wraps the connection object returned by the method `connect`.
Instrumentation for PooledConnections is not supported.
@@ -568,9 +567,9 @@ def _instrument_connect(
class MySQLInstrumentor:
"""MySQL instrumentation supporting mysql-connector-python."""
- _instance: Optional[MySQLInstrumentor] = None
+ _instance = None
- def __new__(cls, *args: Any, **kwargs: Any) -> MySQLInstrumentor:
+ def __new__(cls, *args , **kwargs ) :
"""Singlenton.
Restricts the instantiation to a singular instance.
@@ -582,12 +581,12 @@ class MySQLInstrumentor:
setattr(cls._instance, "_original_connect", connector.connect)
return cls._instance
- def instrumentation_dependencies(self) -> Collection[str]:
+ def instrumentation_dependencies(self) :
"""Return a list of python packages with versions
that the will be instrumented (e.g., versions >= 8.1.0)."""
return [f"mysql-connector-python >= {FIRST_SUPPORTED_VERSION}"]
- def instrument(self, **kwargs: Any) -> None:
+ def instrument(self, **kwargs ) :
"""Instrument the library.
Args:
@@ -606,9 +605,9 @@ class MySQLInstrumentor:
def instrument_connection(
self,
- connection: "MySQLConnectionAbstract",
- tracer_provider: Optional[trace.TracerProvider] = None,
- ) -> "MySQLConnectionAbstract":
+ connection ,
+ tracer_provider = None,
+ ) :
"""Enable instrumentation in a MySQL connection.
Args:
@@ -646,7 +645,7 @@ class MySQLInstrumentor:
return TracedMySQLConnection(wrapped=connection) # type: ignore[return-value]
- def uninstrument(self, **kwargs: Any) -> None:
+ def uninstrument(self, **kwargs ) :
"""Uninstrument the library."""
# pylint: disable=unused-argument
if connector.connect == getattr(self, "_original_connect"):
@@ -655,8 +654,8 @@ class MySQLInstrumentor:
connector.connect = getattr(self, "_original_connect")
def uninstrument_connection(
- self, connection: "MySQLConnectionAbstract"
- ) -> "MySQLConnectionAbstract":
+ self, connection
+ ) :
"""Disable instrumentation in a MySQL connection.
Args:
Index: mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/pooling.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysql-connector-python/lib/mysql/connector/pooling.py
+++ mysql-connector-python-9.1.0-src/mysql-connector-python/lib/mysql/connector/pooling.py
@@ -27,7 +27,6 @@
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Implementing pooling of connections to MySQL servers."""
-from __future__ import annotations
import queue
import random
@@ -70,14 +69,14 @@ CNX_POOL_MAXSIZE = 32
CNX_POOL_MAXNAMESIZE = 64
CNX_POOL_NAMEREGEX = re.compile(r"[^a-zA-Z0-9._:\-*$#]")
ERROR_NO_CEXT = "MySQL Connector/Python C Extension not available"
-MYSQL_CNX_CLASS: Union[type, Tuple[type, ...]] = (
+MYSQL_CNX_CLASS = (
MySQLConnection if CMySQLConnection is None else (MySQLConnection, CMySQLConnection)
)
-_CONNECTION_POOLS: Dict[str, MySQLConnectionPool] = {}
+_CONNECTION_POOLS = {}
-def _get_pooled_connection(**kwargs: Any) -> PooledMySQLConnection:
+def _get_pooled_connection(**kwargs ) :
"""Return a pooled MySQL connection."""
# If no pool name specified, generate one
pool_name = (
@@ -107,8 +106,8 @@ def _get_pooled_connection(**kwargs: Any
def _get_failover_connection(
- **kwargs: Any,
-) -> Union[PooledMySQLConnection, MySQLConnectionAbstract]:
+ **kwargs ,
+) :
"""Return a MySQL connection and try to failover if needed.
An InterfaceError is raise when no MySQL is available. ValueError is
@@ -200,8 +199,8 @@ def _get_failover_connection(
def connect(
- *args: Any, **kwargs: Any
-) -> Union[PooledMySQLConnection, MySQLConnectionAbstract]:
+ *args , **kwargs
+) :
"""Creates or gets a MySQL connection object.
In its simpliest form, `connect()` will open a connection to a
@@ -323,7 +322,7 @@ def connect(
return MySQLConnection(*args, **kwargs)
-def generate_pool_name(**kwargs: Any) -> str:
+def generate_pool_name(**kwargs ) :
"""Generate a pool name
This function takes keyword arguments, usually the connection
@@ -366,7 +365,7 @@ class PooledMySQLConnection:
connection belongs.
"""
- def __init__(self, pool: MySQLConnectionPool, cnx: MySQLConnectionAbstract) -> None:
+ def __init__(self, pool , cnx ) :
"""Constructor.
Args:
@@ -377,25 +376,25 @@ class PooledMySQLConnection:
raise AttributeError("pool should be a MySQLConnectionPool")
if not isinstance(cnx, MYSQL_CNX_CLASS):
raise AttributeError("cnx should be a MySQLConnection")
- self._cnx_pool: MySQLConnectionPool = pool
- self._cnx: MySQLConnectionAbstract = cnx
+ self._cnx_pool = pool
+ self._cnx = cnx
- def __enter__(self) -> PooledMySQLConnection:
+ def __enter__(self) :
return self
def __exit__(
self,
- exc_type: Type[BaseException],
- exc_value: BaseException,
- traceback: TracebackType,
- ) -> None:
+ exc_type ,
+ exc_value ,
+ traceback ,
+ ) :
self.close()
- def __getattr__(self, attr: Any) -> Any:
+ def __getattr__(self, attr ) :
"""Calls attributes of the MySQLConnection instance"""
return getattr(self._cnx, attr)
- def close(self) -> None:
+ def close(self) :
"""Do not close, but adds connection back to pool.
For a pooled connection, close() does not actually close it but returns it
@@ -413,7 +412,7 @@ class PooledMySQLConnection:
self._cnx = None
@staticmethod
- def config(**kwargs: Any) -> NoReturn:
+ def config(**kwargs ) :
"""Configuration is done through the pool.
For pooled connections, the `config()` method raises a `PoolError`
@@ -426,7 +425,7 @@ class PooledMySQLConnection:
)
@property
- def pool_name(self) -> str:
+ def pool_name(self) :
"""Returns the name of the connection pool to which the connection belongs."""
return self._cnx_pool.pool_name
@@ -436,11 +435,11 @@ class MySQLConnectionPool:
def __init__(
self,
- pool_size: int = 5,
- pool_name: Optional[str] = None,
- pool_reset_session: bool = True,
- **kwargs: Any,
- ) -> None:
+ pool_size = 5,
+ pool_name = None,
+ pool_reset_session = True,
+ **kwargs ,
+ ) :
"""Constructor.
Initialize a MySQL connection pool with a maximum number of
@@ -472,13 +471,13 @@ class MySQLConnectionPool:
References:
[1]: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
"""
- self._pool_size: Optional[int] = None
- self._pool_name: Optional[str] = None
+ self._pool_size = None
+ self._pool_name = None
self._reset_session = pool_reset_session
self._set_pool_size(pool_size)
self._set_pool_name(pool_name or generate_pool_name(**kwargs))
- self._cnx_config: Dict[str, Any] = {}
- self._cnx_queue: queue.Queue[MySQLConnectionAbstract] = queue.Queue(
+ self._cnx_config = {}
+ self._cnx_queue = queue.Queue(
self._pool_size
)
self._config_version = uuid4()
@@ -491,21 +490,21 @@ class MySQLConnectionPool:
cnt += 1
@property
- def pool_name(self) -> str:
+ def pool_name(self) :
"""Returns the name of the connection pool."""
return self._pool_name
@property
- def pool_size(self) -> int:
+ def pool_size(self) :
"""Returns number of connections managed by the pool."""
return self._pool_size
@property
- def reset_session(self) -> bool:
+ def reset_session(self) :
"""Returns whether to reset session."""
return self._reset_session
- def set_config(self, **kwargs: Any) -> None:
+ def set_config(self, **kwargs ) :
"""Set the connection configuration for `MySQLConnectionAbstract` subclass instances.
This method sets the configuration used for creating `MySQLConnectionAbstract`
@@ -535,7 +534,7 @@ class MySQLConnectionPool:
except AttributeError as err:
raise PoolError(f"Connection configuration not valid: {err}") from err
- def _set_pool_size(self, pool_size: int) -> None:
+ def _set_pool_size(self, pool_size ) :
"""Set the size of the pool
This method sets the size of the pool but it will not resize the pool.
@@ -550,7 +549,7 @@ class MySQLConnectionPool:
)
self._pool_size = pool_size
- def _set_pool_name(self, pool_name: str) -> None:
+ def _set_pool_name(self, pool_name ) :
r"""Set the name of the pool.
This method checks the validity and sets the name of the pool.
@@ -564,7 +563,7 @@ class MySQLConnectionPool:
raise AttributeError(f"Pool name '{pool_name}' is too long")
self._pool_name = pool_name
- def _queue_connection(self, cnx: MySQLConnectionAbstract) -> None:
+ def _queue_connection(self, cnx ) :
"""Put connection back in the queue
This method is putting a connection back in the queue. It will not
@@ -583,7 +582,7 @@ class MySQLConnectionPool:
except queue.Full as err:
raise PoolError("Failed adding connection; queue is full") from err
- def add_connection(self, cnx: Optional[MySQLConnectionAbstract] = None) -> None:
+ def add_connection(self, cnx = None) :
"""Adds a connection to the pool.
This method instantiates a `MySQLConnection` using the configuration
@@ -634,7 +633,7 @@ class MySQLConnectionPool:
self._queue_connection(cnx)
- def get_connection(self) -> PooledMySQLConnection:
+ def get_connection(self) :
"""Gets a connection from the pool.
This method returns an PooledMySQLConnection instance which
@@ -670,7 +669,7 @@ class MySQLConnectionPool:
return PooledMySQLConnection(self, cnx)
- def _remove_connections(self) -> int:
+ def _remove_connections(self) :
"""Close all connections
This method closes all connections. It returns the number
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/connection.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/connection.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/connection.py
@@ -30,7 +30,6 @@
"""Implementation of communication for MySQL X servers."""
-from __future__ import annotations
from types import TracebackType
@@ -226,7 +225,7 @@ _SESS_OPTS = _SSL_OPTS + [
]
-def generate_pool_name(**kwargs: Any) -> str:
+def generate_pool_name(**kwargs ) :
"""Generate a pool name.
This function takes keyword arguments, usually the connection arguments and
@@ -254,7 +253,7 @@ def generate_pool_name(**kwargs: Any) ->
return "_".join(parts)
-def update_timeout_penalties_by_error(penalty_dict: Mapping[str, Any]) -> None:
+def update_timeout_penalties_by_error(penalty_dict ) :
"""Update the timeout penalties directory.
Update the timeout penalties by error dictionary used to deactivate a pool.
@@ -268,13 +267,13 @@ def update_timeout_penalties_by_error(pe
class SocketStream:
"""Implements a socket stream."""
- def __init__(self) -> None:
- self._socket: Optional[socket.socket] = None
- self._is_ssl: bool = False
- self._is_socket: bool = False
- self._host: Optional[str] = None
+ def __init__(self) :
+ self._socket = None
+ self._is_ssl = False
+ self._is_socket = False
+ self._host = None
- def connect(self, params: Tuple, connect_timeout: float = _CONNECT_TIMEOUT) -> None:
+ def connect(self, params , connect_timeout = _CONNECT_TIMEOUT) :
"""Connects to a TCP service.
Args:
@@ -298,7 +297,7 @@ class SocketStream:
raise InterfaceError("Unix socket unsupported") from None
self._socket.settimeout(None)
- def read(self, count: int) -> bytes:
+ def read(self, count ) :
"""Receive data from the socket.
Args:
@@ -318,7 +317,7 @@ class SocketStream:
count -= len(data)
return b"".join(buf)
- def sendall(self, data: bytes) -> None:
+ def sendall(self, data ) :
"""Send data to the socket.
Args:
@@ -331,7 +330,7 @@ class SocketStream:
except OSError as err:
raise OperationalError(f"Unexpected socket error: {err}") from err
- def close(self) -> None:
+ def close(self) :
"""Close the socket."""
if not self._socket:
return
@@ -343,19 +342,19 @@ class SocketStream:
pass
self._socket = None
- def __del__(self) -> None:
+ def __del__(self) :
self.close()
def set_ssl(
self,
- ssl_protos: List[str],
- ssl_mode: str,
- ssl_ca: str,
- ssl_crl: str,
- ssl_cert: str,
- ssl_key: str,
- ssl_ciphers: List[str],
- ) -> None:
+ ssl_protos ,
+ ssl_mode ,
+ ssl_ca ,
+ ssl_crl ,
+ ssl_cert ,
+ ssl_key ,
+ ssl_ciphers ,
+ ) :
"""Set SSL parameters.
Args:
@@ -445,7 +444,7 @@ class SocketStream:
warn_tls_version_deprecated(tls_version)
warn_ciphersuites_deprecated(cipher, tls_version)
- def is_ssl(self) -> bool:
+ def is_ssl(self) :
"""Verifies if SSL is being used.
Returns:
@@ -453,7 +452,7 @@ class SocketStream:
"""
return self._is_ssl
- def is_socket(self) -> bool:
+ def is_socket(self) :
"""Verifies if socket connection is being used.
Returns:
@@ -461,7 +460,7 @@ class SocketStream:
"""
return self._is_socket
- def is_secure(self) -> bool:
+ def is_secure(self) :
"""Verifies if connection is secure.
Returns:
@@ -469,7 +468,7 @@ class SocketStream:
"""
return self._is_ssl or self._is_socket
- def is_open(self) -> bool:
+ def is_open(self) :
"""Verifies if connection is open.
Returns:
@@ -478,7 +477,7 @@ class SocketStream:
return self._socket is not None
-def catch_network_exception(func: Callable) -> Callable:
+def catch_network_exception(func ) :
"""Decorator used to catch OSError or RuntimeError.
Raises:
@@ -487,7 +486,7 @@ def catch_network_exception(func: Callab
"""
@wraps(func)
- def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(self , *args , **kwargs ) :
"""Wrapper function."""
try:
if (
@@ -497,7 +496,7 @@ def catch_network_exception(func: Callab
raise InterfaceError(*self.get_disconnected_reason())
result = func(self, *args, **kwargs)
if isinstance(result, BaseResult):
- warns: Any = result.get_warnings()
+ warns = result.get_warnings()
for warn in warns:
if warn["code"] in CONNECTION_CLOSED_ERROR:
error_msg = CONNECTION_CLOSED_ERROR[warn["code"]]
@@ -548,12 +547,12 @@ class Router(dict):
.. versionadded:: 8.0.20
"""
- def __init__(self, connection_params: Mapping[str, Any]) -> None:
+ def __init__(self, connection_params ) :
super().__init__()
self.update(connection_params)
self["available"] = self.get("available", True)
- def available(self) -> bool:
+ def available(self) :
"""Verifies if the Router is available to open connections.
Returns:
@@ -561,11 +560,11 @@ class Router(dict):
"""
return self["available"]
- def set_unavailable(self) -> None:
+ def set_unavailable(self) :
"""Sets this Router unavailable to open connections."""
self["available"] = False
- def get_connection_params(self) -> Union[str, Tuple[str, Optional[int]]]:
+ def get_connection_params(self) :
"""Verifies if the Router is available to open connections.
Returns:
@@ -585,17 +584,17 @@ class RouterManager:
.. versionadded:: 8.0.20
"""
- def __init__(self, routers: List[Router], settings: Dict[str, Any]) -> None:
+ def __init__(self, routers , settings ) :
self._routers = routers
self._settings = settings
- self._cur_priority_idx: int = 0
- self._can_failover: bool = True
+ self._cur_priority_idx = 0
+ self._can_failover = True
# Reuters status
- self._routers_directory: Dict[int, List[Router]] = {}
- self.routers_priority_list: List[int] = []
+ self._routers_directory = {}
+ self.routers_priority_list = []
self._ensure_priorities()
- def _ensure_priorities(self) -> None:
+ def _ensure_priorities(self) :
"""Ensure priorities.
Raises:
@@ -630,7 +629,7 @@ class RouterManager:
else:
self._routers_directory[priority].append(Router(router))
- def _get_available_routers(self, priority: int) -> List[Router]:
+ def _get_available_routers(self, priority ) :
"""Get a list of the current available routers that shares the given priority.
Returns:
@@ -640,7 +639,7 @@ class RouterManager:
router_list = [router for router in router_list if router.available()]
return router_list
- def _get_random_connection_params(self, priority: int) -> Router:
+ def _get_random_connection_params(self, priority ) :
"""Get a random router from the group with the given priority.
Returns:
@@ -656,7 +655,7 @@ class RouterManager:
index = random.randint(0, last)
return router_list[index]
- def can_failover(self) -> bool:
+ def can_failover(self) :
"""Returns the next connection parameters.
Returns:
@@ -664,7 +663,7 @@ class RouterManager:
"""
return self._can_failover
- def get_next_router(self) -> Router:
+ def get_next_router(self) :
"""Returns the next connection parameters.
Returns:
@@ -699,7 +698,7 @@ class RouterManager:
return router
- def get_routers_directory(self) -> Dict[int, List[Router]]:
+ def get_routers_directory(self) :
"""Returns the directory containing all the routers managed.
Returns:
@@ -715,16 +714,16 @@ class Connection:
settings (dict): Dictionary with connection settings.
"""
- def __init__(self, settings: Dict[str, Any]) -> None:
- self.settings: Dict[str, Any] = settings
- self.stream: SocketStream = SocketStream()
- self.protocol: Optional[Protocol] = None
- self.keep_open: Optional[bool] = None
- self._user: Optional[str] = settings.get("user")
- self._password: Optional[str] = settings.get("password")
- self._schema: Optional[str] = settings.get("schema")
- self._active_result: Optional[ResultBaseType] = None
- self._routers: List[Router] = settings.get("routers", [])
+ def __init__(self, settings ) :
+ self.settings = settings
+ self.stream = SocketStream()
+ self.protocol = None
+ self.keep_open = None
+ self._user = settings.get("user")
+ self._password = settings.get("password")
+ self._schema = settings.get("schema")
+ self._active_result = None
+ self._routers = settings.get("routers", [])
if "host" in settings and settings["host"]:
self._routers.append(
@@ -734,8 +733,8 @@ class Connection:
}
)
- self.router_manager: RouterManager = RouterManager(self._routers, settings)
- self._connect_timeout: Optional[int] = settings.get(
+ self.router_manager = RouterManager(self._routers, settings)
+ self._connect_timeout = settings.get(
"connect-timeout", _CONNECT_TIMEOUT
)
if self._connect_timeout == 0:
@@ -743,19 +742,19 @@ class Connection:
# on socket operations
self._connect_timeout = None
- self._stmt_counter: int = 0
- self._prepared_stmt_ids: List[int] = []
- self._prepared_stmt_supported: bool = True
- self._server_disconnected: bool = False
- self._server_disconnected_reason: Optional[Union[str, Tuple[str, int]]] = None
+ self._stmt_counter = 0
+ self._prepared_stmt_ids = []
+ self._prepared_stmt_supported = True
+ self._server_disconnected = False
+ self._server_disconnected_reason = None
- def fetch_active_result(self) -> None:
+ def fetch_active_result(self) :
"""Fetch active result."""
if self._active_result is not None:
self._active_result.fetch_all()
self._active_result = None
- def set_active_result(self, result: ResultBaseType) -> None:
+ def set_active_result(self, result ) :
"""Set active result.
Args:
@@ -766,7 +765,7 @@ class Connection:
"""
self._active_result = result
- def connect(self) -> None:
+ def connect(self) :
"""Attempt to connect to the MySQL server.
Raises:
@@ -836,7 +835,7 @@ class Connection:
raise InterfaceError(f"Cannot connect to host: {error}")
raise InterfaceError("Unable to connect to any of the target hosts", 4001)
- def _set_tls_capabilities(self, caps: Dict[str, Any]) -> None:
+ def _set_tls_capabilities(self, caps ) :
"""Set the TLS capabilities.
Args:
@@ -892,10 +891,10 @@ class Connection:
def _set_compression_capabilities(
self,
- caps: Dict[str, Any],
- compression: str,
- algorithms: Optional[List[str]] = None,
- ) -> Optional[str]:
+ caps ,
+ compression ,
+ algorithms = None,
+ ) :
"""Set the compression capabilities.
If compression is available, negociates client and server algorithms.
@@ -989,7 +988,7 @@ class Connection:
self.protocol.set_capabilities(compression={"algorithm": algorithm})
return algorithm
- def _authenticate(self) -> None:
+ def _authenticate(self) :
"""Authenticate with the MySQL server."""
auth = self.settings.get("auth")
if auth:
@@ -1020,7 +1019,7 @@ class Connection:
f"password or try a secure connection err:{err}"
) from err
- def _authenticate_mysql41(self) -> None:
+ def _authenticate_mysql41(self) :
"""Authenticate with the MySQL server using `MySQL41AuthPlugin`."""
plugin = MySQL41AuthPlugin(self._user, self._password)
self.protocol.send_auth_start(plugin.auth_name())
@@ -1028,7 +1027,7 @@ class Connection:
self.protocol.send_auth_continue(plugin.auth_data(extra_data))
self.protocol.read_auth_ok()
- def _authenticate_plain(self) -> None:
+ def _authenticate_plain(self) :
"""Authenticate with the MySQL server using `PlainAuthPlugin`."""
if not self.stream.is_secure():
raise InterfaceError(
@@ -1038,7 +1037,7 @@ class Connection:
self.protocol.send_auth_start(plugin.auth_name(), auth_data=plugin.auth_data())
self.protocol.read_auth_ok()
- def _authenticate_sha256_memory(self) -> None:
+ def _authenticate_sha256_memory(self) :
"""Authenticate with the MySQL server using `Sha256MemoryAuthPlugin`."""
plugin = Sha256MemoryAuthPlugin(self._user, self._password)
self.protocol.send_auth_start(plugin.auth_name())
@@ -1046,7 +1045,7 @@ class Connection:
self.protocol.send_auth_continue(plugin.auth_data(extra_data))
self.protocol.read_auth_ok()
- def _deallocate_statement(self, statement: StatementType) -> None:
+ def _deallocate_statement(self, statement ) :
"""Deallocates statement.
Args:
@@ -1059,17 +1058,17 @@ class Connection:
def _prepare_statement(
self,
- msg_type: str,
- msg: MessageType,
- statement: Union[
- FindStatement,
- DeleteStatement,
- ModifyStatement,
- ReadStatement,
- RemoveStatement,
- UpdateStatement,
- ],
- ) -> None:
+ msg_type ,
+ msg ,
+ statement
+
+
+
+
+
+
+ ,
+ ) :
"""Prepares a statement.
Args:
@@ -1088,17 +1087,17 @@ class Connection:
def _execute_prepared_pipeline(
self,
- msg_type: str,
- msg: MessageType,
- statement: Union[
- FindStatement,
- DeleteStatement,
- ModifyStatement,
- ReadStatement,
- RemoveStatement,
- UpdateStatement,
- ],
- ) -> None:
+ msg_type ,
+ msg ,
+ statement
+
+
+
+
+
+
+ ,
+ ) :
"""Executes the prepared statement pipeline.
Args:
@@ -1149,7 +1148,7 @@ class Connection:
statement.increment_exec_counter()
@catch_network_exception
- def send_sql(self, statement: SqlStatement) -> SqlResult:
+ def send_sql(self, statement ) :
"""Execute a SQL statement.
Args:
@@ -1169,7 +1168,7 @@ class Connection:
return SqlResult(self)
@catch_network_exception
- def send_insert(self, statement: Union[AddStatement, InsertStatement]) -> Result:
+ def send_insert(self, statement ) :
"""Send an insert statement.
Args:
@@ -1190,8 +1189,8 @@ class Connection:
@catch_network_exception
def send_find(
- self, statement: Union[FindStatement, SelectStatement]
- ) -> Union[DocResult, RowResult]:
+ self, statement
+ ) :
"""Send an find statement.
Args:
@@ -1207,7 +1206,7 @@ class Connection:
return DocResult(self) if statement.is_doc_based() else RowResult(self)
@catch_network_exception
- def send_delete(self, statement: Union[DeleteStatement, RemoveStatement]) -> Result:
+ def send_delete(self, statement ) :
"""Send an delete statement.
Args:
@@ -1222,7 +1221,7 @@ class Connection:
return Result(self)
@catch_network_exception
- def send_update(self, statement: Union[ModifyStatement, UpdateStatement]) -> Result:
+ def send_update(self, statement ) :
"""Send an delete statement.
Args:
@@ -1239,11 +1238,11 @@ class Connection:
@catch_network_exception
def execute_nonquery(
self,
- namespace: str,
- cmd: str,
- raise_on_fail: bool,
- fields: Optional[Dict[str, Any]] = None,
- ) -> Optional[Result]:
+ namespace ,
+ cmd ,
+ raise_on_fail ,
+ fields = None,
+ ) :
"""Execute a non query command.
Args:
@@ -1270,7 +1269,7 @@ class Connection:
return None
@catch_network_exception
- def execute_sql_scalar(self, sql: StatementType) -> int:
+ def execute_sql_scalar(self, sql ) :
"""Execute a SQL scalar.
Args:
@@ -1291,7 +1290,7 @@ class Connection:
return result[0][0] # type: ignore[index]
@catch_network_exception
- def get_row_result(self, cmd: str, fields: Dict[str, Any]) -> RowResult:
+ def get_row_result(self, cmd , fields ) :
"""Returns the row result.
Args:
@@ -1306,7 +1305,7 @@ class Connection:
return RowResult(self)
@catch_network_exception
- def read_row(self, result: RowResult) -> Optional[MessageType]:
+ def read_row(self, result ) :
"""Read row.
Args:
@@ -1315,7 +1314,7 @@ class Connection:
return self.protocol.read_row(result)
@catch_network_exception
- def close_result(self, result: Result) -> None:
+ def close_result(self, result ) :
"""Close result.
Args:
@@ -1324,7 +1323,7 @@ class Connection:
self.protocol.close_result(result)
@catch_network_exception
- def get_column_metadata(self, result: Result) -> List[ColumnType]:
+ def get_column_metadata(self, result ) :
"""Get column metadata.
Args:
@@ -1332,7 +1331,7 @@ class Connection:
"""
return self.protocol.get_column_metadata(result)
- def get_next_statement_id(self) -> int:
+ def get_next_statement_id(self) :
"""Returns the next statement ID.
Returns:
@@ -1343,7 +1342,7 @@ class Connection:
self._stmt_counter += 1
return self._stmt_counter
- def is_open(self) -> bool:
+ def is_open(self) :
"""Check if connection is open.
Returns:
@@ -1351,7 +1350,7 @@ class Connection:
"""
return self.stream.is_open()
- def set_server_disconnected(self, reason: Union[str, Tuple[str, int]]) -> None:
+ def set_server_disconnected(self, reason ) :
"""Set the disconnection message from the server.
Args:
@@ -1360,7 +1359,7 @@ class Connection:
self._server_disconnected = True
self._server_disconnected_reason = reason
- def is_server_disconnected(self) -> bool:
+ def is_server_disconnected(self) :
"""Verify if the session has been disconnect from the server.
Returns:
@@ -1369,7 +1368,7 @@ class Connection:
"""
return self._server_disconnected
- def get_disconnected_reason(self) -> Optional[Union[str, Tuple[str, int]]]:
+ def get_disconnected_reason(self) :
"""Get the disconnection message sent by the server.
Returns:
@@ -1377,13 +1376,13 @@ class Connection:
"""
return self._server_disconnected_reason
- def disconnect(self) -> None:
+ def disconnect(self) :
"""Disconnect from server."""
if not self.is_open():
return
self.stream.close()
- def close_session(self) -> None:
+ def close_session(self) :
"""Close a sucessfully authenticated session."""
if not self.is_open():
return
@@ -1410,7 +1409,7 @@ class Connection:
# close the connection locally.
self.stream.close()
- def reset_session(self) -> None:
+ def reset_session(self) :
"""Reset a sucessfully authenticated session."""
if not self.is_open():
return
@@ -1425,7 +1424,7 @@ class Connection:
err,
)
- def close_connection(self) -> None:
+ def close_connection(self) :
"""Announce to the server that the client wants to close the
connection. Discards any session state of the server.
"""
@@ -1457,22 +1456,22 @@ class PooledConnection(Connection):
.. versionadded:: 8.0.13
"""
- def __init__(self, pool: ConnectionPool) -> None:
+ def __init__(self, pool ) :
if not isinstance(pool, ConnectionPool):
raise AttributeError("pool should be a ConnectionPool object")
super().__init__(pool.cnx_config)
- self.pool: ConnectionPool = pool
- self.host: str = pool.cnx_config["host"]
- self.port: int = pool.cnx_config["port"]
+ self.pool = pool
+ self.host = pool.cnx_config["host"]
+ self.port = pool.cnx_config["port"]
- def close_connection(self) -> None:
+ def close_connection(self) :
"""Closes the connection.
This method closes the socket.
"""
super().close_session()
- def close_session(self) -> None:
+ def close_session(self) :
"""Do not close, but add connection back to pool.
The close_session() method does not close the connection with the
@@ -1485,20 +1484,20 @@ class PooledConnection(Connection):
"""
self.pool.add_connection(self)
- def reconnect(self) -> None:
+ def reconnect(self) :
"""Reconnect this connection."""
if self._active_result is not None:
self._active_result.fetch_all()
self._authenticate()
- def reset(self) -> None:
+ def reset(self) :
"""Reset the connection.
Resets the connection by re-authenticate.
"""
self.reconnect()
- def sql(self, sql: str) -> SqlStatement:
+ def sql(self, sql ) :
"""Creates a :class:`mysqlx.SqlStatement` object to allow running the
SQL statement on the target MySQL Server.
@@ -1540,27 +1539,27 @@ class ConnectionPool(queue.Queue):
.. versionadded:: 8.0.13
"""
- def __init__(self, name: str, **kwargs: Any) -> None:
- self.name: Optional[str] = None
+ def __init__(self, name , **kwargs ) :
+ self.name = None
self._set_pool_name(name)
- self._open_sessions: int = 0
- self._connections_openned: List[PooledConnection] = []
- self._available: bool = True
- self._timeout: int = 0
- self._timeout_stamp: datetime = datetime.now()
- self.pool_max_size: int = kwargs.get("max_size", 25)
+ self._open_sessions = 0
+ self._connections_openned = []
+ self._available = True
+ self._timeout = 0
+ self._timeout_stamp = datetime.now()
+ self.pool_max_size = kwargs.get("max_size", 25)
# Can't invoke super due to Queue not is a new-style class
queue.Queue.__init__(self, self.pool_max_size)
- self.reset_session: bool = kwargs.get("reset_session", True)
- self.max_idle_time: int = kwargs.get("max_idle_time", 25)
- self.settings: Dict[str, Any] = kwargs
- self.queue_timeout: int = kwargs.get("queue_timeout", 25)
- self.priority: int = kwargs.get("priority", 0)
- self.cnx_config: Dict[str, Any] = kwargs
- self.host: str = kwargs["host"]
- self.port: int = kwargs["port"]
+ self.reset_session = kwargs.get("reset_session", True)
+ self.max_idle_time = kwargs.get("max_idle_time", 25)
+ self.settings = kwargs
+ self.queue_timeout = kwargs.get("queue_timeout", 25)
+ self.priority = kwargs.get("priority", 0)
+ self.cnx_config = kwargs
+ self.host = kwargs["host"]
+ self.port = kwargs["port"]
- def _set_pool_name(self, pool_name: str) -> None:
+ def _set_pool_name(self, pool_name ) :
r"""Set the name of the pool.
This method checks the validity and sets the name of the pool.
@@ -1580,11 +1579,11 @@ class ConnectionPool(queue.Queue):
self.name = pool_name
@property
- def open_connections(self) -> int:
+ def open_connections(self) :
"""Returns the number of open connections that can return to this pool."""
return len(self._connections_openned)
- def remove_connection(self, cnx: Optional[PooledConnection] = None) -> None:
+ def remove_connection(self, cnx = None) :
"""Removes a connection from this pool.
Args:
@@ -1592,7 +1591,7 @@ class ConnectionPool(queue.Queue):
"""
self._connections_openned.remove(cnx)
- def remove_connections(self) -> None:
+ def remove_connections(self) :
"""Removes all the connections from the pool."""
while self.qsize() > 0:
try:
@@ -1607,7 +1606,7 @@ class ConnectionPool(queue.Queue):
finally:
self.remove_connection(cnx)
- def add_connection(self, cnx: Optional[PooledConnection] = None) -> None:
+ def add_connection(self, cnx = None) :
"""Adds a connection to this pool.
This method instantiates a Connection using the configuration passed
@@ -1649,7 +1648,7 @@ class ConnectionPool(queue.Queue):
self.queue_connection(cnx)
- def queue_connection(self, cnx: PooledConnection) -> None:
+ def queue_connection(self, cnx ) :
"""Put connection back in the queue:
This method is putting a connection back in the queue.
@@ -1673,14 +1672,14 @@ class ConnectionPool(queue.Queue):
except queue.Full as err:
raise PoolError("Failed adding connection; queue is full") from err
- def track_connection(self, connection: PooledConnection) -> None:
+ def track_connection(self, connection ) :
"""Tracks connection in order of close it when client.close() is invoke."""
self._connections_openned.append(connection)
- def __str__(self) -> str:
+ def __str__(self) :
return self.name
- def available(self) -> bool:
+ def available(self) :
"""Returns if this pool is available for pool connections from it.
Returns:
@@ -1689,7 +1688,7 @@ class ConnectionPool(queue.Queue):
"""
return self._available
- def set_unavailable(self, time_out: int = -1) -> None:
+ def set_unavailable(self, time_out = -1) :
"""Sets this pool unavailable for a period of time (in seconds).
.. versionadded:: 8.0.20
@@ -1704,7 +1703,7 @@ class ConnectionPool(queue.Queue):
self._timeout_stamp = datetime.now()
self._timeout = time_out
- def set_available(self) -> None:
+ def set_available(self) :
"""Sets this pool available for pool connections from it.
.. versionadded:: 8.0.20
@@ -1712,7 +1711,7 @@ class ConnectionPool(queue.Queue):
self._available = True
self._timeout_stamp = datetime.now()
- def get_timeout_stamp(self) -> Tuple[int, datetime]:
+ def get_timeout_stamp(self) :
"""Returns the penalized time (timeout) and the time at the penalty.
Returns:
@@ -1721,7 +1720,7 @@ class ConnectionPool(queue.Queue):
"""
return (self._timeout, self._timeout_stamp)
- def close(self) -> None:
+ def close(self) :
"""Empty this ConnectionPool."""
for cnx in self._connections_openned:
cnx.close_connection()
@@ -1735,16 +1734,16 @@ class PoolsManager:
.. versionadded:: 8.0.13
"""
- __instance: PoolsManager = None
- __pools: Dict[str, Any] = {}
+ __instance = None
+ __pools = {}
- def __new__(cls) -> PoolsManager:
+ def __new__(cls) :
if PoolsManager.__instance is None:
PoolsManager.__instance = object.__new__(cls)
PoolsManager.__pools = {}
return PoolsManager.__instance
- def _pool_exists(self, client_id: str, pool_name: str) -> bool:
+ def _pool_exists(self, client_id , pool_name ) :
"""Verifies if a pool exists with the given name.
Args:
@@ -1760,7 +1759,7 @@ class PoolsManager:
return True
return False
- def _get_pools(self, settings: Dict[str, Any]) -> List:
+ def _get_pools(self, settings ) :
"""Retrieves a list of pools that shares the given settings.
Args:
@@ -1785,8 +1784,8 @@ class PoolsManager:
@staticmethod
def _get_connections_settings(
- settings: Dict[str, Any]
- ) -> List[Tuple[str, Dict[str, Any]]]:
+ settings
+ ) :
"""Generates a list of separated connection settings for each host.
Gets a list of connection settings for each host or router found in the
@@ -1828,7 +1827,7 @@ class PoolsManager:
)
return connections_settings
- def create_pool(self, cnx_settings: Dict[str, Any]) -> None:
+ def create_pool(self, cnx_settings ) :
"""Creates a `ConnectionPool` instance to hold the connections.
Creates a `ConnectionPool` instance to hold the connections only if
@@ -1851,7 +1850,7 @@ class PoolsManager:
pool.append(ConnectionPool(router_name, **settings))
@staticmethod
- def _get_random_pool(pool_list: List[ConnectionPool]) -> ConnectionPool:
+ def _get_random_pool(pool_list ) :
"""Get a random router from the group with the given priority.
Returns:
@@ -1870,8 +1869,8 @@ class PoolsManager:
@staticmethod
def _get_sublist(
- pools: List[ConnectionPool], index: int, cur_priority: int
- ) -> List[ConnectionPool]:
+ pools , index , cur_priority
+ ) :
sublist = []
next_priority = None
while index < len(pools):
@@ -1884,14 +1883,14 @@ class PoolsManager:
return sublist
def _get_next_pool(
- self, pools: List[ConnectionPool], cur_priority: int
- ) -> ConnectionPool:
+ self, pools , cur_priority
+ ) :
index = 0
for pool in pools:
if pool.available() and cur_priority == pool.priority:
break
index += 1
- subpool: List = []
+ subpool = []
while not subpool and index < len(pools):
subpool = self._get_sublist(pools, index, cur_priority)
index += 1
@@ -1899,8 +1898,8 @@ class PoolsManager:
@staticmethod
def _get_next_priority(
- pools: List[ConnectionPool], cur_priority: Optional[int] = None
- ) -> int:
+ pools , cur_priority = None
+ ) :
if cur_priority is None and pools:
return pools[0].priority
# find the first pool that does not share the same priority
@@ -1911,8 +1910,8 @@ class PoolsManager:
return pools[0].priority
def _check_unavailable_pools(
- self, settings: Dict[str, Any], revive: Optional[bool] = None
- ) -> None:
+ self, settings , revive = None
+ ) :
pools = self._get_pools(settings)
for pool in pools:
if pool.available():
@@ -1923,7 +1922,7 @@ class PoolsManager:
if datetime.now() > (timeout_stamp + timedelta(seconds=timeout)):
pool.set_available()
- def get_connection(self, settings: Dict[str, Any]) -> PooledConnection:
+ def get_connection(self, settings ) :
"""Get a connection from the pool.
This method returns an `PooledConnection` instance which has a reference
@@ -1938,7 +1937,7 @@ class PoolsManager:
PooledConnection: A pooled connection object.
"""
- def set_mysqlx_wait_timeout(cnx: PooledConnection) -> None:
+ def set_mysqlx_wait_timeout(cnx ) :
ver = cnx.sql(_SELECT_VERSION_QUERY).execute().fetch_all()[0][0]
# mysqlx_wait_timeout is only available on MySQL 8
if tuple(int(n) for n in ver.split("-")[0].split(".")) > (
@@ -2071,7 +2070,7 @@ class PoolsManager:
raise PoolError("Unable to connect to any of the target hosts")
- def close_pool(self, cnx_settings: Dict[str, Any]) -> int:
+ def close_pool(self, cnx_settings ) :
"""Closes the connections in the pools
Returns:
@@ -2089,8 +2088,8 @@ class PoolsManager:
@staticmethod
def set_pool_unavailable(
- pool: ConnectionPool, err: Union[InterfaceError, TimeoutError]
- ) -> None:
+ pool , err
+ ) :
"""Sets a pool as unavailable.
The time a pool is set unavailable depends on the given error message
@@ -2132,9 +2131,9 @@ class Session:
settings (dict): Connection data used to connect to the database.
"""
- def __init__(self, settings: Dict[str, Any]) -> None:
- self.use_pure: bool = settings.get("use-pure", Protobuf.use_pure)
- self._settings: Dict[str, Any] = settings
+ def __init__(self, settings ) :
+ self.use_pure = settings.get("use-pure", Protobuf.use_pure)
+ self._settings = settings
# Check for DNS SRV
if settings.get("host") and settings.get("dns-srv"):
@@ -2171,7 +2170,7 @@ class Session:
if "pooling" in settings and settings["pooling"]:
# Create pool and retrieve a Connection instance
PoolsManager().create_pool(settings)
- self._connection: Connection = PoolsManager().get_connection(settings)
+ self._connection = PoolsManager().get_connection(settings)
if self._connection is None:
raise PoolError("Connection could not be retrieved from pool")
else:
@@ -2191,22 +2190,22 @@ class Session:
)
raise InterfaceError(errmsg, err.errno) from err
- def __enter__(self) -> Session:
+ def __enter__(self) :
return self
def __exit__(
self,
- exc_type: Type[BaseException],
- exc_value: BaseException,
- traceback: TracebackType,
- ) -> None:
+ exc_type ,
+ exc_value ,
+ traceback ,
+ ) :
self.close()
- def _init_attributes(self) -> None:
+ def _init_attributes(self) :
"""Setup default and user defined connection-attributes."""
if os.name == "nt":
if "64" in platform.architecture()[0]:
- platform_arch: Union[str, Tuple[str, str]] = "x86_64"
+ platform_arch = "x86_64"
elif "32" in platform.architecture()[0]:
platform_arch = "i386"
else:
@@ -2280,17 +2279,17 @@ class Session:
self._settings["attributes"][attr_name] = attr_value
@property
- def use_pure(self) -> bool:
+ def use_pure(self) :
"""bool: `True` to use pure Python Protobuf implementation."""
return Protobuf.use_pure
@use_pure.setter
- def use_pure(self, value: bool) -> None:
+ def use_pure(self, value ) :
if not isinstance(value, bool):
raise ProgrammingError("'use_pure' option should be True or False")
Protobuf.set_use_pure(value)
- def is_open(self) -> bool:
+ def is_open(self) :
"""Returns `True` if the session is open.
Returns:
@@ -2298,7 +2297,7 @@ class Session:
"""
return self._connection.stream.is_open()
- def sql(self, sql: str) -> SqlStatement:
+ def sql(self, sql ) :
"""Creates a :class:`mysqlx.SqlStatement` object to allow running the
SQL statement on the target MySQL Server.
@@ -2310,7 +2309,7 @@ class Session:
"""
return SqlStatement(self._connection, sql)
- def get_connection(self) -> Connection:
+ def get_connection(self) :
"""Returns the underlying connection.
Returns:
@@ -2318,7 +2317,7 @@ class Session:
"""
return self._connection
- def get_schemas(self) -> List[str]:
+ def get_schemas(self) :
"""Returns the list of schemas in the current session.
Returns:
@@ -2329,7 +2328,7 @@ class Session:
result = self.sql("SHOW DATABASES").execute()
return [row[0] for row in result.fetch_all()]
- def get_schema(self, name: str) -> Schema:
+ def get_schema(self, name ) :
"""Retrieves a Schema object from the current session by it's name.
Args:
@@ -2340,7 +2339,7 @@ class Session:
"""
return Schema(self, name)
- def get_default_schema(self) -> Optional[Schema]:
+ def get_default_schema(self) :
"""Retrieves a Schema object from the current session by the schema
name configured in the connection settings.
@@ -2370,7 +2369,7 @@ class Session:
) from None
return None
- def drop_schema(self, name: str) -> None:
+ def drop_schema(self, name ) :
"""Drops the schema with the specified name.
Args:
@@ -2380,7 +2379,7 @@ class Session:
"sql", _DROP_DATABASE_QUERY.format(quote_identifier(name)), True
)
- def create_schema(self, name: str) -> Schema:
+ def create_schema(self, name ) :
"""Creates a schema on the database and returns the corresponding
object.
@@ -2392,23 +2391,23 @@ class Session:
)
return Schema(self, name)
- def start_transaction(self) -> None:
+ def start_transaction(self) :
"""Starts a transaction context on the server."""
self._connection.execute_nonquery("sql", "START TRANSACTION", True)
- def commit(self) -> None:
+ def commit(self) :
"""Commits all the operations executed after a call to
startTransaction().
"""
self._connection.execute_nonquery("sql", "COMMIT", True)
- def rollback(self) -> None:
+ def rollback(self) :
"""Discards all the operations executed after a call to
startTransaction().
"""
self._connection.execute_nonquery("sql", "ROLLBACK", True)
- def set_savepoint(self, name: Optional[str] = None) -> str:
+ def set_savepoint(self, name = None) :
"""Creates a transaction savepoint.
If a name is not provided, one will be generated using the uuid.uuid1()
@@ -2429,7 +2428,7 @@ class Session:
)
return name
- def rollback_to(self, name: str) -> None:
+ def rollback_to(self, name ) :
"""Rollback to a transaction savepoint with the given name.
Args:
@@ -2443,7 +2442,7 @@ class Session:
True,
)
- def release_savepoint(self, name: str) -> None:
+ def release_savepoint(self, name ) :
"""Release a transaction savepoint with the given name.
Args:
@@ -2457,13 +2456,13 @@ class Session:
True,
)
- def close(self) -> None:
+ def close(self) :
"""Closes the session."""
self._connection.close_session()
# Set an unconnected connection
self._connection = Connection(self._settings)
- def close_connections(self) -> None:
+ def close_connections(self) :
"""Closes all underliying connections as pooled connections"""
self._connection.close_connection()
@@ -2481,15 +2480,15 @@ class Client:
def __init__(
self,
- connection_dict: Dict[str, Any],
- options_dict: Optional[Dict[str, Any]] = None,
- ) -> None:
- self.settings: Dict[str, Any] = connection_dict
+ connection_dict ,
+ options_dict = None,
+ ) :
+ self.settings = connection_dict
if options_dict is None:
options_dict = {}
- self.sessions: List[Session] = []
- self.client_id: uuid.UUID = uuid.uuid4()
+ self.sessions = []
+ self.client_id = uuid.uuid4()
self._set_pool_size(options_dict.get("max_size", 25))
self._set_max_idle_time(options_dict.get("max_idle_time", 0))
@@ -2500,18 +2499,18 @@ class Client:
self.settings["max_size"] = self.max_size
self.settings["client_id"] = self.client_id
- def __enter__(self) -> Client:
+ def __enter__(self) :
return self
def __exit__(
self,
- exc_type: Type[BaseException],
- exc_value: BaseException,
- traceback: TracebackType,
- ) -> None:
+ exc_type ,
+ exc_value ,
+ traceback ,
+ ) :
self.close()
- def _set_pool_size(self, pool_size: int) -> None:
+ def _set_pool_size(self, pool_size ) :
"""Set the size of the pool.
This method sets the size of the pool but it will not resize the pool.
@@ -2536,7 +2535,7 @@ class Client:
self.max_size = _CNX_POOL_MAXSIZE if pool_size == 0 else pool_size
- def _set_max_idle_time(self, max_idle_time: int) -> None:
+ def _set_max_idle_time(self, max_idle_time ) :
"""Set the max idle time.
This method sets the max idle time.
@@ -2564,7 +2563,7 @@ class Client:
_CNX_POOL_MAX_IDLE_TIME if max_idle_time == 0 else int(max_idle_time / 1000)
)
- def _set_pool_enabled(self, enabled: bool) -> None:
+ def _set_pool_enabled(self, enabled ) :
"""Set if the pool is enabled.
This method sets if the pool is enabled.
@@ -2579,7 +2578,7 @@ class Client:
raise AttributeError("The enabled value should be True or False.")
self.pooling_enabled = enabled
- def _set_queue_timeout(self, queue_timeout: int) -> None:
+ def _set_queue_timeout(self, queue_timeout ) :
"""Set the queue timeout.
This method sets the queue timeout.
@@ -2611,7 +2610,7 @@ class Client:
if "connect-timeout" not in self.settings:
self.settings["connect-timeout"] = self.queue_timeout
- def get_session(self) -> Session:
+ def get_session(self) :
"""Creates a Session instance using the provided connection data.
Returns:
@@ -2621,14 +2620,14 @@ class Client:
self.sessions.append(session)
return session
- def close(self) -> None:
+ def close(self) :
"""Closes the sessions opened by this client."""
PoolsManager().close_pool(self.settings)
for session in self.sessions:
session.close_connections()
-def _parse_address_list(path: str) -> Union[Dict[str, List[Dict]], Dict]:
+def _parse_address_list(path ) :
"""Parses a list of host, port pairs.
Args:
@@ -2649,7 +2648,7 @@ def _parse_address_list(path: str) -> Un
address_list = _SPLIT_RE.split(path[1:-1] if array else path)
priority_count = 0
for address in address_list:
- router: Dict = {}
+ router = {}
match = _PRIORITY_RE.match(address)
if match:
@@ -2683,7 +2682,7 @@ def _parse_address_list(path: str) -> Un
return {"routers": routers} if array else routers[0]
-def _parse_connection_uri(uri: str) -> Dict[str, Any]:
+def _parse_connection_uri(uri ) :
"""Parses the connection string and returns a dictionary with the
connection settings.
@@ -2697,7 +2696,7 @@ def _parse_connection_uri(uri: str) -> D
Raises:
:class:`mysqlx.InterfaceError`: If contains a invalid option.
"""
- settings: Dict[str, Any] = {"schema": ""}
+ settings = {"schema": ""}
match = _URI_SCHEME_RE.match(uri)
scheme, uri = match.groups() if match else ("mysqlx", uri)
@@ -2746,7 +2745,7 @@ def _parse_connection_uri(uri: str) -> D
return settings
-def _validate_settings(settings: Dict[str, Any]) -> None:
+def _validate_settings(settings ) :
"""Validates the settings to be passed to a Session object
the port values are converted to int if specified or set to 33060
otherwise. The priority values for each router is converted to int
@@ -2880,8 +2879,8 @@ def _validate_settings(settings: Dict[st
def _validate_hosts(
- settings: Dict[str, Any], default_port: Optional[int] = None
-) -> None:
+ settings , default_port = None
+) :
"""Validate hosts.
Args:
@@ -2915,7 +2914,7 @@ def _validate_hosts(
settings["port"] = default_port
-def _validate_connection_attributes(settings: Dict[str, Any]) -> None:
+def _validate_connection_attributes(settings ) :
"""Validate connection-attributes.
Args:
@@ -3027,7 +3026,7 @@ def _validate_connection_attributes(sett
settings["connection-attributes"] = attributes
-def _validate_tls_versions(settings: Dict[str, Any]) -> None:
+def _validate_tls_versions(settings ) :
"""Validate tls-versions.
Args:
@@ -3117,7 +3116,7 @@ def _validate_tls_versions(settings: Dic
raise InterfaceError(TLS_VERSION_ERROR.format(tls_ver, SUPPORTED_TLS_VERSIONS))
-def _validate_tls_ciphersuites(settings: Dict[str, Any]) -> None:
+def _validate_tls_ciphersuites(settings ) :
"""Validate tls-ciphersuites.
Args:
@@ -3171,7 +3170,7 @@ def _validate_tls_ciphersuites(settings:
translated_names = []
iani_cipher_suites_names = {}
- ossl_cipher_suites_names: List[str] = []
+ ossl_cipher_suites_names = []
# Old ciphers can work with new TLS versions.
# Find all the ciphers introduced on previous TLS versions
@@ -3219,7 +3218,7 @@ def _validate_tls_ciphersuites(settings:
settings["tls-ciphersuites"] = translated_names
-def _get_connection_settings(*args: Any, **kwargs: Any) -> Dict[str, Any]:
+def _get_connection_settings(*args , **kwargs ) :
"""Parses the connection string and returns a dictionary with the
connection settings.
@@ -3255,7 +3254,7 @@ def _get_connection_settings(*args: Any,
return settings
-def get_session(*args: Any, **kwargs: Any) -> Session:
+def get_session(*args , **kwargs ) :
"""Creates a Session instance using the provided connection data.
Args:
@@ -3273,9 +3272,9 @@ def get_session(*args: Any, **kwargs: An
def get_client(
- connection_string: Union[str, Dict[str, Any]],
- options_string: Union[str, Dict[str, Any]],
-) -> Client:
+ connection_string ,
+ options_string ,
+) :
"""Creates a Client instance with the provided connection data and settings.
Args:
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/crud.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/crud.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/crud.py
@@ -28,7 +28,6 @@
"""Implementation of the CRUD database objects."""
-from __future__ import annotations
import json
import warnings
@@ -83,28 +82,28 @@ class DatabaseObject:
name (str): The database object name.
"""
- def __init__(self, schema: SchemaType, name: StrOrBytes) -> None:
- self._schema: SchemaType = schema
- self._name: str = name.decode() if isinstance(name, bytes) else name
- self._session: SessionType = self._schema.get_session()
- self._connection: ConnectionType = self._session.get_connection()
+ def __init__(self, schema , name ) :
+ self._schema = schema
+ self._name = name.decode() if isinstance(name, bytes) else name
+ self._session = self._schema.get_session()
+ self._connection = self._session.get_connection()
@property
- def session(self) -> SessionType:
+ def session(self) :
""":class:`mysqlx.Session`: The Session object."""
return self._session
@property
- def schema(self) -> SchemaType:
+ def schema(self) :
""":class:`mysqlx.Schema`: The Schema object."""
return self._schema
@property
- def name(self) -> str:
+ def name(self) :
"""str: The name of this database object."""
return self._name
- def get_connection(self) -> ConnectionType:
+ def get_connection(self) :
"""Returns the underlying connection.
Returns:
@@ -112,7 +111,7 @@ class DatabaseObject:
"""
return self._connection
- def get_session(self) -> SessionType:
+ def get_session(self) :
"""Returns the session of this database object.
Returns:
@@ -120,7 +119,7 @@ class DatabaseObject:
"""
return self._session
- def get_schema(self) -> SchemaType:
+ def get_schema(self) :
"""Returns the Schema object of this database object.
Returns:
@@ -128,7 +127,7 @@ class DatabaseObject:
"""
return self._schema
- def get_name(self) -> str:
+ def get_name(self) :
"""Returns the name of this database object.
Returns:
@@ -136,7 +135,7 @@ class DatabaseObject:
"""
return self._name
- def exists_in_database(self) -> Any:
+ def exists_in_database(self) :
"""Verifies if this object exists in the database.
Returns:
@@ -148,7 +147,7 @@ class DatabaseObject:
raise NotImplementedError
@deprecated("8.0.12", "Use 'exists_in_database()' method instead")
- def am_i_real(self) -> Any:
+ def am_i_real(self) :
"""Verifies if this object exists in the database.
Returns:
@@ -163,7 +162,7 @@ class DatabaseObject:
return self.exists_in_database()
@deprecated("8.0.12", "Use 'get_name()' method instead")
- def who_am_i(self) -> str:
+ def who_am_i(self) :
"""Returns the name of this database object.
Returns:
@@ -184,11 +183,11 @@ class Schema(DatabaseObject):
name (str): The Schema name.
"""
- def __init__(self, session: SessionType, name: str) -> None:
- self._session: SessionType = session
+ def __init__(self, session , name ) :
+ self._session = session
super().__init__(self, name)
- def exists_in_database(self) -> bool:
+ def exists_in_database(self) :
"""Verifies if this object exists in the database.
Returns:
@@ -197,7 +196,7 @@ class Schema(DatabaseObject):
sql = _COUNT_SCHEMAS_QUERY.format(escape(self._name))
return self._connection.execute_sql_scalar(sql) == 1
- def get_collections(self) -> List[Collection]:
+ def get_collections(self) :
"""Returns a list of collections for this schema.
Returns:
@@ -217,8 +216,8 @@ class Schema(DatabaseObject):
return collections
def get_collection_as_table(
- self, name: str, check_existence: bool = False
- ) -> Table:
+ self, name , check_existence = False
+ ) :
"""Returns a a table object for the given collection
Returns:
@@ -227,7 +226,7 @@ class Schema(DatabaseObject):
"""
return self.get_table(name, check_existence)
- def get_tables(self) -> List[Table]:
+ def get_tables(self) :
"""Returns a list of tables for this schema.
Returns:
@@ -249,7 +248,7 @@ class Schema(DatabaseObject):
tables.append(table)
return tables
- def get_table(self, name: str, check_existence: bool = False) -> Table:
+ def get_table(self, name , check_existence = False) :
"""Returns the table of the given name for this schema.
Returns:
@@ -261,7 +260,7 @@ class Schema(DatabaseObject):
raise ProgrammingError("Table does not exist")
return table
- def get_view(self, name: str, check_existence: bool = False) -> View:
+ def get_view(self, name , check_existence = False) :
"""Returns the view of the given name for this schema.
Returns:
@@ -273,7 +272,7 @@ class Schema(DatabaseObject):
raise ProgrammingError("View does not exist")
return view
- def get_collection(self, name: str, check_existence: bool = False) -> Collection:
+ def get_collection(self, name , check_existence = False) :
"""Returns the collection of the given name for this schema.
Returns:
@@ -285,7 +284,7 @@ class Schema(DatabaseObject):
raise ProgrammingError("Collection does not exist")
return collection
- def drop_collection(self, name: str) -> None:
+ def drop_collection(self, name ) :
"""Drops a collection.
Args:
@@ -301,11 +300,11 @@ class Schema(DatabaseObject):
def create_collection(
self,
- name: str,
- reuse_existing: bool = False,
- validation: Optional[Dict[str, Union[str, Dict]]] = None,
- **kwargs: Any,
- ) -> Collection:
+ name ,
+ reuse_existing = False,
+ validation = None,
+ **kwargs ,
+ ) :
"""Creates in the current schema a new collection with the specified
name and retrieves an object representing the new collection created.
@@ -341,7 +340,7 @@ class Schema(DatabaseObject):
reuse_existing = kwargs["reuse"]
collection = Collection(self, name)
- fields: Dict[str, Any] = {"schema": self._name, "name": name}
+ fields = {"schema": self._name, "name": name}
if validation is not None:
if not isinstance(validation, dict) or not validation:
@@ -395,8 +394,8 @@ class Schema(DatabaseObject):
return collection
def modify_collection(
- self, name: str, validation: Optional[Dict[str, Union[str, Dict]]] = None
- ) -> None:
+ self, name , validation = None
+ ) :
"""Modifies a collection using a JSON schema validation.
Args:
@@ -471,7 +470,7 @@ class Collection(DatabaseObject):
name (str): The collection name.
"""
- def exists_in_database(self) -> bool:
+ def exists_in_database(self) :
"""Verifies if this object exists in the database.
Returns:
@@ -480,7 +479,7 @@ class Collection(DatabaseObject):
sql = _COUNT_TABLES_QUERY.format(escape(self._schema.name), escape(self._name))
return self._connection.execute_sql_scalar(sql) == 1
- def find(self, condition: Optional[str] = None) -> FindStatement:
+ def find(self, condition = None) :
"""Retrieves documents from a collection.
Args:
@@ -491,7 +490,7 @@ class Collection(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def add(self, *values: DbDoc) -> AddStatement:
+ def add(self, *values ) :
"""Adds a list of documents to a collection.
Args:
@@ -502,7 +501,7 @@ class Collection(DatabaseObject):
"""
return AddStatement(self).add(*values)
- def remove(self, condition: str) -> RemoveStatement:
+ def remove(self, condition ) :
"""Removes documents based on the ``condition``.
Args:
@@ -519,7 +518,7 @@ class Collection(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def modify(self, condition: str) -> ModifyStatement:
+ def modify(self, condition ) :
"""Modifies documents based on the ``condition``.
Args:
@@ -536,7 +535,7 @@ class Collection(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def count(self) -> int:
+ def count(self) :
"""Counts the documents in the collection.
Returns:
@@ -557,8 +556,8 @@ class Collection(DatabaseObject):
return res
def create_index(
- self, index_name: str, fields_desc: Dict[str, Any]
- ) -> CreateCollectionIndexStatement:
+ self, index_name , fields_desc
+ ) :
"""Creates a collection index.
Args:
@@ -582,7 +581,7 @@ class Collection(DatabaseObject):
"""
return CreateCollectionIndexStatement(self, index_name, fields_desc)
- def drop_index(self, index_name: str) -> None:
+ def drop_index(self, index_name ) :
"""Drops a collection index.
Args:
@@ -599,7 +598,7 @@ class Collection(DatabaseObject):
},
)
- def replace_one(self, doc_id: str, doc: Union[Dict, DbDoc]) -> "Result":
+ def replace_one(self, doc_id , doc ) :
"""Replaces the Document matching the document ID with a new document
provided.
@@ -614,7 +613,7 @@ class Collection(DatabaseObject):
)
return self.modify("_id = :id").set("$", doc).bind("id", doc_id).execute()
- def add_or_replace_one(self, doc_id: str, doc: Union[Dict, DbDoc]) -> "Result":
+ def add_or_replace_one(self, doc_id , doc ) :
"""Upserts the Document matching the document ID with a new document
provided.
@@ -631,7 +630,7 @@ class Collection(DatabaseObject):
doc = DbDoc(doc)
return self.add(doc.copy(doc_id)).upsert(True).execute()
- def get_one(self, doc_id: str) -> DbDoc:
+ def get_one(self, doc_id ) :
"""Returns a Document matching the Document ID.
Args:
@@ -645,7 +644,7 @@ class Collection(DatabaseObject):
self._connection.fetch_active_result()
return doc
- def remove_one(self, doc_id: str) -> "Result":
+ def remove_one(self, doc_id ) :
"""Removes a Document matching the Document ID.
Args:
@@ -668,7 +667,7 @@ class Table(DatabaseObject):
name (str): The table name.
"""
- def exists_in_database(self) -> bool:
+ def exists_in_database(self) :
"""Verifies if this object exists in the database.
Returns:
@@ -677,7 +676,7 @@ class Table(DatabaseObject):
sql = _COUNT_TABLES_QUERY.format(escape(self._schema.name), escape(self._name))
return self._connection.execute_sql_scalar(sql) == 1
- def select(self, *fields: str) -> SelectStatement:
+ def select(self, *fields ) :
"""Creates a new :class:`mysqlx.SelectStatement` object.
Args:
@@ -690,7 +689,7 @@ class Table(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def insert(self, *fields: Any) -> InsertStatement:
+ def insert(self, *fields ) :
"""Creates a new :class:`mysqlx.InsertStatement` object.
Args:
@@ -703,7 +702,7 @@ class Table(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def update(self) -> UpdateStatement:
+ def update(self) :
"""Creates a new :class:`mysqlx.UpdateStatement` object.
Returns:
@@ -713,7 +712,7 @@ class Table(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def delete(self) -> DeleteStatement:
+ def delete(self) :
"""Creates a new :class:`mysqlx.DeleteStatement` object.
Returns:
@@ -726,7 +725,7 @@ class Table(DatabaseObject):
stmt.stmt_id = self._connection.get_next_statement_id()
return stmt
- def count(self) -> int:
+ def count(self) :
"""Counts the rows in the table.
Returns:
@@ -746,7 +745,7 @@ class Table(DatabaseObject):
raise
return res
- def is_view(self) -> bool:
+ def is_view(self) :
"""Determine if the underlying object is a view or not.
Returns:
@@ -766,7 +765,7 @@ class View(Table):
name (str): The table name.
"""
- def exists_in_database(self) -> bool:
+ def exists_in_database(self) :
"""Verifies if this object exists in the database.
Returns:
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/dbdoc.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/dbdoc.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/dbdoc.py
@@ -28,7 +28,6 @@
"""Implementation of the DbDoc."""
-from __future__ import annotations
import json
@@ -41,7 +40,7 @@ class ExprJSONEncoder(json.JSONEncoder):
"""A :class:`json.JSONEncoder` subclass, which enables encoding of
:class:`mysqlx.ExprParser` objects."""
- def default(self, o: object) -> str:
+ def default(self, o ) :
if hasattr(o, "expr"):
return f"{o}"
# Let the base class default method raise the TypeError
@@ -58,7 +57,7 @@ class DbDoc:
ValueError: If ``value`` type is not a basestring or dict.
"""
- def __init__(self, value: Union[str, Dict[str, Any]]) -> None:
+ def __init__(self, value ) :
if isinstance(value, dict):
self.__dict__ = value
elif isinstance(value, str):
@@ -66,24 +65,24 @@ class DbDoc:
else:
raise ValueError(f"Unable to handle type: {type(value)}")
- def __str__(self) -> str:
+ def __str__(self) :
return self.as_str()
- def __repr__(self) -> str:
+ def __repr__(self) :
return repr(self.__dict__)
- def __setitem__(self, index: str, value: Any) -> None:
+ def __setitem__(self, index , value ) :
if index == "_id":
raise ProgrammingError("Cannot modify _id")
self.__dict__[index] = value
- def __getitem__(self, index: str) -> Any:
+ def __getitem__(self, index ) :
return self.__dict__[index]
- def __contains__(self, item: str) -> bool:
+ def __contains__(self, item ) :
return item in self.__dict__
- def copy(self, doc_id: Optional[str] = None) -> DbDoc:
+ def copy(self, doc_id = None) :
"""Returns a new copy of a :class:`mysqlx.DbDoc` object containing the
`doc_id` provided. If `doc_id` is not provided, it will be removed from
new :class:`mysqlx.DbDoc` object.
@@ -101,7 +100,7 @@ class DbDoc:
del new_dict["_id"]
return DbDoc(new_dict)
- def keys(self) -> KeysView[str]:
+ def keys(self) :
"""Returns the keys.
Returns:
@@ -109,7 +108,7 @@ class DbDoc:
"""
return self.__dict__.keys()
- def as_str(self) -> str:
+ def as_str(self) :
"""Serialize :class:`mysqlx.DbDoc` to a JSON formatted ``str``.
Returns:
Index: mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/result.py
===================================================================
--- mysql-connector-python-9.1.0-src.orig/mysqlx-connector-python/lib/mysqlx/result.py
+++ mysql-connector-python-9.1.0-src/mysqlx-connector-python/lib/mysqlx/result.py
@@ -28,7 +28,6 @@
"""Implementation of the Result classes."""
-from __future__ import annotations
import decimal
import struct
@@ -44,7 +43,7 @@ from .types import ConnectionType, Field
# pylint: disable=missing-class-docstring,missing-function-docstring
-def from_protobuf(column: Column, payload: bytes) -> Any:
+def from_protobuf(column , payload ) :
if len(payload) == 0:
return None
@@ -59,22 +58,22 @@ def from_protobuf(column: Column, payloa
return None
-def bytes_from_protobuf(payload: bytes) -> bytes:
+def bytes_from_protobuf(payload ) :
# Strip trailing char
return payload[:-1]
-def float_from_protobuf(payload: bytes) -> float:
+def float_from_protobuf(payload ) :
assert len(payload) == 4
return struct.unpack("<f", payload)[0]
-def double_from_protobuf(payload: bytes) -> float:
+def double_from_protobuf(payload ) :
assert len(payload) == 8
return struct.unpack("<d", payload)[0]
-def varint_from_protobuf_stream(payload: bytes) -> Tuple[int, bytes]:
+def varint_from_protobuf_stream(payload ) :
if len(payload) == 0:
raise ValueError("Payload is empty")
@@ -96,7 +95,7 @@ def varint_from_protobuf_stream(payload:
raise EOFError("Payload too short")
-def varint_from_protobuf(payload: bytes) -> int:
+def varint_from_protobuf(payload ) :
i, payload = varint_from_protobuf_stream(payload)
if len(payload) != 0:
raise ValueError("Payload too long")
@@ -104,7 +103,7 @@ def varint_from_protobuf(payload: bytes)
return i
-def varsint_from_protobuf(payload: bytes) -> int:
+def varsint_from_protobuf(payload ) :
i, payload = varint_from_protobuf_stream(payload)
if len(payload) != 0:
raise ValueError("Payload too long")
@@ -120,8 +119,8 @@ def varsint_from_protobuf(payload: bytes
return i
-def set_from_protobuf(payload: bytes) -> List[bytes]:
- set_pb: List = []
+def set_from_protobuf(payload ) :
+ set_pb = []
while True:
try:
field_len, payload = varint_from_protobuf_stream(payload)
@@ -141,7 +140,7 @@ def set_from_protobuf(payload: bytes) ->
return set_pb
-def decimal_from_protobuf(payload: bytes) -> decimal.Decimal:
+def decimal_from_protobuf(payload ) :
digits = []
sign = None
scale = payload[0] if isinstance(payload[0], int) else ord(payload[0]) # type: ignore[arg-type]
@@ -177,7 +176,7 @@ def decimal_from_protobuf(payload: bytes
return decimal.Decimal((sign, digits, -scale))
-def datetime_from_protobuf(payload: bytes) -> datetime:
+def datetime_from_protobuf(payload ) :
# A sequence of varints
hour = 0
minutes = 0
@@ -198,7 +197,7 @@ def datetime_from_protobuf(payload: byte
return datetime(year, month, day, hour, minutes, seconds, useconds)
-def time_from_protobuf(payload: bytes) -> timedelta:
+def time_from_protobuf(payload ) :
# A sequence of varints
hour = 0
minutes = 0
@@ -273,32 +272,32 @@ class ColumnType:
LONGTEXT = 35
@classmethod
- def to_string(cls, needle: Any) -> Optional[str]:
+ def to_string(cls, needle ) :
for key, value in vars(cls).items():
if value == needle:
return key
return None
@classmethod
- def from_string(cls, key: str) -> Any:
+ def from_string(cls, key ) :
return getattr(cls, key.upper(), None)
@classmethod
- def is_char(cls, col_type: int) -> bool:
+ def is_char(cls, col_type ) :
return col_type in (
cls.CHAR,
cls.VARCHAR,
)
@classmethod
- def is_binary(cls, col_type: int) -> bool:
+ def is_binary(cls, col_type ) :
return col_type in (
cls.BINARY,
cls.VARBINARY,
)
@classmethod
- def is_text(cls, col_type: int) -> bool:
+ def is_text(cls, col_type ) :
return col_type in (
cls.TEXT,
cls.TINYTEXT,
@@ -307,7 +306,7 @@ class ColumnType:
)
@classmethod
- def is_decimals(cls, col_type: int) -> bool:
+ def is_decimals(cls, col_type ) :
return col_type in (
cls.REAL,
cls.DOUBLE,
@@ -317,7 +316,7 @@ class ColumnType:
)
@classmethod
- def is_numeric(cls, col_type: int) -> bool:
+ def is_numeric(cls, col_type ) :
return col_type in (
cls.BIT,
cls.TINYINT,
@@ -328,7 +327,7 @@ class ColumnType:
)
@classmethod
- def is_finite_set(cls, col_type: int) -> bool:
+ def is_finite_set(cls, col_type ) :
return col_type in (
cls.SET,
cls.ENUM,
@@ -348,7 +347,7 @@ class ColumnProtoType:
BIT = 17
DECIMAL = 18
- converter_map: Dict[int, Callable[[bytes], Any]] = {
+ converter_map = {
SINT: varsint_from_protobuf,
UINT: varint_from_protobuf,
BYTES: bytes_from_protobuf,
@@ -364,18 +363,18 @@ class ColumnProtoType:
class Flags:
- def __init__(self, value: int) -> None:
- self._allowed_flags: Dict[str, int] = {}
- self._flag_names: Dict[int, str] = {}
+ def __init__(self, value ) :
+ self._allowed_flags = {}
+ self._flag_names = {}
for key, val in self.__class__.__dict__.items():
if key.startswith("__"):
continue
if isinstance(val, int):
self._allowed_flags[key] = val
self._flag_names[val] = key
- self._value: int = value
+ self._value = value
- def __str__(self) -> str:
+ def __str__(self) :
mask = 1
flag_names = []
value = self._value
@@ -394,11 +393,11 @@ class Flags:
return ",".join(flag_names)
@property
- def value(self) -> int:
+ def value(self) :
return self._value
@value.setter
- def value(self, val: int) -> None:
+ def value(self, val ) :
self._value = val
@@ -461,39 +460,39 @@ class Column:
def __init__(
self,
- col_type: int,
- catalog: Optional[str] = None,
- schema: Optional[str] = None,
- table: Optional[str] = None,
- original_table: Optional[str] = None,
- name: Optional[str] = None,
- original_name: Optional[str] = None,
- length: Optional[int] = None,
- collation: Optional[int] = None,
- fractional_digits: Optional[int] = None,
- flags: Optional[int] = None,
- content_type: Optional[int] = None,
- ) -> None:
- self._schema: str = decode_from_bytes(schema)
- self._name: str = decode_from_bytes(name)
- self._original_name: str = decode_from_bytes(original_name)
- self._table: str = decode_from_bytes(table)
- self._original_table: str = decode_from_bytes(original_table)
- self._proto_type: int = col_type
- self._col_type: Optional[int] = None
- self._catalog: Optional[str] = catalog
- self._length: Optional[int] = length
- self._collation: Optional[int] = collation
- self._fractional_digits: Optional[int] = fractional_digits
- self._flags: Optional[int] = flags
- self._content_type: Optional[int] = content_type
- self._number_signed: bool = False
- self._is_padded: Union[bool, int] = False
- self._is_binary: bool = False
- self._is_bytes: bool = False
- self._collation_name: Optional[str] = None
- self._character_set_name: Optional[str] = None
- self._zero_fill: Optional[int] = None
+ col_type ,
+ catalog = None,
+ schema = None,
+ table = None,
+ original_table = None,
+ name = None,
+ original_name = None,
+ length = None,
+ collation = None,
+ fractional_digits = None,
+ flags = None,
+ content_type = None,
+ ) :
+ self._schema = decode_from_bytes(schema)
+ self._name = decode_from_bytes(name)
+ self._original_name = decode_from_bytes(original_name)
+ self._table = decode_from_bytes(table)
+ self._original_table = decode_from_bytes(original_table)
+ self._proto_type = col_type
+ self._col_type = None
+ self._catalog = catalog
+ self._length = length
+ self._collation = collation
+ self._fractional_digits = fractional_digits
+ self._flags = flags
+ self._content_type = content_type
+ self._number_signed = False
+ self._is_padded = False
+ self._is_binary = False
+ self._is_bytes = False
+ self._collation_name = None
+ self._character_set_name = None
+ self._zero_fill = None
if self._collation > 0:
if self._collation >= len(MYSQL_CHARACTER_SETS):
@@ -513,7 +512,7 @@ class Column:
ColumnType.STRING,
)
- def __str__(self) -> str:
+ def __str__(self) :
return str(
{
"col_type": self._col_type,
@@ -523,7 +522,7 @@ class Column:
}
)
- def _map_bytes(self) -> None:
+ def _map_bytes(self) :
"""Map bytes."""
if self._content_type == BytesContentType.GEOMETRY:
self._col_type = ColumnType.GEOMETRY
@@ -537,7 +536,7 @@ class Column:
self._col_type = ColumnType.STRING
self._is_padded = self._flags & 1
- def _map_datetime(self) -> None:
+ def _map_datetime(self) :
"""Map datetime."""
if self._length == 10:
self._col_type = ColumnType.DATE
@@ -548,7 +547,7 @@ class Column:
else:
raise ValueError("Datetime mapping scenario unhandled")
- def _map_int_type(self) -> None:
+ def _map_int_type(self) :
"""Map int type."""
if self._length <= 4:
self._col_type = ColumnType.TINYINT
@@ -562,7 +561,7 @@ class Column:
self._col_type = ColumnType.BIGINT
self._number_signed = True
- def _map_uint_type(self) -> None:
+ def _map_uint_type(self) :
"""Map uint type."""
if self._length <= 3:
self._col_type = ColumnType.TINYINT
@@ -576,7 +575,7 @@ class Column:
self._col_type = ColumnType.BIGINT
self._zero_fill = self._flags & 1
- def _map_type(self) -> None:
+ def _map_type(self) :
"""Map type."""
if self._proto_type == ColumnProtoType.SINT:
self._map_int_type()
@@ -607,7 +606,7 @@ class Column:
raise ValueError(f"Unknown column type {self._proto_type}")
@property
- def schema_name(self) -> str:
+ def schema_name(self) :
"""str: The schema name.
.. versionadded:: 8.0.12
@@ -615,7 +614,7 @@ class Column:
return self._schema
@property
- def table_name(self) -> str:
+ def table_name(self) :
"""str: The table name.
.. versionadded:: 8.0.12
@@ -623,7 +622,7 @@ class Column:
return self._original_table or self._table
@property
- def table_label(self) -> str:
+ def table_label(self) :
"""str: The table label.
.. versionadded:: 8.0.12
@@ -631,7 +630,7 @@ class Column:
return self._table or self._original_table
@property
- def column_name(self) -> str:
+ def column_name(self) :
"""str: The column name.
.. versionadded:: 8.0.12
@@ -639,7 +638,7 @@ class Column:
return self._original_name or self._name
@property
- def column_label(self) -> str:
+ def column_label(self) :
"""str: The column label.
.. versionadded:: 8.0.12
@@ -647,7 +646,7 @@ class Column:
return self._name or self._original_name
@property
- def type(self) -> int:
+ def type(self) :
"""int: The column type.
.. versionadded:: 8.0.12
@@ -655,7 +654,7 @@ class Column:
return self._col_type
@property
- def length(self) -> int:
+ def length(self) :
"""int. The column length.
.. versionadded:: 8.0.12
@@ -663,7 +662,7 @@ class Column:
return self._length
@property
- def fractional_digits(self) -> int:
+ def fractional_digits(self) :
"""int: The column fractional digits.
.. versionadded:: 8.0.12
@@ -671,7 +670,7 @@ class Column:
return self._fractional_digits
@property
- def collation_name(self) -> str:
+ def collation_name(self) :
"""str: The collation name.
.. versionadded:: 8.0.12
@@ -679,14 +678,14 @@ class Column:
return self._collation_name
@property
- def character_set_name(self) -> str:
+ def character_set_name(self) :
"""str: The character set name.
.. versionadded:: 8.0.12
"""
return self._character_set_name
- def get_schema_name(self) -> str:
+ def get_schema_name(self) :
"""Returns the schema name.
Returns:
@@ -694,7 +693,7 @@ class Column:
"""
return self._schema
- def get_table_name(self) -> str:
+ def get_table_name(self) :
"""Returns the table name.
Returns:
@@ -702,7 +701,7 @@ class Column:
"""
return self._original_table or self._table
- def get_table_label(self) -> str:
+ def get_table_label(self) :
"""Returns the table label.
Returns:
@@ -710,7 +709,7 @@ class Column:
"""
return self._table or self._original_table
- def get_column_name(self) -> str:
+ def get_column_name(self) :
"""Returns the column name.
Returns:
@@ -718,7 +717,7 @@ class Column:
"""
return self._original_name or self._name
- def get_column_label(self) -> str:
+ def get_column_label(self) :
"""Returns the column label.
Returns:
@@ -726,7 +725,7 @@ class Column:
"""
return self._name or self._original_name
- def get_proto_type(self) -> int:
+ def get_proto_type(self) :
"""Returns the column proto type.
Returns:
@@ -734,7 +733,7 @@ class Column:
"""
return self._proto_type
- def get_type(self) -> int:
+ def get_type(self) :
"""Returns the column type.
Returns:
@@ -742,7 +741,7 @@ class Column:
"""
return self._col_type
- def get_length(self) -> int:
+ def get_length(self) :
"""Returns the column length.
Returns:
@@ -750,7 +749,7 @@ class Column:
"""
return self._length
- def get_fractional_digits(self) -> int:
+ def get_fractional_digits(self) :
"""Returns the column fractional digits.
Returns:
@@ -758,7 +757,7 @@ class Column:
"""
return self._fractional_digits
- def get_collation_name(self) -> str:
+ def get_collation_name(self) :
"""Returns the collation name.
Returns:
@@ -766,7 +765,7 @@ class Column:
"""
return self._collation_name
- def get_character_set_name(self) -> str:
+ def get_character_set_name(self) :
"""Returns the character set name.
Returns:
@@ -774,7 +773,7 @@ class Column:
"""
return self._character_set_name
- def is_number_signed(self) -> bool:
+ def is_number_signed(self) :
"""Returns `True` if is a number signed.
Returns:
@@ -782,7 +781,7 @@ class Column:
"""
return self._number_signed
- def is_padded(self) -> Union[bool, int]:
+ def is_padded(self) :
"""Returns `True` if is padded.
Returns:
@@ -790,7 +789,7 @@ class Column:
"""
return self._is_padded
- def is_bytes(self) -> bool:
+ def is_bytes(self) :
"""Returns `True` if is bytes.
Returns:
@@ -808,15 +807,15 @@ class Row:
"""
def __init__(
- self, resultset: Union[BufferingResult, RowResult], fields: Sequence[FieldTypes]
- ) -> None:
- self._fields: Sequence[FieldTypes] = fields
- self._resultset: Union[BufferingResult, RowResult] = resultset
+ self, resultset , fields
+ ) :
+ self._fields = fields
+ self._resultset = resultset
- def __repr__(self) -> str:
+ def __repr__(self) :
return repr(self._fields)
- def __getitem__(self, index: Union[int, str]) -> Any:
+ def __getitem__(self, index ) :
"""Returns the value of a column by name or index.
.. versionchanged:: 8.0.12
@@ -829,7 +828,7 @@ class Row:
return self._fields[int_index]
@deprecated("8.0.12")
- def get_string(self, str_index: str) -> str:
+ def get_string(self, str_index ) :
"""Returns the value using the column name.
Args:
@@ -852,13 +851,13 @@ class BaseResult:
connection (mysqlx.connection.Connection): The Connection object.
"""
- def __init__(self, connection: ConnectionType) -> None:
- self._connection: ConnectionType = connection
- self._closed: bool = False
- self._rows_affected: int = 0
- self._generated_id: int = -1
- self._generated_ids: List[int] = []
- self._warnings: List[Dict[str, Union[int, str]]] = []
+ def __init__(self, connection ) :
+ self._connection = connection
+ self._closed = False
+ self._rows_affected = 0
+ self._generated_id = -1
+ self._generated_ids = []
+ self._warnings = []
if connection is None:
self._protocol = None
@@ -866,7 +865,7 @@ class BaseResult:
self._protocol = connection.protocol
connection.fetch_active_result()
- def get_affected_items_count(self) -> int:
+ def get_affected_items_count(self) :
"""Returns the number of affected items for the last operation.
Returns:
@@ -874,7 +873,7 @@ class BaseResult:
"""
return self._rows_affected
- def get_warnings(self) -> List[Dict[str, Union[int, str]]]:
+ def get_warnings(self) :
"""Returns the warnings.
Returns:
@@ -882,7 +881,7 @@ class BaseResult:
"""
return self._warnings
- def get_warnings_count(self) -> int:
+ def get_warnings_count(self) :
"""Returns the number of warnings.
Returns:
@@ -890,11 +889,11 @@ class BaseResult:
"""
return len(self._warnings)
- def set_closed(self, flag: bool) -> None:
+ def set_closed(self, flag ) :
"""Sets if resultset fetch is done."""
self._closed = flag
- def append_warning(self, level: int, code: int, msg: str) -> None:
+ def append_warning(self, level , code , msg ) :
"""Append a warning.
Args:
@@ -904,15 +903,15 @@ class BaseResult:
"""
self._warnings.append({"level": level, "code": code, "msg": msg})
- def set_generated_ids(self, generated_ids: List[int]) -> None:
+ def set_generated_ids(self, generated_ids ) :
"""Sets the generated ids."""
self._generated_ids = generated_ids
- def set_generated_insert_id(self, generated_id: int) -> None:
+ def set_generated_insert_id(self, generated_id ) :
"""Sets the generated insert id."""
self._generated_id = generated_id
- def set_rows_affected(self, total: int) -> None:
+ def set_rows_affected(self, total ) :
"""Sets the number of rows affected."""
self._rows_affected = total
@@ -928,16 +927,16 @@ class Result(BaseResult):
def __init__(
self,
- connection: Optional[ConnectionType] = None,
- ids: Optional[List[int]] = None,
- ) -> None:
+ connection = None,
+ ids = None,
+ ) :
super().__init__(connection)
- self._ids: Optional[List[int]] = ids
+ self._ids = ids
if connection is not None:
self._connection.close_result(self)
- def get_autoincrement_value(self) -> int:
+ def get_autoincrement_value(self) :
"""Returns the last insert id auto generated.
Returns:
@@ -946,7 +945,7 @@ class Result(BaseResult):
return self._generated_id
@deprecated("8.0.12")
- def get_document_id(self) -> Optional[int]:
+ def get_document_id(self) :
"""Returns ID of the last document inserted into a collection.
.. deprecated:: 8.0.12
@@ -956,14 +955,14 @@ class Result(BaseResult):
return self._ids[0]
@deprecated("8.0.12")
- def get_generated_insert_id(self) -> int:
+ def get_generated_insert_id(self) :
"""Returns the generated insert id.
.. deprecated:: 8.0.12
"""
return self._generated_id
- def get_generated_ids(self) -> List[int]:
+ def get_generated_ids(self) :
"""Returns the generated ids."""
return self._generated_ids
@@ -976,25 +975,25 @@ class BufferingResult(BaseResult):
ids (`list`): A list of IDs.
"""
- def __init__(self, connection: ConnectionType) -> None:
+ def __init__(self, connection ) :
super().__init__(connection)
- self._columns: List[Column] = []
- self._has_data: bool = False
- self._has_more_results: bool = False
- self._items: List[Union[Row, DbDoc]] = []
- self._page_size: int = 0
- self._position: int = -1
+ self._columns = []
+ self._has_data = False
+ self._has_more_results = False
+ self._items = []
+ self._page_size = 0
+ self._position = -1
self._init_result()
- def __getitem__(self, index: int) -> Union[Row, DbDoc]:
+ def __getitem__(self, index ) :
return self._items[index]
@property
- def count(self) -> int:
+ def count(self) :
"""int: The total of items."""
return len(self._items)
- def _init_result(self) -> None:
+ def _init_result(self) :
"""Initialize the result."""
self._columns = self._connection.get_column_metadata(self)
self._has_more_data = len(self._columns) > 0
@@ -1003,7 +1002,7 @@ class BufferingResult(BaseResult):
self._position = -1
self._connection.set_active_result(self if self._has_more_data else None)
- def _read_item(self, dumping: bool) -> Optional[Union[Row, DbDoc]]:
+ def _read_item(self, dumping ) :
"""Read item.
Args:
@@ -1022,7 +1021,7 @@ class BufferingResult(BaseResult):
item[key] = from_protobuf(column, row["field"][key])
return Row(self, item)
- def _page_in_items(self) -> Union[bool, int]:
+ def _page_in_items(self) :
"""Reads the page items.
Returns:
@@ -1040,7 +1039,7 @@ class BufferingResult(BaseResult):
count += 1
return count
- def index_of(self, col_name: str) -> int:
+ def index_of(self, col_name ) :
"""Returns the index of the column.
Returns:
@@ -1053,7 +1052,7 @@ class BufferingResult(BaseResult):
index += 1
return -1
- def fetch_one(self) -> Optional[Union[Row, DbDoc]]:
+ def fetch_one(self) :
"""Fetch one item.
Returns:
@@ -1064,7 +1063,7 @@ class BufferingResult(BaseResult):
return self._read_item(False)
- def fetch_all(self) -> List[Union[Row, DbDoc]]:
+ def fetch_all(self) :
"""Fetch all items.
Returns:
@@ -1076,7 +1075,7 @@ class BufferingResult(BaseResult):
break
return self._items
- def set_has_data(self, flag: bool) -> None:
+ def set_has_data(self, flag ) :
"""Sets if result has data.
Args:
@@ -1084,7 +1083,7 @@ class BufferingResult(BaseResult):
"""
self._has_data = flag
- def set_has_more_results(self, flag: bool) -> None:
+ def set_has_more_results(self, flag ) :
"""Sets if has more results.
Args:
@@ -1101,11 +1100,11 @@ class RowResult(BufferingResult):
"""
@property
- def columns(self) -> List[Column]:
+ def columns(self) :
"""`list`: The list of columns."""
return self._columns
- def get_columns(self) -> List[Column]:
+ def get_columns(self) :
"""Returns the list of columns.
Returns:
@@ -1123,7 +1122,7 @@ class SqlResult(RowResult):
connection (mysqlx.connection.Connection): The Connection object.
"""
- def get_autoincrement_value(self) -> int:
+ def get_autoincrement_value(self) :
"""Returns the identifier for the last record inserted.
Returns:
@@ -1131,7 +1130,7 @@ class SqlResult(RowResult):
"""
return self._generated_id
- def next_result(self) -> bool:
+ def next_result(self) :
"""Process the next result.
Returns:
@@ -1143,7 +1142,7 @@ class SqlResult(RowResult):
self._init_result()
return True
- def has_data(self) -> bool:
+ def has_data(self) :
"""Returns True if result has data.
Returns:
@@ -1162,7 +1161,7 @@ class DocResult(BufferingResult):
connection (mysqlx.connection.Connection): The Connection object.
"""
- def _read_item(self, dumping: bool) -> DbDoc:
+ def _read_item(self, dumping ) :
"""Read item.
Args: