mysqlx-connector-python 9.1.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. _mysqlxpb.cp313-win_amd64.pyd +0 -0
  2. mysqlx/__init__.py +136 -0
  3. mysqlx/authentication.py +186 -0
  4. mysqlx/charsets.py +620 -0
  5. mysqlx/connection.py +3374 -0
  6. mysqlx/constants.py +240 -0
  7. mysqlx/crud.py +776 -0
  8. mysqlx/dbdoc.py +120 -0
  9. mysqlx/errorcode.py +1877 -0
  10. mysqlx/errors.py +257 -0
  11. mysqlx/expr.py +1366 -0
  12. mysqlx/helpers.py +234 -0
  13. mysqlx/locales/__init__.py +80 -0
  14. mysqlx/locales/eng/__init__.py +30 -0
  15. mysqlx/locales/eng/client_error.py +152 -0
  16. mysqlx/logger.py +33 -0
  17. mysqlx/protobuf/__init__.py +627 -0
  18. mysqlx/protobuf/mysqlx_connection_pb2.py +74 -0
  19. mysqlx/protobuf/mysqlx_crud_pb2.py +108 -0
  20. mysqlx/protobuf/mysqlx_cursor_pb2.py +68 -0
  21. mysqlx/protobuf/mysqlx_datatypes_pb2.py +75 -0
  22. mysqlx/protobuf/mysqlx_expect_pb2.py +69 -0
  23. mysqlx/protobuf/mysqlx_expr_pb2.py +81 -0
  24. mysqlx/protobuf/mysqlx_notice_pb2.py +81 -0
  25. mysqlx/protobuf/mysqlx_pb2.py +71 -0
  26. mysqlx/protobuf/mysqlx_prepare_pb2.py +73 -0
  27. mysqlx/protobuf/mysqlx_resultset_pb2.py +75 -0
  28. mysqlx/protobuf/mysqlx_session_pb2.py +67 -0
  29. mysqlx/protobuf/mysqlx_sql_pb2.py +63 -0
  30. mysqlx/protocol.py +1214 -0
  31. mysqlx/py.typed +0 -0
  32. mysqlx/result.py +1177 -0
  33. mysqlx/statement.py +1542 -0
  34. mysqlx/tls_ciphers.py +169 -0
  35. mysqlx/types.py +120 -0
  36. mysqlx/utils.py +178 -0
  37. mysqlx/version.py +46 -0
  38. mysqlx_connector_python-9.1.0.dist-info/LICENSE.txt +4247 -0
  39. mysqlx_connector_python-9.1.0.dist-info/METADATA +187 -0
  40. mysqlx_connector_python-9.1.0.dist-info/RECORD +42 -0
  41. mysqlx_connector_python-9.1.0.dist-info/WHEEL +5 -0
  42. mysqlx_connector_python-9.1.0.dist-info/top_level.txt +2 -0
mysqlx/connection.py ADDED
@@ -0,0 +1,3374 @@
1
+ # Copyright (c) 2016, 2024, Oracle and/or its affiliates.
2
+ #
3
+ # This program is free software; you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License, version 2.0, as
5
+ # published by the Free Software Foundation.
6
+ #
7
+ # This program is designed to work with certain software (including
8
+ # but not limited to OpenSSL) that is licensed under separate terms,
9
+ # as designated in a particular file or component or in included license
10
+ # documentation. The authors of MySQL hereby grant you an
11
+ # additional permission to link the program and your derivative works
12
+ # with the separately licensed software that they have either included with
13
+ # the program or referenced in the documentation.
14
+ #
15
+ # Without limiting anything contained in the foregoing, this file,
16
+ # which is part of MySQL Connector/Python, is also subject to the
17
+ # Universal FOSS Exception, version 1.0, a copy of which can be found at
18
+ # http://oss.oracle.com/licenses/universal-foss-exception.
19
+ #
20
+ # This program is distributed in the hope that it will be useful, but
21
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23
+ # See the GNU General Public License, version 2.0, for more details.
24
+ #
25
+ # You should have received a copy of the GNU General Public License
26
+ # along with this program; if not, write to the Free Software Foundation, Inc.,
27
+ # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28
+
29
+ # mypy: disable-error-code="index,attr-defined"
30
+
31
+ """Implementation of communication for MySQL X servers."""
32
+
33
+ from __future__ import annotations
34
+
35
+ from types import TracebackType
36
+
37
+ try:
38
+ import ssl
39
+
40
+ SSL_AVAILABLE = True
41
+ TLS_VERSIONS = {
42
+ "TLSv1.2": ssl.PROTOCOL_TLSv1_2,
43
+ }
44
+ # TLSv1.3 included in PROTOCOL_TLS, but PROTOCOL_TLS is not included on 3.4
45
+ TLS_VERSIONS["TLSv1.3"] = (
46
+ ssl.PROTOCOL_TLS
47
+ if hasattr(ssl, "PROTOCOL_TLS")
48
+ else ssl.PROTOCOL_SSLv23 # Alias of PROTOCOL_TLS
49
+ )
50
+ TLS_V1_3_SUPPORTED = hasattr(ssl, "HAS_TLSv1_3") and ssl.HAS_TLSv1_3
51
+ except ImportError:
52
+ SSL_AVAILABLE = False
53
+ TLS_V1_3_SUPPORTED = False
54
+ TLS_VERSIONS = {}
55
+
56
+ import json
57
+ import os
58
+ import platform
59
+ import queue
60
+ import random
61
+ import re
62
+ import socket
63
+ import sys
64
+ import threading
65
+ import uuid
66
+
67
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, Union
68
+
69
+ try:
70
+ import dns.exception
71
+ import dns.resolver
72
+ except ImportError:
73
+ HAVE_DNSPYTHON = False
74
+ else:
75
+ HAVE_DNSPYTHON = True
76
+
77
+ from datetime import datetime, timedelta
78
+ from functools import wraps
79
+ from json.decoder import JSONDecodeError
80
+ from urllib.parse import parse_qsl, unquote, urlparse
81
+
82
+ from .authentication import MySQL41AuthPlugin, PlainAuthPlugin, Sha256MemoryAuthPlugin
83
+ from .constants import (
84
+ COMPRESSION_ALGORITHMS,
85
+ OPENSSL_CS_NAMES,
86
+ SUPPORTED_TLS_VERSIONS,
87
+ TLS_CIPHER_SUITES,
88
+ Auth,
89
+ Compression,
90
+ SSLMode,
91
+ )
92
+ from .crud import Schema
93
+
94
+ # pylint: disable=redefined-builtin
95
+ from .errors import (
96
+ InterfaceError,
97
+ NotSupportedError,
98
+ OperationalError,
99
+ PoolError,
100
+ ProgrammingError,
101
+ TimeoutError,
102
+ )
103
+ from .helpers import escape, get_item_or_attr, iani_to_openssl_cs_name
104
+ from .logger import logger
105
+ from .protobuf import Protobuf
106
+ from .protocol import HAVE_LZ4, HAVE_ZSTD, MessageReader, MessageWriter, Protocol
107
+ from .result import BaseResult, DocResult, Result, RowResult, SqlResult
108
+ from .statement import (
109
+ AddStatement,
110
+ DeleteStatement,
111
+ FindStatement,
112
+ InsertStatement,
113
+ ModifyStatement,
114
+ ReadStatement,
115
+ RemoveStatement,
116
+ SelectStatement,
117
+ SqlStatement,
118
+ UpdateStatement,
119
+ quote_identifier,
120
+ )
121
+ from .types import ColumnType, MessageType, ResultBaseType, StatementType
122
+
123
+ sys.path.append("..")
124
+
125
+ from .tls_ciphers import UNACCEPTABLE_TLS_CIPHERSUITES, UNACCEPTABLE_TLS_VERSIONS
126
+ from .utils import (
127
+ linux_distribution,
128
+ warn_ciphersuites_deprecated,
129
+ warn_tls_version_deprecated,
130
+ )
131
+ from .version import LICENSE, VERSION
132
+
133
+ DUPLICATED_IN_LIST_ERROR = (
134
+ "The '{list}' list must not contain repeated values, the value "
135
+ "'{value}' is duplicated."
136
+ )
137
+
138
+ TLS_VERSION_ERROR = (
139
+ "The given tls_version: '{}' is not recognized as a valid "
140
+ "TLS protocol version (should be one of {})."
141
+ )
142
+
143
+ TLS_VERSION_UNACCEPTABLE_ERROR = (
144
+ "The given tls_version: '{}' are no longer allowed (should be one of {})."
145
+ )
146
+
147
+ TLS_VER_NO_SUPPORTED = (
148
+ "No supported TLS protocol version found in the 'tls-versions' list '{}'. "
149
+ )
150
+
151
+ CONNECTION_CLOSED_ERROR = {
152
+ 1810: "This session was closed because the connection has been idle for "
153
+ "too long. Use 'mysqlx.getSession()' or 'mysqlx.getClient()' to create a "
154
+ "new one.",
155
+ 1053: "This session was closed because the server is shutting down.",
156
+ 3169: "This session was closed because the connection has been killed in "
157
+ "a different session. Use 'mysqlx.getSession()' or 'mysqlx.getClient()' "
158
+ "to create a new one.",
159
+ }
160
+
161
+ _CONNECT_TIMEOUT = 10000 # Default connect timeout in milliseconds
162
+ _DROP_DATABASE_QUERY = "DROP DATABASE IF EXISTS {}"
163
+ _CREATE_DATABASE_QUERY = "CREATE DATABASE IF NOT EXISTS {}"
164
+ _SELECT_SCHEMA_NAME_QUERY = (
165
+ "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{}'"
166
+ )
167
+ _SELECT_VERSION_QUERY = "SELECT @@version"
168
+
169
+ _CNX_POOL_MAXSIZE = 99
170
+ _CNX_POOL_MAX_NAME_SIZE = 120
171
+ _CNX_POOL_NAME_REGEX = re.compile(r"[^a-zA-Z0-9._:\-*$#]")
172
+ _CNX_POOL_MAX_IDLE_TIME = 2147483
173
+ _CNX_POOL_QUEUE_TIMEOUT = 2147483
174
+
175
+ # Time is on seconds
176
+ _PENALTY_SERVER_OFFLINE = 1000000
177
+ _PENALTY_MAXED_OUT = 60
178
+ _PENALTY_NO_ADD_INFO = 60 * 60
179
+ _PENALTY_CONN_TIMEOUT = 60 * 60
180
+ _PENALTY_WRONG_PASSW = 60 * 60 * 24
181
+ _PENALTY_RESTARTING = 60
182
+ _TIMEOUT_PENALTIES = {
183
+ # Server denays service e.g Max connections reached
184
+ "[WinError 10053]": _PENALTY_MAXED_OUT, # Established connection was aborted
185
+ "[Errno 32]": _PENALTY_MAXED_OUT, # Broken pipe
186
+ # Server is Offline
187
+ "[WinError 10061]": _PENALTY_SERVER_OFFLINE, # Target machine actively refused it
188
+ "[Errno 111]": _PENALTY_SERVER_OFFLINE, # Connection refused
189
+ # Host is offline:
190
+ "[WinError 10060]": _PENALTY_CONN_TIMEOUT, # Not respond after a period of time
191
+ # No route to Host:
192
+ "[Errno 11001]": _PENALTY_NO_ADD_INFO, # getaddrinfo failed
193
+ "[Errno -2]": _PENALTY_NO_ADD_INFO, # Name or service not known
194
+ # Wrong Password
195
+ "Access denied": _PENALTY_WRONG_PASSW,
196
+ }
197
+ _TIMEOUT_PENALTIES_BY_ERR_NO = {1053: _PENALTY_RESTARTING}
198
+ _SPLIT_RE = re.compile(r",(?![^\(\)]*\))")
199
+ _PRIORITY_RE = re.compile(r"^\(address=(.+),priority=(\d+)\)$", re.VERBOSE)
200
+ _ROUTER_RE = re.compile(r"^\(address=(.+)[,]*\)$", re.VERBOSE)
201
+ _URI_SCHEME_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+\-.]+)://(.*)")
202
+ _SSL_OPTS = [
203
+ "ssl-cert",
204
+ "ssl-ca",
205
+ "ssl-key",
206
+ "ssl-crl",
207
+ "tls-versions",
208
+ "tls-ciphersuites",
209
+ ]
210
+ _SESS_OPTS = _SSL_OPTS + [
211
+ "user",
212
+ "password",
213
+ "schema",
214
+ "host",
215
+ "port",
216
+ "routers",
217
+ "socket",
218
+ "ssl-mode",
219
+ "auth",
220
+ "use-pure",
221
+ "connect-timeout",
222
+ "connection-attributes",
223
+ "compression",
224
+ "compression-algorithms",
225
+ "dns-srv",
226
+ ]
227
+
228
+
229
+ def generate_pool_name(**kwargs: Any) -> str:
230
+ """Generate a pool name.
231
+
232
+ This function takes keyword arguments, usually the connection arguments and
233
+ tries to generate a name for the pool.
234
+
235
+ Args:
236
+ **kwargs: Arbitrary keyword arguments with the connection arguments.
237
+
238
+ Raises:
239
+ PoolError: If the name can't be generated.
240
+
241
+ Returns:
242
+ str: The generated pool name.
243
+ """
244
+ parts = []
245
+ for key in ("host", "port", "user", "database", "client_id"):
246
+ try:
247
+ parts.append(str(kwargs[key]))
248
+ except KeyError:
249
+ pass
250
+
251
+ if not parts:
252
+ raise PoolError("Failed generating pool name; specify pool_name")
253
+
254
+ return "_".join(parts)
255
+
256
+
257
+ def update_timeout_penalties_by_error(penalty_dict: Mapping[str, Any]) -> None:
258
+ """Update the timeout penalties directory.
259
+
260
+ Update the timeout penalties by error dictionary used to deactivate a pool.
261
+ Args:
262
+ penalty_dict (dict): The dictionary with the new timeouts.
263
+ """
264
+ if penalty_dict and isinstance(penalty_dict, dict):
265
+ _TIMEOUT_PENALTIES_BY_ERR_NO.update(penalty_dict)
266
+
267
+
268
+ class SocketStream:
269
+ """Implements a socket stream."""
270
+
271
+ def __init__(self) -> None:
272
+ self._socket: Optional[socket.socket] = None
273
+ self._is_ssl: bool = False
274
+ self._is_socket: bool = False
275
+ self._host: Optional[str] = None
276
+
277
+ def connect(self, params: Tuple, connect_timeout: float = _CONNECT_TIMEOUT) -> None:
278
+ """Connects to a TCP service.
279
+
280
+ Args:
281
+ params (tuple): The connection parameters.
282
+
283
+ Raises:
284
+ :class:`mysqlx.InterfaceError`: If Unix socket is not supported.
285
+ """
286
+ if connect_timeout is not None:
287
+ connect_timeout = connect_timeout / 1000 # Convert to seconds
288
+ try:
289
+ self._socket = socket.create_connection(params, connect_timeout)
290
+ self._host = params[0]
291
+ except ValueError:
292
+ try:
293
+ self._socket = socket.socket(socket.AF_UNIX)
294
+ self._socket.settimeout(connect_timeout)
295
+ self._socket.connect(params)
296
+ self._is_socket = True
297
+ except AttributeError:
298
+ raise InterfaceError("Unix socket unsupported") from None
299
+ self._socket.settimeout(None)
300
+
301
+ def read(self, count: int) -> bytes:
302
+ """Receive data from the socket.
303
+
304
+ Args:
305
+ count (int): Buffer size.
306
+
307
+ Returns:
308
+ bytes: The data received.
309
+ """
310
+ if self._socket is None:
311
+ raise OperationalError("MySQLx Connection not available")
312
+ buf = []
313
+ while count > 0:
314
+ data = self._socket.recv(count)
315
+ if data == b"":
316
+ raise RuntimeError("Unexpected connection close")
317
+ buf.append(data)
318
+ count -= len(data)
319
+ return b"".join(buf)
320
+
321
+ def sendall(self, data: bytes) -> None:
322
+ """Send data to the socket.
323
+
324
+ Args:
325
+ data (bytes): The data to be sent.
326
+ """
327
+ if self._socket is None:
328
+ raise OperationalError("MySQLx Connection not available")
329
+ try:
330
+ self._socket.sendall(data)
331
+ except OSError as err:
332
+ raise OperationalError(f"Unexpected socket error: {err}") from err
333
+
334
+ def close(self) -> None:
335
+ """Close the socket."""
336
+ if not self._socket:
337
+ return
338
+ try:
339
+ self._socket.shutdown(socket.SHUT_RDWR)
340
+ self._socket.close()
341
+ except OSError:
342
+ # On [Errno 107] Transport endpoint is not connected
343
+ pass
344
+ self._socket = None
345
+
346
+ def __del__(self) -> None:
347
+ self.close()
348
+
349
+ def set_ssl(
350
+ self,
351
+ ssl_protos: List[str],
352
+ ssl_mode: str,
353
+ ssl_ca: str,
354
+ ssl_crl: str,
355
+ ssl_cert: str,
356
+ ssl_key: str,
357
+ ssl_ciphers: List[str],
358
+ ) -> None:
359
+ """Set SSL parameters.
360
+
361
+ Args:
362
+ ssl_protos (list): SSL protocol to use.
363
+ ssl_mode (str): SSL mode.
364
+ ssl_ca (str): The certification authority certificate.
365
+ ssl_crl (str): The certification revocation lists.
366
+ ssl_cert (str): The certificate.
367
+ ssl_key (str): The certificate key.
368
+ ssl_ciphers (list): SSL ciphersuites to use.
369
+
370
+ Raises:
371
+ :class:`mysqlx.RuntimeError`: If Python installation has no SSL
372
+ support.
373
+ :class:`mysqlx.InterfaceError`: If the parameters are invalid.
374
+ """
375
+ if not SSL_AVAILABLE:
376
+ self.close()
377
+ raise RuntimeError("Python installation has no SSL support")
378
+
379
+ if ssl_protos is None or not ssl_protos:
380
+ # `check_hostname` is True by default
381
+ context = ssl.create_default_context()
382
+ if ssl_mode != SSLMode.VERIFY_IDENTITY:
383
+ context.check_hostname = False
384
+ if ssl_mode == SSLMode.REQUIRED:
385
+ context.verify_mode = ssl.CERT_NONE
386
+ else:
387
+ ssl_protos.sort(reverse=True)
388
+ tls_version = ssl_protos[0]
389
+ if (
390
+ not TLS_V1_3_SUPPORTED
391
+ and tls_version == "TLSv1.3"
392
+ and len(ssl_protos) > 1
393
+ ):
394
+ tls_version = ssl_protos[1]
395
+ ssl_protocol = TLS_VERSIONS[tls_version]
396
+ context = ssl.SSLContext(ssl_protocol)
397
+
398
+ if tls_version == "TLSv1.3":
399
+ if "TLSv1.2" not in ssl_protos:
400
+ context.options |= ssl.OP_NO_TLSv1_2
401
+ if "TLSv1.1" not in ssl_protos:
402
+ context.options |= ssl.OP_NO_TLSv1_1
403
+ if "TLSv1" not in ssl_protos:
404
+ context.options |= ssl.OP_NO_TLSv1
405
+
406
+ context.check_hostname = ssl_mode == SSLMode.VERIFY_IDENTITY
407
+
408
+ if ssl_ca:
409
+ try:
410
+ context.load_verify_locations(ssl_ca)
411
+ context.verify_mode = ssl.CERT_REQUIRED
412
+ except (IOError, ssl.SSLError) as err:
413
+ self.close()
414
+ raise InterfaceError(f"Invalid CA Certificate: {err}") from err
415
+
416
+ if ssl_crl:
417
+ try:
418
+ context.load_verify_locations(ssl_crl)
419
+ context.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
420
+ except (IOError, ssl.SSLError) as err:
421
+ self.close()
422
+ raise InterfaceError(f"Invalid CRL: {err}") from err
423
+
424
+ if ssl_cert:
425
+ try:
426
+ context.load_cert_chain(ssl_cert, ssl_key)
427
+ except (IOError, ssl.SSLError) as err:
428
+ self.close()
429
+ raise InterfaceError(f"Invalid Certificate/Key: {err}") from err
430
+
431
+ if ssl_ciphers:
432
+ context.set_ciphers(
433
+ ":".join(iani_to_openssl_cs_name(ssl_protos[0], ssl_ciphers))
434
+ )
435
+ try:
436
+ self._socket = context.wrap_socket(self._socket, server_hostname=self._host)
437
+ except ssl.CertificateError as err:
438
+ raise InterfaceError(f"{err}") from err
439
+
440
+ self._is_ssl = True
441
+
442
+ # Raise a deprecation warning if a deprecated TLS cipher or
443
+ # version is being used.
444
+ cipher, tls_version, _ = self._socket.cipher()
445
+ warn_tls_version_deprecated(tls_version)
446
+ warn_ciphersuites_deprecated(cipher, tls_version)
447
+
448
+ def is_ssl(self) -> bool:
449
+ """Verifies if SSL is being used.
450
+
451
+ Returns:
452
+ bool: Returns `True` if SSL is being used.
453
+ """
454
+ return self._is_ssl
455
+
456
+ def is_socket(self) -> bool:
457
+ """Verifies if socket connection is being used.
458
+
459
+ Returns:
460
+ bool: Returns `True` if socket connection is being used.
461
+ """
462
+ return self._is_socket
463
+
464
+ def is_secure(self) -> bool:
465
+ """Verifies if connection is secure.
466
+
467
+ Returns:
468
+ bool: Returns `True` if connection is secure.
469
+ """
470
+ return self._is_ssl or self._is_socket
471
+
472
+ def is_open(self) -> bool:
473
+ """Verifies if connection is open.
474
+
475
+ Returns:
476
+ bool: Returns `True` if connection is open.
477
+ """
478
+ return self._socket is not None
479
+
480
+
481
+ def catch_network_exception(func: Callable) -> Callable:
482
+ """Decorator used to catch OSError or RuntimeError.
483
+
484
+ Raises:
485
+ :class:`mysqlx.InterfaceError`: If `OSError` or `RuntimeError`
486
+ is raised.
487
+ """
488
+
489
+ @wraps(func)
490
+ def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
491
+ """Wrapper function."""
492
+ try:
493
+ if (
494
+ isinstance(self, (Connection, PooledConnection))
495
+ and self.is_server_disconnected()
496
+ ):
497
+ raise InterfaceError(*self.get_disconnected_reason())
498
+ result = func(self, *args, **kwargs)
499
+ if isinstance(result, BaseResult):
500
+ warns: Any = result.get_warnings()
501
+ for warn in warns:
502
+ if warn["code"] in CONNECTION_CLOSED_ERROR:
503
+ error_msg = CONNECTION_CLOSED_ERROR[warn["code"]]
504
+ reason = (
505
+ f"Connection close: {warn['msg']}: {error_msg}",
506
+ warn["code"],
507
+ )
508
+ if isinstance(self, (Connection, PooledConnection)):
509
+ self.set_server_disconnected(reason)
510
+ break
511
+ return result
512
+ except (InterfaceError, OSError, RuntimeError, TimeoutError) as err:
513
+ if (
514
+ func.__name__ == "get_column_metadata"
515
+ and args
516
+ and isinstance(args[0], SqlResult)
517
+ ):
518
+ warns = args[0].get_warnings()
519
+ if warns:
520
+ warn = warns[0]
521
+ error_msg = CONNECTION_CLOSED_ERROR[warn["code"]]
522
+ reason = (
523
+ f"Connection close: {warn['msg']}: {error_msg}",
524
+ warn["code"],
525
+ )
526
+ if isinstance(self, PooledConnection):
527
+ self.pool.remove_connections()
528
+ # pool must be listed as faulty if server is shutting down
529
+ if warn["code"] == 1053:
530
+ PoolsManager().set_pool_unavailable(
531
+ self.pool, InterfaceError(*reason)
532
+ )
533
+ if isinstance(self, (Connection, PooledConnection)):
534
+ self.set_server_disconnected(reason)
535
+ self.disconnect()
536
+ raise InterfaceError(*reason) from err
537
+ self.disconnect()
538
+ raise
539
+
540
+ return wrapper
541
+
542
+
543
+ class Router(dict):
544
+ """Represents a set of connection parameters.
545
+
546
+ Args:
547
+ settings (dict): Dictionary with connection settings
548
+ .. versionadded:: 8.0.20
549
+ """
550
+
551
+ def __init__(self, connection_params: Mapping[str, Any]) -> None:
552
+ super().__init__()
553
+ self.update(connection_params)
554
+ self["available"] = self.get("available", True)
555
+
556
+ def available(self) -> bool:
557
+ """Verifies if the Router is available to open connections.
558
+
559
+ Returns:
560
+ bool: True if this Router is available else False.
561
+ """
562
+ return self["available"]
563
+
564
+ def set_unavailable(self) -> None:
565
+ """Sets this Router unavailable to open connections."""
566
+ self["available"] = False
567
+
568
+ def get_connection_params(self) -> Union[str, Tuple[str, Optional[int]]]:
569
+ """Verifies if the Router is available to open connections.
570
+
571
+ Returns:
572
+ tuple: host and port or socket information tuple.
573
+ """
574
+ if "socket" in self:
575
+ return self["socket"]
576
+ return (self["host"], self["port"])
577
+
578
+
579
+ class RouterManager:
580
+ """Manages the connection parameters of all the routers.
581
+
582
+ Args:
583
+ Routers (list): A list of Router objects.
584
+ settings (dict): Dictionary with connection settings.
585
+ .. versionadded:: 8.0.20
586
+ """
587
+
588
+ def __init__(self, routers: List[Router], settings: Dict[str, Any]) -> None:
589
+ self._routers = routers
590
+ self._settings = settings
591
+ self._cur_priority_idx: int = 0
592
+ self._can_failover: bool = True
593
+ # Reuters status
594
+ self._routers_directory: Dict[int, List[Router]] = {}
595
+ self.routers_priority_list: List[int] = []
596
+ self._ensure_priorities()
597
+
598
+ def _ensure_priorities(self) -> None:
599
+ """Ensure priorities.
600
+
601
+ Raises:
602
+ :class:`mysqlx.ProgrammingError`: If priorities are invalid.
603
+ """
604
+ priority_count = 0
605
+
606
+ for router in self._routers:
607
+ priority = router.get("priority", None)
608
+ if priority is None:
609
+ priority_count += 1
610
+ router["priority"] = 100
611
+ elif priority > 100:
612
+ raise ProgrammingError("The priorities must be between 0 and 100", 4007)
613
+
614
+ if 0 < priority_count < len(self._routers):
615
+ raise ProgrammingError(
616
+ "You must either assign no priority to any "
617
+ "of the routers or give a priority for "
618
+ "every router",
619
+ 4000,
620
+ )
621
+
622
+ self._routers.sort(key=lambda x: x["priority"], reverse=True)
623
+
624
+ # Group servers with the same priority
625
+ for router in self._routers:
626
+ priority = router["priority"]
627
+ if priority not in self._routers_directory:
628
+ self._routers_directory[priority] = [Router(router)]
629
+ self.routers_priority_list.append(priority)
630
+ else:
631
+ self._routers_directory[priority].append(Router(router))
632
+
633
+ def _get_available_routers(self, priority: int) -> List[Router]:
634
+ """Get a list of the current available routers that shares the given priority.
635
+
636
+ Returns:
637
+ list: A list of the current available routers.
638
+ """
639
+ router_list = self._routers_directory[priority]
640
+ router_list = [router for router in router_list if router.available()]
641
+ return router_list
642
+
643
+ def _get_random_connection_params(self, priority: int) -> Router:
644
+ """Get a random router from the group with the given priority.
645
+
646
+ Returns:
647
+ Router: A random router.
648
+ """
649
+ router_list = self._get_available_routers(priority)
650
+ if not router_list:
651
+ return None
652
+ if len(router_list) == 1:
653
+ return router_list[0]
654
+
655
+ last = len(router_list) - 1
656
+ index = random.randint(0, last)
657
+ return router_list[index]
658
+
659
+ def can_failover(self) -> bool:
660
+ """Returns the next connection parameters.
661
+
662
+ Returns:
663
+ bool: True if there is more server to failover to else False.
664
+ """
665
+ return self._can_failover
666
+
667
+ def get_next_router(self) -> Router:
668
+ """Returns the next connection parameters.
669
+
670
+ Returns:
671
+ Router: with the connection parameters.
672
+ """
673
+ if not self._routers:
674
+ self._can_failover = False
675
+ router_settings = self._settings.copy()
676
+ router_settings["host"] = self._settings.get("host", "localhost")
677
+ router_settings["port"] = self._settings.get("port", 33060)
678
+ return Router(router_settings)
679
+
680
+ cur_priority = self.routers_priority_list[self._cur_priority_idx]
681
+ routers_priority_len = len(self.routers_priority_list)
682
+
683
+ search = True
684
+ while search:
685
+ router = self._get_random_connection_params(cur_priority)
686
+
687
+ if router is not None or self._cur_priority_idx >= routers_priority_len:
688
+ if (
689
+ self._cur_priority_idx == routers_priority_len - 1
690
+ and len(self._get_available_routers(cur_priority)) < 2
691
+ ):
692
+ self._can_failover = False
693
+ break
694
+
695
+ # Search on next group
696
+ self._cur_priority_idx += 1
697
+ if self._cur_priority_idx < routers_priority_len:
698
+ cur_priority = self.routers_priority_list[self._cur_priority_idx]
699
+
700
+ return router
701
+
702
+ def get_routers_directory(self) -> Dict[int, List[Router]]:
703
+ """Returns the directory containing all the routers managed.
704
+
705
+ Returns:
706
+ dict: Dictionary with priorities as connection settings.
707
+ """
708
+ return self._routers_directory
709
+
710
+
711
+ class Connection:
712
+ """Connection to a MySQL Server.
713
+
714
+ Args:
715
+ settings (dict): Dictionary with connection settings.
716
+ """
717
+
718
+ def __init__(self, settings: Dict[str, Any]) -> None:
719
+ self.settings: Dict[str, Any] = settings
720
+ self.stream: SocketStream = SocketStream()
721
+ self.protocol: Optional[Protocol] = None
722
+ self.keep_open: Optional[bool] = None
723
+ self._user: Optional[str] = settings.get("user")
724
+ self._password: Optional[str] = settings.get("password")
725
+ self._schema: Optional[str] = settings.get("schema")
726
+ self._active_result: Optional[ResultBaseType] = None
727
+ self._routers: List[Router] = settings.get("routers", [])
728
+
729
+ if "host" in settings and settings["host"]:
730
+ self._routers.append(
731
+ { # type: ignore[arg-type]
732
+ "host": settings.get("host"),
733
+ "port": settings.get("port", None),
734
+ }
735
+ )
736
+
737
+ self.router_manager: RouterManager = RouterManager(self._routers, settings)
738
+ self._connect_timeout: Optional[int] = settings.get(
739
+ "connect-timeout", _CONNECT_TIMEOUT
740
+ )
741
+ if self._connect_timeout == 0:
742
+ # None is assigned if connect timeout is 0, which disables timeouts
743
+ # on socket operations
744
+ self._connect_timeout = None
745
+
746
+ self._stmt_counter: int = 0
747
+ self._prepared_stmt_ids: List[int] = []
748
+ self._prepared_stmt_supported: bool = True
749
+ self._server_disconnected: bool = False
750
+ self._server_disconnected_reason: Optional[Union[str, Tuple[str, int]]] = None
751
+
752
+ def fetch_active_result(self) -> None:
753
+ """Fetch active result."""
754
+ if self._active_result is not None:
755
+ self._active_result.fetch_all()
756
+ self._active_result = None
757
+
758
+ def set_active_result(self, result: ResultBaseType) -> None:
759
+ """Set active result.
760
+
761
+ Args:
762
+ `Result`: It can be :class:`mysqlx.Result`,
763
+ :class:`mysqlx.BufferingResult`,
764
+ :class:`mysqlx.RowResult`, :class:`mysqlx.SqlResult` or
765
+ :class:`mysqlx.DocResult`.
766
+ """
767
+ self._active_result = result
768
+
769
+ def connect(self) -> None:
770
+ """Attempt to connect to the MySQL server.
771
+
772
+ Raises:
773
+ :class:`mysqlx.InterfaceError`: If fails to connect to the MySQL
774
+ server.
775
+ :class:`mysqlx.TimeoutError`: If connect timeout was exceeded.
776
+ """
777
+ # Loop and check
778
+ error = None
779
+ while self.router_manager.can_failover():
780
+ try:
781
+ router = self.router_manager.get_next_router()
782
+ self.stream.connect(
783
+ router.get_connection_params(), self._connect_timeout # type: ignore[arg-type]
784
+ )
785
+ reader = MessageReader(self.stream)
786
+ writer = MessageWriter(self.stream)
787
+ self.protocol = Protocol(reader, writer)
788
+
789
+ caps_data = self.protocol.get_capabilites().capabilities
790
+ caps = (
791
+ {get_item_or_attr(cap, "name").lower(): cap for cap in caps_data}
792
+ if caps_data
793
+ else {}
794
+ )
795
+
796
+ # Set TLS capabilities
797
+ self._set_tls_capabilities(caps)
798
+
799
+ # Set connection attributes capabilities
800
+ if "attributes" in self.settings:
801
+ conn_attrs = self.settings["attributes"]
802
+ self.protocol.set_capabilities(session_connect_attrs=conn_attrs)
803
+
804
+ # Set compression capabilities
805
+ compression = self.settings.get("compression", Compression.PREFERRED)
806
+ algorithms = self.settings.get("compression-algorithms")
807
+ algorithm = (
808
+ None
809
+ if compression == Compression.DISABLED
810
+ else self._set_compression_capabilities(
811
+ caps, compression, algorithms
812
+ )
813
+ )
814
+ self._authenticate()
815
+ self.protocol.set_compression(algorithm)
816
+ return
817
+ except (OSError, RuntimeError) as err:
818
+ error = err
819
+ router.set_unavailable()
820
+
821
+ # Python 2.7 does not raise a socket.timeout exception when using
822
+ # settimeout(), but it raises a socket.error with errno.EAGAIN (11)
823
+ # or errno.EINPROGRESS (115) if connect-timeout value is too low
824
+ if error is not None and isinstance(error, socket.timeout):
825
+ if len(self._routers) <= 1:
826
+ raise TimeoutError(
827
+ "Connection attempt to the server was aborted. "
828
+ f"Timeout of {self._connect_timeout} ms was exceeded"
829
+ )
830
+ raise TimeoutError(
831
+ "All server connection attempts were aborted. "
832
+ f"Timeout of {self._connect_timeout} ms was exceeded for each "
833
+ "selected server"
834
+ )
835
+ if len(self._routers) <= 1:
836
+ raise InterfaceError(f"Cannot connect to host: {error}")
837
+ raise InterfaceError("Unable to connect to any of the target hosts", 4001)
838
+
839
+ def _set_tls_capabilities(self, caps: Dict[str, Any]) -> None:
840
+ """Set the TLS capabilities.
841
+
842
+ Args:
843
+ caps (dict): Dictionary with the server capabilities.
844
+
845
+ Raises:
846
+ :class:`mysqlx.OperationalError`: If SSL is not enabled at the
847
+ server.
848
+ :class:`mysqlx.RuntimeError`: If support for SSL is not available
849
+ in Python.
850
+
851
+ .. versionadded:: 8.0.21
852
+ """
853
+ if self.settings.get("ssl-mode") == SSLMode.DISABLED:
854
+ return
855
+
856
+ if self.stream.is_socket():
857
+ if self.settings.get("ssl-mode"):
858
+ logger.warning("SSL not required when using Unix socket.")
859
+ return
860
+
861
+ if "tls" not in caps:
862
+ self.close_connection()
863
+ raise OperationalError("SSL not enabled at server")
864
+
865
+ is_ol7 = False
866
+ if platform.system() == "Linux":
867
+ distname, version, _ = linux_distribution()
868
+ try:
869
+ is_ol7 = "Oracle Linux" in distname and version.split(".")[0] == "7"
870
+ except IndexError:
871
+ is_ol7 = False
872
+
873
+ if sys.version_info < (2, 7, 9) and not is_ol7:
874
+ self.close_connection()
875
+ raise RuntimeError(
876
+ "The support for SSL is not available for this Python version"
877
+ )
878
+
879
+ self.protocol.set_capabilities(tls=True)
880
+ self.stream.set_ssl(
881
+ self.settings.get("tls-versions", None),
882
+ self.settings.get("ssl-mode", SSLMode.REQUIRED),
883
+ self.settings.get("ssl-ca"),
884
+ self.settings.get("ssl-crl"),
885
+ self.settings.get("ssl-cert"),
886
+ self.settings.get("ssl-key"),
887
+ self.settings.get("tls-ciphersuites"),
888
+ )
889
+ if "attributes" in self.settings:
890
+ conn_attrs = self.settings["attributes"]
891
+ self.protocol.set_capabilities(session_connect_attrs=conn_attrs)
892
+
893
+ def _set_compression_capabilities(
894
+ self,
895
+ caps: Dict[str, Any],
896
+ compression: str,
897
+ algorithms: Optional[List[str]] = None,
898
+ ) -> Optional[str]:
899
+ """Set the compression capabilities.
900
+
901
+ If compression is available, negociates client and server algorithms.
902
+ By trying to find an algorithm from the requested compression
903
+ algorithms list, which is supported by the server.
904
+
905
+ If no compression algorithms list is provided, the following priority
906
+ is used:
907
+
908
+ 1) zstd_stream
909
+ 2) lz4_message
910
+ 3) deflate_stream
911
+
912
+ Args:
913
+ caps (dict): Dictionary with the server capabilities.
914
+ compression (str): The compression connection setting.
915
+ algorithms (list): List of requested compression algorithms.
916
+
917
+ Returns:
918
+ str: The compression algorithm.
919
+
920
+ .. versionadded:: 8.0.21
921
+ .. versionchanged:: 8.0.22
922
+ """
923
+ compression_data = caps.get("compression")
924
+ if compression_data is None:
925
+ msg = "Compression requested but the server does not support it"
926
+ if compression == Compression.REQUIRED:
927
+ raise NotSupportedError(msg)
928
+ logger.warning(msg)
929
+ return None
930
+
931
+ compression_dict = {}
932
+ if isinstance(compression_data, dict): # C extension is being used
933
+ for fld in compression_data["value"]["obj"]["fld"]:
934
+ compression_dict[fld["key"]] = [
935
+ value["scalar"]["v_string"]["value"].decode("utf-8")
936
+ for value in fld["value"]["array"]["value"]
937
+ ]
938
+ else:
939
+ for fld in compression_data.value.obj.fld:
940
+ compression_dict[fld.key] = [
941
+ value.scalar.v_string.value.decode("utf-8")
942
+ for value in fld.value.array.value
943
+ ]
944
+
945
+ server_algorithms = compression_dict.get("algorithm", [])
946
+ algorithm = None
947
+
948
+ # Try to find an algorithm from the requested compression algorithms
949
+ # list, which is supported by the server
950
+ if algorithms:
951
+ # Resolve compression algorithms aliases and ignore unsupported
952
+ client_algorithms = [
953
+ COMPRESSION_ALGORITHMS[item]
954
+ for item in algorithms
955
+ if item in COMPRESSION_ALGORITHMS
956
+ ]
957
+ matched = [item for item in client_algorithms if item in server_algorithms]
958
+ if matched:
959
+ algorithm = COMPRESSION_ALGORITHMS.get(matched[0])
960
+ elif compression == Compression.REQUIRED:
961
+ raise InterfaceError(
962
+ "The connection compression is set as "
963
+ "required, but none of the provided "
964
+ "compression algorithms are supported."
965
+ )
966
+ else:
967
+ return None # Disable compression
968
+
969
+ # No compression algorithms list was provided or couldn't found one
970
+ # supported by the server
971
+ if algorithm is None:
972
+ if HAVE_ZSTD and "zstd_stream" in server_algorithms:
973
+ algorithm = "zstd_stream"
974
+ elif HAVE_LZ4 and "lz4_message" in server_algorithms:
975
+ algorithm = "lz4_message"
976
+ else:
977
+ algorithm = "deflate_stream"
978
+
979
+ if algorithm not in server_algorithms:
980
+ msg = (
981
+ "Compression requested but the compression algorithm "
982
+ "negotiation failed"
983
+ )
984
+ if compression == Compression.REQUIRED:
985
+ raise InterfaceError(msg)
986
+ logger.warning(msg)
987
+ return None
988
+
989
+ self.protocol.set_capabilities(compression={"algorithm": algorithm})
990
+ return algorithm
991
+
992
+ def _authenticate(self) -> None:
993
+ """Authenticate with the MySQL server."""
994
+ auth = self.settings.get("auth")
995
+ if auth:
996
+ if auth == Auth.PLAIN:
997
+ self._authenticate_plain()
998
+ elif auth == Auth.SHA256_MEMORY:
999
+ self._authenticate_sha256_memory()
1000
+ elif auth == Auth.MYSQL41:
1001
+ self._authenticate_mysql41()
1002
+ elif self.stream.is_secure():
1003
+ # Use PLAIN if no auth provided and connection is secure
1004
+ self._authenticate_plain()
1005
+ else:
1006
+ # Use MYSQL41 if connection is not secure
1007
+ try:
1008
+ self._authenticate_mysql41()
1009
+ except InterfaceError:
1010
+ pass
1011
+ else:
1012
+ return
1013
+ # Try SHA256_MEMORY if MYSQL41 fails
1014
+ try:
1015
+ self._authenticate_sha256_memory()
1016
+ except InterfaceError as err:
1017
+ raise InterfaceError(
1018
+ "Authentication failed using MYSQL41 and "
1019
+ "SHA256_MEMORY, check username and "
1020
+ f"password or try a secure connection err:{err}"
1021
+ ) from err
1022
+
1023
+ def _authenticate_mysql41(self) -> None:
1024
+ """Authenticate with the MySQL server using `MySQL41AuthPlugin`."""
1025
+ plugin = MySQL41AuthPlugin(self._user, self._password)
1026
+ self.protocol.send_auth_start(plugin.auth_name())
1027
+ extra_data = self.protocol.read_auth_continue()
1028
+ self.protocol.send_auth_continue(plugin.auth_data(extra_data))
1029
+ self.protocol.read_auth_ok()
1030
+
1031
+ def _authenticate_plain(self) -> None:
1032
+ """Authenticate with the MySQL server using `PlainAuthPlugin`."""
1033
+ if not self.stream.is_secure():
1034
+ raise InterfaceError(
1035
+ "PLAIN authentication is not allowed via unencrypted connection"
1036
+ )
1037
+ plugin = PlainAuthPlugin(self._user, self._password)
1038
+ self.protocol.send_auth_start(plugin.auth_name(), auth_data=plugin.auth_data())
1039
+ self.protocol.read_auth_ok()
1040
+
1041
+ def _authenticate_sha256_memory(self) -> None:
1042
+ """Authenticate with the MySQL server using `Sha256MemoryAuthPlugin`."""
1043
+ plugin = Sha256MemoryAuthPlugin(self._user, self._password)
1044
+ self.protocol.send_auth_start(plugin.auth_name())
1045
+ extra_data = self.protocol.read_auth_continue()
1046
+ self.protocol.send_auth_continue(plugin.auth_data(extra_data))
1047
+ self.protocol.read_auth_ok()
1048
+
1049
+ def _deallocate_statement(self, statement: StatementType) -> None:
1050
+ """Deallocates statement.
1051
+
1052
+ Args:
1053
+ statement (Statement): A `Statement` based type object.
1054
+ """
1055
+ if statement.prepared:
1056
+ self.protocol.send_prepare_deallocate(statement.stmt_id)
1057
+ self._prepared_stmt_ids.remove(statement.stmt_id)
1058
+ statement.prepared = False
1059
+
1060
+ def _prepare_statement(
1061
+ self,
1062
+ msg_type: str,
1063
+ msg: MessageType,
1064
+ statement: Union[
1065
+ FindStatement,
1066
+ DeleteStatement,
1067
+ ModifyStatement,
1068
+ ReadStatement,
1069
+ RemoveStatement,
1070
+ UpdateStatement,
1071
+ ],
1072
+ ) -> None:
1073
+ """Prepares a statement.
1074
+
1075
+ Args:
1076
+ msg_type (str): Message ID string.
1077
+ msg (mysqlx.protobuf.Message): MySQL X Protobuf Message.
1078
+ statement (Statement): A `Statement` based type object.
1079
+ """
1080
+ try:
1081
+ self.fetch_active_result()
1082
+ self.protocol.send_prepare_prepare(msg_type, msg, statement)
1083
+ except NotSupportedError:
1084
+ self._prepared_stmt_supported = False
1085
+ return
1086
+ self._prepared_stmt_ids.append(statement.stmt_id)
1087
+ statement.prepared = True
1088
+
1089
+ def _execute_prepared_pipeline(
1090
+ self,
1091
+ msg_type: str,
1092
+ msg: MessageType,
1093
+ statement: Union[
1094
+ FindStatement,
1095
+ DeleteStatement,
1096
+ ModifyStatement,
1097
+ ReadStatement,
1098
+ RemoveStatement,
1099
+ UpdateStatement,
1100
+ ],
1101
+ ) -> None:
1102
+ """Executes the prepared statement pipeline.
1103
+
1104
+ Args:
1105
+ msg_type (str): Message ID string.
1106
+ msg (mysqlx.protobuf.Message): MySQL X Protobuf Message.
1107
+ statement (Statement): A `Statement` based type object.
1108
+ """
1109
+ # For old servers without prepared statement support
1110
+ if not self._prepared_stmt_supported:
1111
+ # Crud::<Operation>
1112
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1113
+ return
1114
+
1115
+ if statement.deallocate_prepare_execute:
1116
+ # Prepare::Deallocate + Prepare::Prepare + Prepare::Execute
1117
+ self._deallocate_statement(statement)
1118
+ self._prepare_statement(msg_type, msg, statement)
1119
+ if not self._prepared_stmt_supported:
1120
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1121
+ return
1122
+ self.protocol.send_prepare_execute(msg_type, msg, statement)
1123
+ statement.deallocate_prepare_execute = False
1124
+ statement.reset_exec_counter()
1125
+ elif statement.prepared and not statement.changed:
1126
+ # Prepare::Execute
1127
+ self.protocol.send_prepare_execute(msg_type, msg, statement)
1128
+ elif statement.changed and not statement.repeated:
1129
+ # Crud::<Operation>
1130
+ self._deallocate_statement(statement)
1131
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1132
+ statement.changed = False
1133
+ statement.reset_exec_counter()
1134
+ elif not statement.changed and not statement.repeated:
1135
+ # Prepare::Prepare + Prepare::Execute
1136
+ if not statement.prepared:
1137
+ self._prepare_statement(msg_type, msg, statement)
1138
+ if not self._prepared_stmt_supported:
1139
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1140
+ return
1141
+ self.protocol.send_prepare_execute(msg_type, msg, statement)
1142
+ elif statement.changed and statement.repeated:
1143
+ # Prepare::Deallocate + Crud::<Operation>
1144
+ self._deallocate_statement(statement)
1145
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1146
+ statement.changed = False
1147
+ statement.reset_exec_counter()
1148
+
1149
+ statement.increment_exec_counter()
1150
+
1151
+ @catch_network_exception
1152
+ def send_sql(self, statement: SqlStatement) -> SqlResult:
1153
+ """Execute a SQL statement.
1154
+
1155
+ Args:
1156
+ sql (str): The SQL statement.
1157
+
1158
+ Raises:
1159
+ :class:`mysqlx.ProgrammingError`: If the SQL statement is not a
1160
+ valid string.
1161
+ """
1162
+ sql = statement.sql
1163
+ if self.protocol is None:
1164
+ raise OperationalError("MySQLx Connection not available")
1165
+ if not isinstance(sql, str):
1166
+ raise ProgrammingError("The SQL statement is not a valid string")
1167
+ msg_type, msg = self.protocol.build_execute_statement("sql", sql)
1168
+ self.protocol.send_msg_without_ps(msg_type, msg, statement)
1169
+ return SqlResult(self)
1170
+
1171
+ @catch_network_exception
1172
+ def send_insert(self, statement: Union[AddStatement, InsertStatement]) -> Result:
1173
+ """Send an insert statement.
1174
+
1175
+ Args:
1176
+ statement (`Statement`): It can be :class:`mysqlx.InsertStatement`
1177
+ or :class:`mysqlx.AddStatement`.
1178
+
1179
+ Returns:
1180
+ :class:`mysqlx.Result`: A result object.
1181
+ """
1182
+ if self.protocol is None:
1183
+ raise OperationalError("MySQLx Connection not available")
1184
+ msg_type, msg = self.protocol.build_insert(statement)
1185
+ self.protocol.send_msg(msg_type, msg)
1186
+ ids = None
1187
+ if isinstance(statement, AddStatement):
1188
+ ids = statement.ids
1189
+ return Result(self, ids)
1190
+
1191
+ @catch_network_exception
1192
+ def send_find(
1193
+ self, statement: Union[FindStatement, SelectStatement]
1194
+ ) -> Union[DocResult, RowResult]:
1195
+ """Send an find statement.
1196
+
1197
+ Args:
1198
+ statement (`Statement`): It can be :class:`mysqlx.SelectStatement`
1199
+ or :class:`mysqlx.FindStatement`.
1200
+
1201
+ Returns:
1202
+ `Result`: It can be class:`mysqlx.DocResult` or
1203
+ :class:`mysqlx.RowResult`.
1204
+ """
1205
+ msg_type, msg = self.protocol.build_find(statement)
1206
+ self._execute_prepared_pipeline(msg_type, msg, statement)
1207
+ return DocResult(self) if statement.is_doc_based() else RowResult(self)
1208
+
1209
+ @catch_network_exception
1210
+ def send_delete(self, statement: Union[DeleteStatement, RemoveStatement]) -> Result:
1211
+ """Send an delete statement.
1212
+
1213
+ Args:
1214
+ statement (`Statement`): It can be :class:`mysqlx.RemoveStatement`
1215
+ or :class:`mysqlx.DeleteStatement`.
1216
+
1217
+ Returns:
1218
+ :class:`mysqlx.Result`: The result object.
1219
+ """
1220
+ msg_type, msg = self.protocol.build_delete(statement)
1221
+ self._execute_prepared_pipeline(msg_type, msg, statement)
1222
+ return Result(self)
1223
+
1224
+ @catch_network_exception
1225
+ def send_update(self, statement: Union[ModifyStatement, UpdateStatement]) -> Result:
1226
+ """Send an delete statement.
1227
+
1228
+ Args:
1229
+ statement (`Statement`): It can be :class:`mysqlx.ModifyStatement`
1230
+ or :class:`mysqlx.UpdateStatement`.
1231
+
1232
+ Returns:
1233
+ :class:`mysqlx.Result`: The result object.
1234
+ """
1235
+ msg_type, msg = self.protocol.build_update(statement)
1236
+ self._execute_prepared_pipeline(msg_type, msg, statement)
1237
+ return Result(self)
1238
+
1239
+ @catch_network_exception
1240
+ def execute_nonquery(
1241
+ self,
1242
+ namespace: str,
1243
+ cmd: str,
1244
+ raise_on_fail: bool,
1245
+ fields: Optional[Dict[str, Any]] = None,
1246
+ ) -> Optional[Result]:
1247
+ """Execute a non query command.
1248
+
1249
+ Args:
1250
+ namespace (str): The namespace.
1251
+ cmd (str): The command.
1252
+ raise_on_fail (bool): `True` to raise on fail.
1253
+ fields (Optional[dict]): The message fields.
1254
+
1255
+ Raises:
1256
+ :class:`mysqlx.OperationalError`: On errors.
1257
+
1258
+ Returns:
1259
+ :class:`mysqlx.Result`: The result object.
1260
+ """
1261
+ try:
1262
+ msg_type, msg = self.protocol.build_execute_statement(
1263
+ namespace, cmd, fields
1264
+ )
1265
+ self.protocol.send_msg(msg_type, msg)
1266
+ return Result(self)
1267
+ except OperationalError:
1268
+ if raise_on_fail:
1269
+ raise
1270
+ return None
1271
+
1272
+ @catch_network_exception
1273
+ def execute_sql_scalar(self, sql: StatementType) -> int:
1274
+ """Execute a SQL scalar.
1275
+
1276
+ Args:
1277
+ sql (str): The SQL statement.
1278
+
1279
+ Raises:
1280
+ :class:`mysqlx.InterfaceError`: If no data found.
1281
+
1282
+ Returns:
1283
+ :class:`mysqlx.Result`: The result.
1284
+ """
1285
+ msg_type, msg = self.protocol.build_execute_statement("sql", sql)
1286
+ self.protocol.send_msg(msg_type, msg)
1287
+ result = RowResult(self)
1288
+ result.fetch_all()
1289
+ if result.count == 0:
1290
+ raise InterfaceError("No data found")
1291
+ return result[0][0] # type: ignore[index]
1292
+
1293
+ @catch_network_exception
1294
+ def get_row_result(self, cmd: str, fields: Dict[str, Any]) -> RowResult:
1295
+ """Returns the row result.
1296
+
1297
+ Args:
1298
+ cmd (str): The command.
1299
+ fields (dict): The message fields.
1300
+
1301
+ Returns:
1302
+ :class:`mysqlx.RowResult`: The result object.
1303
+ """
1304
+ msg_type, msg = self.protocol.build_execute_statement("mysqlx", cmd, fields)
1305
+ self.protocol.send_msg(msg_type, msg)
1306
+ return RowResult(self)
1307
+
1308
+ @catch_network_exception
1309
+ def read_row(self, result: RowResult) -> Optional[MessageType]:
1310
+ """Read row.
1311
+
1312
+ Args:
1313
+ result (:class:`mysqlx.RowResult`): The result object.
1314
+ """
1315
+ return self.protocol.read_row(result)
1316
+
1317
+ @catch_network_exception
1318
+ def close_result(self, result: Result) -> None:
1319
+ """Close result.
1320
+
1321
+ Args:
1322
+ result (:class:`mysqlx.Result`): The result object.
1323
+ """
1324
+ self.protocol.close_result(result)
1325
+
1326
+ @catch_network_exception
1327
+ def get_column_metadata(self, result: Result) -> List[ColumnType]:
1328
+ """Get column metadata.
1329
+
1330
+ Args:
1331
+ result (:class:`mysqlx.Result`): The result object.
1332
+ """
1333
+ return self.protocol.get_column_metadata(result)
1334
+
1335
+ def get_next_statement_id(self) -> int:
1336
+ """Returns the next statement ID.
1337
+
1338
+ Returns:
1339
+ int: A statement ID.
1340
+
1341
+ .. versionadded:: 8.0.16
1342
+ """
1343
+ self._stmt_counter += 1
1344
+ return self._stmt_counter
1345
+
1346
+ def is_open(self) -> bool:
1347
+ """Check if connection is open.
1348
+
1349
+ Returns:
1350
+ bool: `True` if connection is open.
1351
+ """
1352
+ return self.stream.is_open()
1353
+
1354
+ def set_server_disconnected(self, reason: Union[str, Tuple[str, int]]) -> None:
1355
+ """Set the disconnection message from the server.
1356
+
1357
+ Args:
1358
+ reason (str): disconnection reason from the server.
1359
+ """
1360
+ self._server_disconnected = True
1361
+ self._server_disconnected_reason = reason
1362
+
1363
+ def is_server_disconnected(self) -> bool:
1364
+ """Verify if the session has been disconnect from the server.
1365
+
1366
+ Returns:
1367
+ bool: `True` if the connection has been closed from the server
1368
+ otherwise `False`.
1369
+ """
1370
+ return self._server_disconnected
1371
+
1372
+ def get_disconnected_reason(self) -> Optional[Union[str, Tuple[str, int]]]:
1373
+ """Get the disconnection message sent by the server.
1374
+
1375
+ Returns:
1376
+ string: disconnection reason from the server.
1377
+ """
1378
+ return self._server_disconnected_reason
1379
+
1380
+ def disconnect(self) -> None:
1381
+ """Disconnect from server."""
1382
+ if not self.is_open():
1383
+ return
1384
+ self.stream.close()
1385
+
1386
+ def close_session(self) -> None:
1387
+ """Close a sucessfully authenticated session."""
1388
+ if not self.is_open():
1389
+ return
1390
+
1391
+ try:
1392
+ # Fetch any active result
1393
+ self.fetch_active_result()
1394
+ # Deallocate all prepared statements
1395
+ if self._prepared_stmt_supported:
1396
+ for stmt_id in self._prepared_stmt_ids:
1397
+ self.protocol.send_prepare_deallocate(stmt_id)
1398
+ self._stmt_counter = 0
1399
+ # Send session close
1400
+ self.protocol.send_close()
1401
+ self.protocol.read_ok()
1402
+ except (InterfaceError, OperationalError, OSError) as err:
1403
+ logger.warning(
1404
+ "Warning: An error occurred while attempting to close the "
1405
+ "connection: %s",
1406
+ err,
1407
+ )
1408
+ finally:
1409
+ # The remote connection with the server has been lost,
1410
+ # close the connection locally.
1411
+ self.stream.close()
1412
+
1413
+ def reset_session(self) -> None:
1414
+ """Reset a sucessfully authenticated session."""
1415
+ if not self.is_open():
1416
+ return
1417
+ if self._active_result is not None:
1418
+ self._active_result.fetch_all()
1419
+ try:
1420
+ self.keep_open = self.protocol.send_reset(self.keep_open)
1421
+ except (InterfaceError, OperationalError) as err:
1422
+ logger.warning(
1423
+ "Warning: An error occurred while attempting to reset the "
1424
+ "session: %s",
1425
+ err,
1426
+ )
1427
+
1428
+ def close_connection(self) -> None:
1429
+ """Announce to the server that the client wants to close the
1430
+ connection. Discards any session state of the server.
1431
+ """
1432
+ if not self.is_open():
1433
+ return
1434
+ if self._active_result is not None:
1435
+ self._active_result.fetch_all()
1436
+ self.protocol.send_connection_close()
1437
+ self.protocol.read_ok()
1438
+ self.stream.close()
1439
+
1440
+
1441
+ class PooledConnection(Connection):
1442
+ """Class to hold :class:`Connection` instances in a pool.
1443
+
1444
+ PooledConnection is used by :class:`ConnectionPool` to facilitate the
1445
+ connection to return to the pool once is not required, more specifically
1446
+ once the close_session() method is invoked. It works like a normal
1447
+ Connection except for methods like close() and sql().
1448
+
1449
+ The close_session() method will add the connection back to the pool rather
1450
+ than disconnecting from the MySQL server.
1451
+
1452
+ The sql() method is used to execute sql statements.
1453
+
1454
+ Args:
1455
+ pool (ConnectionPool): The pool where this connection must return.
1456
+
1457
+ .. versionadded:: 8.0.13
1458
+ """
1459
+
1460
+ def __init__(self, pool: ConnectionPool) -> None:
1461
+ if not isinstance(pool, ConnectionPool):
1462
+ raise AttributeError("pool should be a ConnectionPool object")
1463
+ super().__init__(pool.cnx_config)
1464
+ self.pool: ConnectionPool = pool
1465
+ self.host: str = pool.cnx_config["host"]
1466
+ self.port: int = pool.cnx_config["port"]
1467
+
1468
+ def close_connection(self) -> None:
1469
+ """Closes the connection.
1470
+
1471
+ This method closes the socket.
1472
+ """
1473
+ super().close_session()
1474
+
1475
+ def close_session(self) -> None:
1476
+ """Do not close, but add connection back to pool.
1477
+
1478
+ The close_session() method does not close the connection with the
1479
+ MySQL server. The connection is added back to the pool so it
1480
+ can be reused.
1481
+
1482
+ When the pool is configured to reset the session, the session
1483
+ state will be cleared by re-authenticating the user once the connection
1484
+ is get from the pool.
1485
+ """
1486
+ self.pool.add_connection(self)
1487
+
1488
+ def reconnect(self) -> None:
1489
+ """Reconnect this connection."""
1490
+ if self._active_result is not None:
1491
+ self._active_result.fetch_all()
1492
+ self._authenticate()
1493
+
1494
+ def reset(self) -> None:
1495
+ """Reset the connection.
1496
+
1497
+ Resets the connection by re-authenticate.
1498
+ """
1499
+ self.reconnect()
1500
+
1501
+ def sql(self, sql: str) -> SqlStatement:
1502
+ """Creates a :class:`mysqlx.SqlStatement` object to allow running the
1503
+ SQL statement on the target MySQL Server.
1504
+
1505
+ Args:
1506
+ sql (string): The SQL statement to be executed.
1507
+
1508
+ Returns:
1509
+ mysqlx.SqlStatement: SqlStatement object.
1510
+ """
1511
+ return SqlStatement(self, sql)
1512
+
1513
+
1514
+ class ConnectionPool(queue.Queue):
1515
+ """This class represents a pool of connections.
1516
+
1517
+ Initializes the Pool with the given name and settings.
1518
+
1519
+ Args:
1520
+ name (str): The name of the pool, used to track a single pool per
1521
+ combination of host and user.
1522
+ **kwargs:
1523
+ max_size (int): The maximun number of connections to hold in
1524
+ the pool.
1525
+ reset_session (bool): If the connection should be reseted when
1526
+ is taken from the pool.
1527
+ max_idle_time (int): The maximum number of milliseconds to allow
1528
+ a connection to be idle in the queue before
1529
+ being closed. Zero value means infinite.
1530
+ queue_timeout (int): The maximum number of milliseconds a
1531
+ request will wait for a connection to
1532
+ become available. A zero value means
1533
+ infinite.
1534
+ priority (int): The router priority, to choose this pool over
1535
+ other with lower priority.
1536
+
1537
+ Raises:
1538
+ :class:`mysqlx.PoolError` on errors.
1539
+
1540
+ .. versionadded:: 8.0.13
1541
+ """
1542
+
1543
+ def __init__(self, name: str, **kwargs: Any) -> None:
1544
+ self.name: Optional[str] = None
1545
+ self._set_pool_name(name)
1546
+ self._open_sessions: int = 0
1547
+ self._connections_openned: List[PooledConnection] = []
1548
+ self._available: bool = True
1549
+ self._timeout: int = 0
1550
+ self._timeout_stamp: datetime = datetime.now()
1551
+ self.pool_max_size: int = kwargs.get("max_size", 25)
1552
+ # Can't invoke super due to Queue not is a new-style class
1553
+ queue.Queue.__init__(self, self.pool_max_size)
1554
+ self.reset_session: bool = kwargs.get("reset_session", True)
1555
+ self.max_idle_time: int = kwargs.get("max_idle_time", 25)
1556
+ self.settings: Dict[str, Any] = kwargs
1557
+ self.queue_timeout: int = kwargs.get("queue_timeout", 25)
1558
+ self.priority: int = kwargs.get("priority", 0)
1559
+ self.cnx_config: Dict[str, Any] = kwargs
1560
+ self.host: str = kwargs["host"]
1561
+ self.port: int = kwargs["port"]
1562
+
1563
+ def _set_pool_name(self, pool_name: str) -> None:
1564
+ r"""Set the name of the pool.
1565
+
1566
+ This method checks the validity and sets the name of the pool.
1567
+
1568
+ Args:
1569
+ pool_name (str): The pool name.
1570
+
1571
+ Raises:
1572
+ AttributeError: If the pool_name contains illegal characters
1573
+ ([^a-zA-Z0-9._\-*$#]) or is longer than
1574
+ connection._CNX_POOL_MAX_NAME_SIZE.
1575
+ """
1576
+ if _CNX_POOL_NAME_REGEX.search(pool_name):
1577
+ raise AttributeError(f"Pool name '{pool_name}' contains illegal characters")
1578
+ if len(pool_name) > _CNX_POOL_MAX_NAME_SIZE:
1579
+ raise AttributeError(f"Pool name '{pool_name}' is too long")
1580
+ self.name = pool_name
1581
+
1582
+ @property
1583
+ def open_connections(self) -> int:
1584
+ """Returns the number of open connections that can return to this pool."""
1585
+ return len(self._connections_openned)
1586
+
1587
+ def remove_connection(self, cnx: Optional[PooledConnection] = None) -> None:
1588
+ """Removes a connection from this pool.
1589
+
1590
+ Args:
1591
+ cnx (PooledConnection): The connection object.
1592
+ """
1593
+ self._connections_openned.remove(cnx)
1594
+
1595
+ def remove_connections(self) -> None:
1596
+ """Removes all the connections from the pool."""
1597
+ while self.qsize() > 0:
1598
+ try:
1599
+ cnx = self.get(block=True, timeout=self.queue_timeout)
1600
+ except queue.Empty:
1601
+ pass
1602
+ else:
1603
+ try:
1604
+ cnx.close_connection()
1605
+ except (RuntimeError, OSError, InterfaceError):
1606
+ pass
1607
+ finally:
1608
+ self.remove_connection(cnx)
1609
+
1610
+ def add_connection(self, cnx: Optional[PooledConnection] = None) -> None:
1611
+ """Adds a connection to this pool.
1612
+
1613
+ This method instantiates a Connection using the configuration passed
1614
+ when initializing the ConnectionPool instance or using the set_config()
1615
+ method.
1616
+ If cnx is a Connection instance, it will be added to the queue.
1617
+
1618
+ Args:
1619
+ cnx (PooledConnection): The connection object.
1620
+
1621
+ Raises:
1622
+ PoolError: If no configuration is set, if no more connection can
1623
+ be added (maximum reached) or if the connection can not
1624
+ be instantiated.
1625
+ """
1626
+ if not self.cnx_config:
1627
+ raise PoolError("Connection configuration not available")
1628
+
1629
+ if self.full():
1630
+ raise PoolError("Failed adding connection; queue is full")
1631
+
1632
+ if not cnx:
1633
+ cnx = PooledConnection(self)
1634
+ # mysqlx_wait_timeout is only available on MySQL 8
1635
+ ver = cnx.sql(_SELECT_VERSION_QUERY).execute().fetch_all()[0][0]
1636
+ if tuple(int(n) for n in ver.split("-")[0].split(".")) > (
1637
+ 8,
1638
+ 0,
1639
+ 10,
1640
+ ):
1641
+ cnx.sql(f"set mysqlx_wait_timeout = {self.max_idle_time}").execute()
1642
+ self._connections_openned.append(cnx)
1643
+ else:
1644
+ if not isinstance(cnx, PooledConnection):
1645
+ raise PoolError("Connection instance not subclass of PooledSession")
1646
+ if cnx.is_server_disconnected():
1647
+ self.remove_connections()
1648
+ cnx.close() # type: ignore[attr-defined]
1649
+
1650
+ self.queue_connection(cnx)
1651
+
1652
+ def queue_connection(self, cnx: PooledConnection) -> None:
1653
+ """Put connection back in the queue:
1654
+
1655
+ This method is putting a connection back in the queue.
1656
+ It will not acquire a lock as the methods using _queue_connection() will
1657
+ have it set.
1658
+
1659
+ Args:
1660
+ PooledConnection: The connection object.
1661
+
1662
+ Raises:
1663
+ PoolError: On errors.
1664
+ """
1665
+ if not isinstance(cnx, PooledConnection):
1666
+ raise PoolError("Connection instance not subclass of PooledSession.")
1667
+
1668
+ # Reset the connection
1669
+ if self.reset_session:
1670
+ cnx.reset_session()
1671
+ try:
1672
+ self.put(cnx, block=False)
1673
+ except queue.Full as err:
1674
+ raise PoolError("Failed adding connection; queue is full") from err
1675
+
1676
+ def track_connection(self, connection: PooledConnection) -> None:
1677
+ """Tracks connection in order of close it when client.close() is invoke."""
1678
+ self._connections_openned.append(connection)
1679
+
1680
+ def __str__(self) -> str:
1681
+ return self.name
1682
+
1683
+ def available(self) -> bool:
1684
+ """Returns if this pool is available for pool connections from it.
1685
+
1686
+ Returns:
1687
+ bool: True if this pool is available else False.
1688
+ .. versionadded:: 8.0.20
1689
+ """
1690
+ return self._available
1691
+
1692
+ def set_unavailable(self, time_out: int = -1) -> None:
1693
+ """Sets this pool unavailable for a period of time (in seconds).
1694
+
1695
+ .. versionadded:: 8.0.20
1696
+ """
1697
+ if self._available:
1698
+ logger.warning(
1699
+ "ConnectionPool.set_unavailable pool: %s time_out: %s",
1700
+ self,
1701
+ time_out,
1702
+ )
1703
+ self._available = False
1704
+ self._timeout_stamp = datetime.now()
1705
+ self._timeout = time_out
1706
+
1707
+ def set_available(self) -> None:
1708
+ """Sets this pool available for pool connections from it.
1709
+
1710
+ .. versionadded:: 8.0.20
1711
+ """
1712
+ self._available = True
1713
+ self._timeout_stamp = datetime.now()
1714
+
1715
+ def get_timeout_stamp(self) -> Tuple[int, datetime]:
1716
+ """Returns the penalized time (timeout) and the time at the penalty.
1717
+
1718
+ Returns:
1719
+ tuple: penalty seconds (int), timestamp at penalty (datetime object)
1720
+ .. versionadded:: 8.0.20
1721
+ """
1722
+ return (self._timeout, self._timeout_stamp)
1723
+
1724
+ def close(self) -> None:
1725
+ """Empty this ConnectionPool."""
1726
+ for cnx in self._connections_openned:
1727
+ cnx.close_connection()
1728
+
1729
+
1730
+ class PoolsManager:
1731
+ """Manages a pool of connections for a host or hosts in routers.
1732
+
1733
+ This class handles all the pools of Connections.
1734
+
1735
+ .. versionadded:: 8.0.13
1736
+ """
1737
+
1738
+ __instance: PoolsManager = None
1739
+ __pools: Dict[str, Any] = {}
1740
+
1741
+ def __new__(cls) -> PoolsManager:
1742
+ if PoolsManager.__instance is None:
1743
+ PoolsManager.__instance = object.__new__(cls)
1744
+ PoolsManager.__pools = {}
1745
+ return PoolsManager.__instance
1746
+
1747
+ def _pool_exists(self, client_id: str, pool_name: str) -> bool:
1748
+ """Verifies if a pool exists with the given name.
1749
+
1750
+ Args:
1751
+ client_id (str): The client id.
1752
+ pool_name (str): The name of the pool.
1753
+
1754
+ Returns:
1755
+ bool: Returns `True` if the pool exists otherwise `False`.
1756
+ """
1757
+ pools = self.__pools.get(client_id, [])
1758
+ for pool in pools:
1759
+ if pool.name == pool_name:
1760
+ return True
1761
+ return False
1762
+
1763
+ def _get_pools(self, settings: Dict[str, Any]) -> List:
1764
+ """Retrieves a list of pools that shares the given settings.
1765
+
1766
+ Args:
1767
+ settings (dict): the configuration of the pool.
1768
+
1769
+ Returns:
1770
+ list: A list of pools that shares the given settings.
1771
+ """
1772
+ available_pools = []
1773
+ pool_names = []
1774
+ connections_settings = self._get_connections_settings(settings)
1775
+
1776
+ # Generate the names of the pools this settings can connect to
1777
+ for router_name, _ in connections_settings:
1778
+ pool_names.append(router_name)
1779
+
1780
+ # Generate the names of the pools this settings can connect to
1781
+ for pool in self.__pools.get(settings.get("client_id", "No id"), []):
1782
+ if pool.name in pool_names:
1783
+ available_pools.append(pool)
1784
+ return available_pools
1785
+
1786
+ @staticmethod
1787
+ def _get_connections_settings(
1788
+ settings: Dict[str, Any]
1789
+ ) -> List[Tuple[str, Dict[str, Any]]]:
1790
+ """Generates a list of separated connection settings for each host.
1791
+
1792
+ Gets a list of connection settings for each host or router found in the
1793
+ given settings.
1794
+
1795
+ Args:
1796
+ settings (dict): The configuration for the connections.
1797
+
1798
+ Returns:
1799
+ list: A list of connections settings
1800
+ """
1801
+ pool_settings = settings.copy()
1802
+ routers = pool_settings.get("routers", [])
1803
+ connections_settings = []
1804
+ if "routers" in pool_settings:
1805
+ pool_settings.pop("routers")
1806
+ if "host" in pool_settings and "port" in pool_settings:
1807
+ routers.append(
1808
+ {
1809
+ "priority": 100,
1810
+ "weight": 0,
1811
+ "host": pool_settings["host"],
1812
+ "port": pool_settings["port"],
1813
+ }
1814
+ )
1815
+ # Order routers
1816
+ routers.sort(key=lambda x: (x["priority"], -x.get("weight", 0)))
1817
+ for router in routers:
1818
+ connection_settings = pool_settings.copy()
1819
+ connection_settings["host"] = router["host"]
1820
+ connection_settings["port"] = router["port"]
1821
+ connection_settings["priority"] = router["priority"]
1822
+ connection_settings["weight"] = router.get("weight", 0)
1823
+ connections_settings.append(
1824
+ (
1825
+ generate_pool_name(**connection_settings),
1826
+ connection_settings,
1827
+ )
1828
+ )
1829
+ return connections_settings
1830
+
1831
+ def create_pool(self, cnx_settings: Dict[str, Any]) -> None:
1832
+ """Creates a `ConnectionPool` instance to hold the connections.
1833
+
1834
+ Creates a `ConnectionPool` instance to hold the connections only if
1835
+ no other pool exists with the same configuration.
1836
+
1837
+ Args:
1838
+ cnx_settings (dict): The configuration for the connections.
1839
+ """
1840
+ connections_settings = self._get_connections_settings(cnx_settings)
1841
+
1842
+ # Subscribe client if it does not exists
1843
+ if cnx_settings.get("client_id", "No id") not in self.__pools:
1844
+ self.__pools[cnx_settings.get("client_id", "No id")] = []
1845
+
1846
+ # Create a pool for each router
1847
+ for router_name, settings in connections_settings:
1848
+ if self._pool_exists(cnx_settings.get("client_id", "No id"), router_name):
1849
+ continue
1850
+ pool = self.__pools.get(cnx_settings.get("client_id", "No id"), [])
1851
+ pool.append(ConnectionPool(router_name, **settings))
1852
+
1853
+ @staticmethod
1854
+ def _get_random_pool(pool_list: List[ConnectionPool]) -> ConnectionPool:
1855
+ """Get a random router from the group with the given priority.
1856
+
1857
+ Returns:
1858
+ Router: a random router.
1859
+
1860
+ .. versionadded:: 8.0.20
1861
+ """
1862
+ if not pool_list:
1863
+ return None
1864
+ if len(pool_list) == 1:
1865
+ return pool_list[0]
1866
+
1867
+ last = len(pool_list) - 1
1868
+ index = random.randint(0, last)
1869
+ return pool_list[index]
1870
+
1871
+ @staticmethod
1872
+ def _get_sublist(
1873
+ pools: List[ConnectionPool], index: int, cur_priority: int
1874
+ ) -> List[ConnectionPool]:
1875
+ sublist = []
1876
+ next_priority = None
1877
+ while index < len(pools):
1878
+ next_priority = pools[index].priority
1879
+ if cur_priority == next_priority and pools[index].available():
1880
+ sublist.append(pools[index])
1881
+ elif cur_priority != next_priority:
1882
+ break
1883
+ index += 1
1884
+ return sublist
1885
+
1886
+ def _get_next_pool(
1887
+ self, pools: List[ConnectionPool], cur_priority: int
1888
+ ) -> ConnectionPool:
1889
+ index = 0
1890
+ for pool in pools:
1891
+ if pool.available() and cur_priority == pool.priority:
1892
+ break
1893
+ index += 1
1894
+ subpool: List = []
1895
+ while not subpool and index < len(pools):
1896
+ subpool = self._get_sublist(pools, index, cur_priority)
1897
+ index += 1
1898
+ return self._get_random_pool(subpool)
1899
+
1900
+ @staticmethod
1901
+ def _get_next_priority(
1902
+ pools: List[ConnectionPool], cur_priority: Optional[int] = None
1903
+ ) -> int:
1904
+ if cur_priority is None and pools:
1905
+ return pools[0].priority
1906
+ # find the first pool that does not share the same priority
1907
+ for t_pool in pools:
1908
+ if t_pool.available():
1909
+ cur_priority = t_pool.priority
1910
+ return cur_priority
1911
+ return pools[0].priority
1912
+
1913
+ def _check_unavailable_pools(
1914
+ self, settings: Dict[str, Any], revive: Optional[bool] = None
1915
+ ) -> None:
1916
+ pools = self._get_pools(settings)
1917
+ for pool in pools:
1918
+ if pool.available():
1919
+ continue
1920
+ timeout, timeout_stamp = pool.get_timeout_stamp()
1921
+ if revive:
1922
+ timeout = revive
1923
+ if datetime.now() > (timeout_stamp + timedelta(seconds=timeout)):
1924
+ pool.set_available()
1925
+
1926
+ def get_connection(self, settings: Dict[str, Any]) -> PooledConnection:
1927
+ """Get a connection from the pool.
1928
+
1929
+ This method returns an `PooledConnection` instance which has a reference
1930
+ to the pool that created it, and can be used as a normal Connection.
1931
+
1932
+ When the MySQL connection is not connected, a reconnect is attempted.
1933
+
1934
+ Raises:
1935
+ :class:`PoolError`: On errors.
1936
+
1937
+ Returns:
1938
+ PooledConnection: A pooled connection object.
1939
+ """
1940
+
1941
+ def set_mysqlx_wait_timeout(cnx: PooledConnection) -> None:
1942
+ ver = cnx.sql(_SELECT_VERSION_QUERY).execute().fetch_all()[0][0]
1943
+ # mysqlx_wait_timeout is only available on MySQL 8
1944
+ if tuple(int(n) for n in ver.split("-")[0].split(".")) > (
1945
+ 8,
1946
+ 0,
1947
+ 10,
1948
+ ):
1949
+ cnx.sql(f"set mysqlx_wait_timeout = {pool.max_idle_time}").execute()
1950
+
1951
+ pools = self._get_pools(settings)
1952
+ cur_priority = settings.get("cur_priority", None)
1953
+ error_list = []
1954
+ self._check_unavailable_pools(settings)
1955
+ cur_priority = self._get_next_priority(pools, cur_priority)
1956
+ if cur_priority is None:
1957
+ raise PoolError(
1958
+ "Unable to connect to any of the target hosts. No pool is available"
1959
+ )
1960
+ settings["cur_priority"] = cur_priority
1961
+ pool = self._get_next_pool(pools, cur_priority)
1962
+ lock = threading.RLock()
1963
+ while pool is not None:
1964
+ try:
1965
+ # Check connections aviability in this pool
1966
+ if pool.qsize() > 0:
1967
+ # We have connections in pool, try to return a working one
1968
+ with lock:
1969
+ try:
1970
+ cnx = pool.get(block=True, timeout=pool.queue_timeout)
1971
+ except queue.Empty:
1972
+ raise PoolError(
1973
+ "Failed getting connection; pool exhausted"
1974
+ ) from None
1975
+ try:
1976
+ if cnx.is_server_disconnected():
1977
+ pool.remove_connections()
1978
+ # Only reset the connection by re-authentification
1979
+ # if the connection was unable to keep open by the
1980
+ # server
1981
+ if not cnx.keep_open:
1982
+ cnx.reset()
1983
+ set_mysqlx_wait_timeout(cnx)
1984
+ except (RuntimeError, OSError, InterfaceError):
1985
+ # Unable to reset connection, close and remove
1986
+ try:
1987
+ cnx.close_connection()
1988
+ except (RuntimeError, OSError, InterfaceError):
1989
+ pass
1990
+ finally:
1991
+ pool.remove_connection(cnx)
1992
+ # By WL#13222 all idle sessions that connect to the
1993
+ # same endpoint should be removed from the pool.
1994
+ while pool.qsize() > 0:
1995
+ try:
1996
+ cnx = pool.get(
1997
+ block=True, timeout=pool.queue_timeout
1998
+ )
1999
+ except queue.Empty:
2000
+ pass
2001
+ else:
2002
+ try:
2003
+ cnx.close_connection()
2004
+ except (RuntimeError, OSError, InterfaceError):
2005
+ pass
2006
+ finally:
2007
+ pool.remove_connection(cnx)
2008
+ # Connection was closed by the server, create new
2009
+ try:
2010
+ cnx = PooledConnection(pool)
2011
+ pool.track_connection(cnx)
2012
+ cnx.connect()
2013
+ set_mysqlx_wait_timeout(cnx)
2014
+ except (RuntimeError, OSError, InterfaceError):
2015
+ pass
2016
+ finally:
2017
+ # Server must be down, take down idle
2018
+ # connections from this pool
2019
+ while pool.qsize() > 0:
2020
+ try:
2021
+ cnx = pool.get(
2022
+ block=True,
2023
+ timeout=pool.queue_timeout,
2024
+ )
2025
+ cnx.close_connection()
2026
+ pool.remove_connection(cnx)
2027
+ except (RuntimeError, OSError, InterfaceError):
2028
+ pass
2029
+ return cnx
2030
+ elif pool.open_connections < pool.pool_max_size:
2031
+ # No connections in pool, but we can open a new one
2032
+ cnx = PooledConnection(pool)
2033
+ pool.track_connection(cnx)
2034
+ cnx.connect()
2035
+ set_mysqlx_wait_timeout(cnx)
2036
+ return cnx
2037
+ else:
2038
+ # Pool is exaust so the client needs to wait
2039
+ with lock:
2040
+ try:
2041
+ cnx = pool.get(block=True, timeout=pool.queue_timeout)
2042
+ cnx.reset()
2043
+ set_mysqlx_wait_timeout(cnx)
2044
+ return cnx
2045
+ except queue.Empty:
2046
+ raise PoolError("pool max size has been reached") from None
2047
+ except (InterfaceError, TimeoutError, PoolError) as err:
2048
+ error_list.append(f"pool: {pool} error: {err}")
2049
+ if isinstance(err, PoolError):
2050
+ # Pool can be exhaust now but can be ready again in no time,
2051
+ # e.g a connection is returned to the pool.
2052
+ pool.set_unavailable(2)
2053
+ else:
2054
+ self.set_pool_unavailable(pool, err)
2055
+
2056
+ self._check_unavailable_pools(settings)
2057
+ # Try next pool with the same priority
2058
+ pool = self._get_next_pool(pools, cur_priority)
2059
+
2060
+ if pool is None:
2061
+ cur_priority = self._get_next_priority(pools, cur_priority)
2062
+ settings["cur_priority"] = cur_priority
2063
+ pool = self._get_next_pool(pools, cur_priority)
2064
+ if pool is None:
2065
+ msg = "\n ".join(error_list)
2066
+ raise PoolError(
2067
+ "Unable to connect to any of the target hosts: "
2068
+ f"[\n {msg}\n]"
2069
+ ) from err
2070
+ continue
2071
+
2072
+ raise PoolError("Unable to connect to any of the target hosts")
2073
+
2074
+ def close_pool(self, cnx_settings: Dict[str, Any]) -> int:
2075
+ """Closes the connections in the pools
2076
+
2077
+ Returns:
2078
+ int: The number of closed pools
2079
+ """
2080
+ pools = self._get_pools(cnx_settings)
2081
+ for pool in pools:
2082
+ pool.close()
2083
+ # Remove the pool
2084
+ if cnx_settings.get("client_id", None) is not None:
2085
+ client_pools = self.__pools.get(cnx_settings.get("client_id"))
2086
+ if pool in client_pools:
2087
+ client_pools.remove(pool)
2088
+ return len(pools)
2089
+
2090
+ @staticmethod
2091
+ def set_pool_unavailable(
2092
+ pool: ConnectionPool, err: Union[InterfaceError, TimeoutError]
2093
+ ) -> None:
2094
+ """Sets a pool as unavailable.
2095
+
2096
+ The time a pool is set unavailable depends on the given error message
2097
+ or the error number.
2098
+
2099
+ Args:
2100
+ pool (ConnectionPool): The pool to set unavailable.
2101
+ err (Exception): The raised exception raised by a connection belonging
2102
+ to the pool.
2103
+ """
2104
+ penalty = None
2105
+ try:
2106
+ err_no = err.errno
2107
+ penalty = _TIMEOUT_PENALTIES_BY_ERR_NO[err_no]
2108
+ except (AttributeError, KeyError):
2109
+ pass
2110
+ if not penalty:
2111
+ err_msg = err.msg
2112
+ for key, value in _TIMEOUT_PENALTIES.items():
2113
+ if key in err_msg:
2114
+ penalty = value
2115
+ if penalty:
2116
+ pool.set_unavailable(penalty)
2117
+ else:
2118
+ # Other errors are severe punished
2119
+ pool.set_unavailable(100000)
2120
+
2121
+
2122
+ class Session:
2123
+ """Enables interaction with a X Protocol enabled MySQL Product.
2124
+
2125
+ The functionality includes:
2126
+
2127
+ - Accessing available schemas.
2128
+ - Schema management operations.
2129
+ - Retrieval of connection information.
2130
+
2131
+ Args:
2132
+ settings (dict): Connection data used to connect to the database.
2133
+ """
2134
+
2135
+ def __init__(self, settings: Dict[str, Any]) -> None:
2136
+ self.use_pure: bool = settings.get("use-pure", Protobuf.use_pure)
2137
+ self._settings: Dict[str, Any] = settings
2138
+
2139
+ # Check for DNS SRV
2140
+ if settings.get("host") and settings.get("dns-srv"):
2141
+ if not HAVE_DNSPYTHON:
2142
+ raise InterfaceError(
2143
+ "MySQL host configuration requested DNS "
2144
+ "SRV. This requires the Python dnspython "
2145
+ "module. Please refer to documentation"
2146
+ )
2147
+ try:
2148
+ srv_records = dns.resolver.query(settings["host"], "SRV")
2149
+ except dns.exception.DNSException as err:
2150
+ raise InterfaceError(
2151
+ f"Unable to locate any hosts for '{settings['host']}'"
2152
+ ) from err
2153
+ self._settings["routers"] = []
2154
+ for srv in srv_records:
2155
+ self._settings["routers"].append(
2156
+ {
2157
+ "host": srv.target.to_text(omit_final_dot=True),
2158
+ "port": srv.port,
2159
+ "priority": srv.priority,
2160
+ "weight": srv.weight,
2161
+ }
2162
+ )
2163
+
2164
+ if (
2165
+ "connection-attributes" not in self._settings
2166
+ or self._settings["connection-attributes"] is not False
2167
+ ):
2168
+ self._settings["attributes"] = {}
2169
+ self._init_attributes()
2170
+
2171
+ if "pooling" in settings and settings["pooling"]:
2172
+ # Create pool and retrieve a Connection instance
2173
+ PoolsManager().create_pool(settings)
2174
+ self._connection: Connection = PoolsManager().get_connection(settings)
2175
+ if self._connection is None:
2176
+ raise PoolError("Connection could not be retrieved from pool")
2177
+ else:
2178
+ self._connection = Connection(self._settings)
2179
+ self._connection.connect()
2180
+ # Set default schema
2181
+ schema = self._settings.get("schema")
2182
+ if schema:
2183
+ try:
2184
+ self.sql(f"USE {quote_identifier(schema)}").execute()
2185
+ except OperationalError as err:
2186
+ # Access denied for user will raise err.errno = 1044
2187
+ errmsg = (
2188
+ err.msg
2189
+ if err.errno == 1044
2190
+ else f"Default schema '{schema}' does not exists"
2191
+ )
2192
+ raise InterfaceError(errmsg, err.errno) from err
2193
+
2194
+ def __enter__(self) -> Session:
2195
+ return self
2196
+
2197
+ def __exit__(
2198
+ self,
2199
+ exc_type: Type[BaseException],
2200
+ exc_value: BaseException,
2201
+ traceback: TracebackType,
2202
+ ) -> None:
2203
+ self.close()
2204
+
2205
+ def _init_attributes(self) -> None:
2206
+ """Setup default and user defined connection-attributes."""
2207
+ if os.name == "nt":
2208
+ if "64" in platform.architecture()[0]:
2209
+ platform_arch: Union[str, Tuple[str, str]] = "x86_64"
2210
+ elif "32" in platform.architecture()[0]:
2211
+ platform_arch = "i386"
2212
+ else:
2213
+ platform_arch = platform.architecture()
2214
+ os_ver = f"Windows-{platform.win32_ver()[1]}"
2215
+ else:
2216
+ platform_arch = platform.machine()
2217
+ if platform.system() == "Darwin":
2218
+ os_ver = f"macOS-{platform.mac_ver()[0]}"
2219
+ else:
2220
+ os_ver = "-".join(linux_distribution()[0:2])
2221
+
2222
+ license_chunks = LICENSE.split(" ")
2223
+ if license_chunks[0] == "GPLv2":
2224
+ client_license = "GPL-2.0"
2225
+ else:
2226
+ client_license = "Commercial"
2227
+
2228
+ default_attributes = {
2229
+ # Process id
2230
+ "_pid": str(os.getpid()),
2231
+ # Platform architecture
2232
+ "_platform": platform_arch,
2233
+ # OS version
2234
+ "_os": os_ver,
2235
+ # Hostname of the local machine
2236
+ "_source_host": socket.gethostname(),
2237
+ # Client's name
2238
+ "_client_name": "mysql-connector-python",
2239
+ # Client's version
2240
+ "_client_version": ".".join([str(x) for x in VERSION[0:3]]),
2241
+ # Client's License identifier
2242
+ "_client_license": client_license,
2243
+ }
2244
+ self._settings["attributes"].update(default_attributes)
2245
+
2246
+ if "connection-attributes" in self._settings:
2247
+ for attr_name in self._settings["connection-attributes"]:
2248
+ attr_value = self._settings["connection-attributes"][attr_name]
2249
+ # Validate name type
2250
+ if not isinstance(attr_name, str):
2251
+ raise InterfaceError(
2252
+ f"Attribute name '{attr_name}' must be a string type"
2253
+ )
2254
+ # Validate attribute name limit 32 characters
2255
+ if len(attr_name) > 32:
2256
+ raise InterfaceError(
2257
+ f"Attribute name '{attr_name}' exceeds 32 characters "
2258
+ "limit size"
2259
+ )
2260
+ # Validate names in connection-attributes cannot start with "_"
2261
+ if attr_name.startswith("_"):
2262
+ raise InterfaceError(
2263
+ "Key names in 'session-connect-attributes' cannot "
2264
+ f"start with '_', found: {attr_name}"
2265
+ )
2266
+ # Validate value type
2267
+ if not isinstance(attr_value, str):
2268
+ raise InterfaceError(
2269
+ f"Attribute name '{attr_name}' value '{attr_value}' "
2270
+ " must be a string type"
2271
+ )
2272
+
2273
+ # Validate attribute value limit 1024 characters
2274
+ if len(attr_value) > 1024:
2275
+ raise InterfaceError(
2276
+ f"Attribute name '{attr_name}' value: '{attr_value}' "
2277
+ "exceeds 1024 characters limit size"
2278
+ )
2279
+
2280
+ self._settings["attributes"][attr_name] = attr_value
2281
+
2282
+ @property
2283
+ def use_pure(self) -> bool:
2284
+ """bool: `True` to use pure Python Protobuf implementation."""
2285
+ return Protobuf.use_pure
2286
+
2287
+ @use_pure.setter
2288
+ def use_pure(self, value: bool) -> None:
2289
+ if not isinstance(value, bool):
2290
+ raise ProgrammingError("'use_pure' option should be True or False")
2291
+ Protobuf.set_use_pure(value)
2292
+
2293
+ def is_open(self) -> bool:
2294
+ """Returns `True` if the session is open.
2295
+
2296
+ Returns:
2297
+ bool: Returns `True` if the session is open.
2298
+ """
2299
+ return self._connection.stream.is_open()
2300
+
2301
+ def sql(self, sql: str) -> SqlStatement:
2302
+ """Creates a :class:`mysqlx.SqlStatement` object to allow running the
2303
+ SQL statement on the target MySQL Server.
2304
+
2305
+ Args:
2306
+ sql (string): The SQL statement to be executed.
2307
+
2308
+ Returns:
2309
+ mysqlx.SqlStatement: SqlStatement object.
2310
+ """
2311
+ return SqlStatement(self._connection, sql)
2312
+
2313
+ def get_connection(self) -> Connection:
2314
+ """Returns the underlying connection.
2315
+
2316
+ Returns:
2317
+ mysqlx.connection.Connection: The connection object.
2318
+ """
2319
+ return self._connection
2320
+
2321
+ def get_schemas(self) -> List[str]:
2322
+ """Returns the list of schemas in the current session.
2323
+
2324
+ Returns:
2325
+ `list`: The list of schemas in the current session.
2326
+
2327
+ .. versionadded:: 8.0.12
2328
+ """
2329
+ result = self.sql("SHOW DATABASES").execute()
2330
+ return [row[0] for row in result.fetch_all()]
2331
+
2332
+ def get_schema(self, name: str) -> Schema:
2333
+ """Retrieves a Schema object from the current session by it's name.
2334
+
2335
+ Args:
2336
+ name (string): The name of the Schema object to be retrieved.
2337
+
2338
+ Returns:
2339
+ mysqlx.Schema: The Schema object with the given name.
2340
+ """
2341
+ return Schema(self, name)
2342
+
2343
+ def get_default_schema(self) -> Optional[Schema]:
2344
+ """Retrieves a Schema object from the current session by the schema
2345
+ name configured in the connection settings.
2346
+
2347
+ Returns:
2348
+ mysqlx.Schema: The Schema object with the given name at connect
2349
+ time.
2350
+ None: In case the default schema was not provided with the
2351
+ initialization data.
2352
+
2353
+ Raises:
2354
+ :class:`mysqlx.ProgrammingError`: If the provided default schema
2355
+ does not exists.
2356
+ """
2357
+ schema = self._connection.settings.get("schema")
2358
+ if schema:
2359
+ res = (
2360
+ self.sql(_SELECT_SCHEMA_NAME_QUERY.format(escape(schema)))
2361
+ .execute()
2362
+ .fetch_all()
2363
+ )
2364
+ try:
2365
+ if res[0][0] == schema: # type: ignore[index]
2366
+ return Schema(self, schema)
2367
+ except IndexError:
2368
+ raise ProgrammingError(
2369
+ f"Default schema '{schema}' does not exists"
2370
+ ) from None
2371
+ return None
2372
+
2373
+ def drop_schema(self, name: str) -> None:
2374
+ """Drops the schema with the specified name.
2375
+
2376
+ Args:
2377
+ name (string): The name of the Schema object to be retrieved.
2378
+ """
2379
+ self._connection.execute_nonquery(
2380
+ "sql", _DROP_DATABASE_QUERY.format(quote_identifier(name)), True
2381
+ )
2382
+
2383
+ def create_schema(self, name: str) -> Schema:
2384
+ """Creates a schema on the database and returns the corresponding
2385
+ object.
2386
+
2387
+ Args:
2388
+ name (string): A string value indicating the schema name.
2389
+ """
2390
+ self._connection.execute_nonquery(
2391
+ "sql", _CREATE_DATABASE_QUERY.format(quote_identifier(name)), True
2392
+ )
2393
+ return Schema(self, name)
2394
+
2395
+ def start_transaction(self) -> None:
2396
+ """Starts a transaction context on the server."""
2397
+ self._connection.execute_nonquery("sql", "START TRANSACTION", True)
2398
+
2399
+ def commit(self) -> None:
2400
+ """Commits all the operations executed after a call to
2401
+ startTransaction().
2402
+ """
2403
+ self._connection.execute_nonquery("sql", "COMMIT", True)
2404
+
2405
+ def rollback(self) -> None:
2406
+ """Discards all the operations executed after a call to
2407
+ startTransaction().
2408
+ """
2409
+ self._connection.execute_nonquery("sql", "ROLLBACK", True)
2410
+
2411
+ def set_savepoint(self, name: Optional[str] = None) -> str:
2412
+ """Creates a transaction savepoint.
2413
+
2414
+ If a name is not provided, one will be generated using the uuid.uuid1()
2415
+ function.
2416
+
2417
+ Args:
2418
+ name (Optional[string]): The savepoint name.
2419
+
2420
+ Returns:
2421
+ string: The savepoint name.
2422
+ """
2423
+ if name is None:
2424
+ name = f"{uuid.uuid1()}"
2425
+ elif not isinstance(name, str) or len(name.strip()) == 0:
2426
+ raise ProgrammingError("Invalid SAVEPOINT name")
2427
+ self._connection.execute_nonquery(
2428
+ "sql", f"SAVEPOINT {quote_identifier(name)}", True
2429
+ )
2430
+ return name
2431
+
2432
+ def rollback_to(self, name: str) -> None:
2433
+ """Rollback to a transaction savepoint with the given name.
2434
+
2435
+ Args:
2436
+ name (string): The savepoint name.
2437
+ """
2438
+ if not isinstance(name, str) or len(name.strip()) == 0:
2439
+ raise ProgrammingError("Invalid SAVEPOINT name")
2440
+ self._connection.execute_nonquery(
2441
+ "sql",
2442
+ f"ROLLBACK TO SAVEPOINT {quote_identifier(name)}",
2443
+ True,
2444
+ )
2445
+
2446
+ def release_savepoint(self, name: str) -> None:
2447
+ """Release a transaction savepoint with the given name.
2448
+
2449
+ Args:
2450
+ name (string): The savepoint name.
2451
+ """
2452
+ if not isinstance(name, str) or len(name.strip()) == 0:
2453
+ raise ProgrammingError("Invalid SAVEPOINT name")
2454
+ self._connection.execute_nonquery(
2455
+ "sql",
2456
+ f"RELEASE SAVEPOINT {quote_identifier(name)}",
2457
+ True,
2458
+ )
2459
+
2460
+ def close(self) -> None:
2461
+ """Closes the session."""
2462
+ self._connection.close_session()
2463
+ # Set an unconnected connection
2464
+ self._connection = Connection(self._settings)
2465
+
2466
+ def close_connections(self) -> None:
2467
+ """Closes all underliying connections as pooled connections"""
2468
+ self._connection.close_connection()
2469
+
2470
+
2471
+ class Client:
2472
+ """Class defining a client, it stores a connection configuration.
2473
+
2474
+ Args:
2475
+ connection_dict (dict): The connection information to connect to a
2476
+ MySQL server.
2477
+ options_dict (dict): The options to configure this client.
2478
+
2479
+ .. versionadded:: 8.0.13
2480
+ """
2481
+
2482
+ def __init__(
2483
+ self,
2484
+ connection_dict: Dict[str, Any],
2485
+ options_dict: Optional[Dict[str, Any]] = None,
2486
+ ) -> None:
2487
+ self.settings: Dict[str, Any] = connection_dict
2488
+ if options_dict is None:
2489
+ options_dict = {}
2490
+
2491
+ self.sessions: List[Session] = []
2492
+ self.client_id: uuid.UUID = uuid.uuid4()
2493
+
2494
+ self._set_pool_size(options_dict.get("max_size", 25))
2495
+ self._set_max_idle_time(options_dict.get("max_idle_time", 0))
2496
+ self._set_queue_timeout(options_dict.get("queue_timeout", 0))
2497
+ self._set_pool_enabled(options_dict.get("enabled", True))
2498
+
2499
+ self.settings["pooling"] = self.pooling_enabled
2500
+ self.settings["max_size"] = self.max_size
2501
+ self.settings["client_id"] = self.client_id
2502
+
2503
+ def __enter__(self) -> Client:
2504
+ return self
2505
+
2506
+ def __exit__(
2507
+ self,
2508
+ exc_type: Type[BaseException],
2509
+ exc_value: BaseException,
2510
+ traceback: TracebackType,
2511
+ ) -> None:
2512
+ self.close()
2513
+
2514
+ def _set_pool_size(self, pool_size: int) -> None:
2515
+ """Set the size of the pool.
2516
+
2517
+ This method sets the size of the pool but it will not resize the pool.
2518
+
2519
+ Args:
2520
+ pool_size (int): An integer equal or greater than 0 indicating
2521
+ the pool size.
2522
+
2523
+ Raises:
2524
+ :class:`AttributeError`: If the pool_size value is not an integer
2525
+ greater or equal to 0.
2526
+ """
2527
+ if (
2528
+ isinstance(pool_size, bool)
2529
+ or not isinstance(pool_size, int)
2530
+ or not pool_size > 0
2531
+ ):
2532
+ raise AttributeError(
2533
+ "Pool max_size value must be an integer greater than 0, the "
2534
+ f"given value {pool_size} is not valid"
2535
+ )
2536
+
2537
+ self.max_size = _CNX_POOL_MAXSIZE if pool_size == 0 else pool_size
2538
+
2539
+ def _set_max_idle_time(self, max_idle_time: int) -> None:
2540
+ """Set the max idle time.
2541
+
2542
+ This method sets the max idle time.
2543
+
2544
+ Args:
2545
+ max_idle_time (int): An integer equal or greater than 0 indicating
2546
+ the max idle time.
2547
+
2548
+ Raises:
2549
+ :class:`AttributeError`: If the max_idle_time value is not an
2550
+ integer greater or equal to 0.
2551
+ """
2552
+ if (
2553
+ isinstance(max_idle_time, bool)
2554
+ or not isinstance(max_idle_time, int)
2555
+ or not max_idle_time > -1
2556
+ ):
2557
+ raise AttributeError(
2558
+ "Connection max_idle_time value must be an integer greater or "
2559
+ f"equal to 0, the given value {max_idle_time} is not valid"
2560
+ )
2561
+
2562
+ self.max_idle_time = max_idle_time
2563
+ self.settings["max_idle_time"] = (
2564
+ _CNX_POOL_MAX_IDLE_TIME if max_idle_time == 0 else int(max_idle_time / 1000)
2565
+ )
2566
+
2567
+ def _set_pool_enabled(self, enabled: bool) -> None:
2568
+ """Set if the pool is enabled.
2569
+
2570
+ This method sets if the pool is enabled.
2571
+
2572
+ Args:
2573
+ enabled (bool): True if to enabling the pool.
2574
+
2575
+ Raises:
2576
+ :class:`AttributeError`: If the value of enabled is not a bool type.
2577
+ """
2578
+ if not isinstance(enabled, bool):
2579
+ raise AttributeError("The enabled value should be True or False.")
2580
+ self.pooling_enabled = enabled
2581
+
2582
+ def _set_queue_timeout(self, queue_timeout: int) -> None:
2583
+ """Set the queue timeout.
2584
+
2585
+ This method sets the queue timeout.
2586
+
2587
+ Args:
2588
+ queue_timeout (int): An integer equal or greater than 0 indicating
2589
+ the queue timeout.
2590
+
2591
+ Raises:
2592
+ :class:`AttributeError`: If the queue_timeout value is not an
2593
+ integer greater or equal to 0.
2594
+ """
2595
+ if (
2596
+ isinstance(queue_timeout, bool)
2597
+ or not isinstance(queue_timeout, int)
2598
+ or not queue_timeout > -1
2599
+ ):
2600
+ raise AttributeError(
2601
+ "Connection queue_timeout value must be an integer greater or "
2602
+ f"equal to 0, the given value {queue_timeout} is not valid"
2603
+ )
2604
+
2605
+ self.queue_timeout = queue_timeout
2606
+ self.settings["queue_timeout"] = (
2607
+ _CNX_POOL_QUEUE_TIMEOUT if queue_timeout == 0 else int(queue_timeout / 1000)
2608
+ )
2609
+ # To avoid a connection stall waiting for the server, if the
2610
+ # connect-timeout is not given, use the queue_timeout
2611
+ if "connect-timeout" not in self.settings:
2612
+ self.settings["connect-timeout"] = self.queue_timeout
2613
+
2614
+ def get_session(self) -> Session:
2615
+ """Creates a Session instance using the provided connection data.
2616
+
2617
+ Returns:
2618
+ Session: Session object.
2619
+ """
2620
+ session = Session(self.settings)
2621
+ self.sessions.append(session)
2622
+ return session
2623
+
2624
+ def close(self) -> None:
2625
+ """Closes the sessions opened by this client."""
2626
+ PoolsManager().close_pool(self.settings)
2627
+ for session in self.sessions:
2628
+ session.close_connections()
2629
+
2630
+
2631
+ def _parse_address_list(path: str) -> Union[Dict[str, List[Dict]], Dict]:
2632
+ """Parses a list of host, port pairs.
2633
+
2634
+ Args:
2635
+ path: String containing a list of routers or just router
2636
+
2637
+ Returns:
2638
+ Returns a dict with parsed values of host, port and priority if
2639
+ specified.
2640
+ """
2641
+ path = path.replace(" ", "")
2642
+ array = (
2643
+ not ("," not in path and path.count(":") > 1 and path.count("[") == 1)
2644
+ and path.startswith("[")
2645
+ and path.endswith("]")
2646
+ )
2647
+
2648
+ routers = []
2649
+ address_list = _SPLIT_RE.split(path[1:-1] if array else path)
2650
+ priority_count = 0
2651
+ for address in address_list:
2652
+ router: Dict = {}
2653
+
2654
+ match = _PRIORITY_RE.match(address)
2655
+ if match:
2656
+ address = match.group(1)
2657
+ router["priority"] = int(match.group(2))
2658
+ priority_count += 1
2659
+ else:
2660
+ match = _ROUTER_RE.match(address)
2661
+ if match:
2662
+ address = match.group(1)
2663
+ router["priority"] = 100
2664
+
2665
+ match = urlparse(f"//{address}")
2666
+ if not match.hostname:
2667
+ raise InterfaceError(f"Invalid address: {address}")
2668
+
2669
+ try:
2670
+ router.update(host=match.hostname, port=match.port)
2671
+ except ValueError as err:
2672
+ raise ProgrammingError(f"Invalid URI: {err}", 4002) from err
2673
+
2674
+ routers.append(router)
2675
+
2676
+ if 0 < priority_count < len(address_list):
2677
+ raise ProgrammingError(
2678
+ "You must either assign no priority to any of the routers or give "
2679
+ "a priority for every router",
2680
+ 4000,
2681
+ )
2682
+
2683
+ return {"routers": routers} if array else routers[0]
2684
+
2685
+
2686
+ def _parse_connection_uri(uri: str) -> Dict[str, Any]:
2687
+ """Parses the connection string and returns a dictionary with the
2688
+ connection settings.
2689
+
2690
+ Args:
2691
+ uri: mysqlx URI scheme to connect to a MySQL server/farm.
2692
+
2693
+ Returns:
2694
+ Returns a dict with parsed values of credentials and address of the
2695
+ MySQL server/farm.
2696
+
2697
+ Raises:
2698
+ :class:`mysqlx.InterfaceError`: If contains a invalid option.
2699
+ """
2700
+ settings: Dict[str, Any] = {"schema": ""}
2701
+
2702
+ match = _URI_SCHEME_RE.match(uri)
2703
+ scheme, uri = match.groups() if match else ("mysqlx", uri)
2704
+
2705
+ if scheme not in ("mysqlx", "mysqlx+srv"):
2706
+ raise InterfaceError(f"Scheme '{scheme}' is not valid")
2707
+
2708
+ if scheme == "mysqlx+srv":
2709
+ settings["dns-srv"] = True
2710
+
2711
+ userinfo, tmp = uri.partition("@")[::2]
2712
+ host, query_str = tmp.partition("?")[::2]
2713
+
2714
+ pos = host.rfind("/")
2715
+ if host[pos:].find(")") == -1 and pos > 0:
2716
+ host, settings["schema"] = host.rsplit("/", 1)
2717
+ host = host.strip("()")
2718
+
2719
+ if not host or not userinfo or ":" not in userinfo:
2720
+ raise InterfaceError(f"Malformed URI '{uri}'")
2721
+ user, password = userinfo.split(":", 1)
2722
+ settings["user"], settings["password"] = unquote(user), unquote(password)
2723
+
2724
+ if host.startswith(("/", "..", ".")):
2725
+ settings["socket"] = unquote(host)
2726
+ elif host.startswith("\\."):
2727
+ raise InterfaceError("Windows Pipe is not supported")
2728
+ else:
2729
+ settings.update(_parse_address_list(host))
2730
+
2731
+ invalid_options = ("user", "password", "dns-srv")
2732
+ for key, val in parse_qsl(query_str, True):
2733
+ opt = key.replace("_", "-").lower()
2734
+ if opt in invalid_options:
2735
+ raise InterfaceError(f"Invalid option: '{key}'")
2736
+ if opt in _SSL_OPTS:
2737
+ settings[opt] = unquote(val.strip("()"))
2738
+ else:
2739
+ val_str = val.lower()
2740
+ if val_str in ("1", "true"):
2741
+ settings[opt] = True
2742
+ elif val_str in ("0", "false"):
2743
+ settings[opt] = False
2744
+ else:
2745
+ settings[opt] = val_str
2746
+ return settings
2747
+
2748
+
2749
+ def _validate_settings(settings: Dict[str, Any]) -> None:
2750
+ """Validates the settings to be passed to a Session object
2751
+ the port values are converted to int if specified or set to 33060
2752
+ otherwise. The priority values for each router is converted to int
2753
+ if specified.
2754
+
2755
+ Args:
2756
+ settings: dict containing connection settings.
2757
+
2758
+ Raises:
2759
+ :class:`mysqlx.InterfaceError`: On any configuration issue.
2760
+ """
2761
+ invalid_opts = set(settings.keys()).difference(_SESS_OPTS)
2762
+ if invalid_opts:
2763
+ invalid_opts_list = "', '".join(invalid_opts)
2764
+ raise InterfaceError(f"Invalid option(s): '{invalid_opts_list}'")
2765
+
2766
+ if "routers" in settings:
2767
+ for router in settings["routers"]:
2768
+ _validate_hosts(router, 33060)
2769
+ elif "host" in settings:
2770
+ _validate_hosts(settings)
2771
+
2772
+ if "ssl-mode" in settings:
2773
+ ssl_mode = settings["ssl-mode"]
2774
+ try:
2775
+ settings["ssl-mode"] = SSLMode(
2776
+ ssl_mode.lower().strip() if isinstance(ssl_mode, str) else ssl_mode
2777
+ )
2778
+ except (AttributeError, ValueError) as err:
2779
+ raise InterfaceError(f"Invalid SSL Mode '{settings['ssl-mode']}'") from err
2780
+ if "ssl-ca" not in settings and settings["ssl-mode"] in [
2781
+ SSLMode.VERIFY_IDENTITY,
2782
+ SSLMode.VERIFY_CA,
2783
+ ]:
2784
+ raise InterfaceError("Cannot verify Server without CA")
2785
+
2786
+ if "ssl-crl" in settings and "ssl-ca" not in settings:
2787
+ raise InterfaceError("CA Certificate not provided")
2788
+
2789
+ if "ssl-key" in settings and "ssl-cert" not in settings:
2790
+ raise InterfaceError("Client Certificate not provided")
2791
+
2792
+ if "ssl-ca" in settings and settings.get("ssl-mode") not in [
2793
+ SSLMode.VERIFY_IDENTITY,
2794
+ SSLMode.VERIFY_CA,
2795
+ SSLMode.DISABLED,
2796
+ ]:
2797
+ raise InterfaceError("Must verify Server if CA is provided")
2798
+
2799
+ if "auth" in settings:
2800
+ auth = settings["auth"]
2801
+ try:
2802
+ settings["auth"] = Auth(
2803
+ auth.lower().strip() if isinstance(auth, str) else auth
2804
+ )
2805
+ except (AttributeError, ValueError) as err:
2806
+ raise InterfaceError(f"Invalid Auth '{settings['auth']}'") from err
2807
+
2808
+ if "compression" in settings:
2809
+ compression = settings["compression"]
2810
+ try:
2811
+ settings["compression"] = Compression(
2812
+ compression.lower().strip()
2813
+ if isinstance(compression, str)
2814
+ else compression
2815
+ )
2816
+ except (AttributeError, ValueError) as err:
2817
+ raise InterfaceError(
2818
+ "The connection property 'compression' acceptable values are: "
2819
+ "'preferred', 'required', or 'disabled'. The value "
2820
+ f"'{settings['compression']}' is not acceptable"
2821
+ ) from err
2822
+
2823
+ if "compression-algorithms" in settings:
2824
+ if isinstance(settings["compression-algorithms"], str):
2825
+ compression_algorithms = (
2826
+ settings["compression-algorithms"].strip().strip("[]")
2827
+ )
2828
+ if compression_algorithms:
2829
+ settings["compression-algorithms"] = compression_algorithms.split(",")
2830
+ else:
2831
+ settings["compression-algorithms"] = None
2832
+ elif not isinstance(settings["compression-algorithms"], (list, tuple)):
2833
+ raise InterfaceError(
2834
+ "Invalid type of the connection property 'compression-algorithms'"
2835
+ )
2836
+ if settings.get("compression") == Compression.DISABLED:
2837
+ settings["compression-algorithms"] = None
2838
+
2839
+ if "connection-attributes" in settings:
2840
+ _validate_connection_attributes(settings)
2841
+
2842
+ if "connect-timeout" in settings:
2843
+ try:
2844
+ if isinstance(settings["connect-timeout"], str):
2845
+ settings["connect-timeout"] = int(settings["connect-timeout"])
2846
+ if (
2847
+ not isinstance(settings["connect-timeout"], int)
2848
+ or settings["connect-timeout"] < 0
2849
+ ):
2850
+ raise ValueError
2851
+ except ValueError:
2852
+ raise TypeError(
2853
+ "The connection timeout value must be a positive "
2854
+ "integer (including 0)"
2855
+ ) from None
2856
+
2857
+ if "dns-srv" in settings:
2858
+ if not isinstance(settings["dns-srv"], bool):
2859
+ raise InterfaceError("The value of 'dns-srv' must be a boolean")
2860
+ if settings.get("socket"):
2861
+ raise InterfaceError(
2862
+ "Using Unix domain sockets with DNS SRV lookup is not allowed"
2863
+ )
2864
+ if settings.get("port"):
2865
+ raise InterfaceError(
2866
+ "Specifying a port number with DNS SRV lookup is not allowed"
2867
+ )
2868
+ if settings.get("routers"):
2869
+ raise InterfaceError(
2870
+ "Specifying multiple hostnames with DNS SRV look up is not allowed"
2871
+ )
2872
+ elif "host" in settings and not settings.get("port"):
2873
+ settings["port"] = 33060
2874
+
2875
+ if "tls-versions" in settings:
2876
+ _validate_tls_versions(settings)
2877
+
2878
+ if "tls-ciphersuites" in settings:
2879
+ _validate_tls_ciphersuites(settings)
2880
+
2881
+
2882
+ def _validate_hosts(
2883
+ settings: Dict[str, Any], default_port: Optional[int] = None
2884
+ ) -> None:
2885
+ """Validate hosts.
2886
+
2887
+ Args:
2888
+ settings (dict): Settings dictionary.
2889
+ default_port (int): Default connection port.
2890
+
2891
+ Raises:
2892
+ :class:`mysqlx.InterfaceError`: If priority or port are invalid.
2893
+ """
2894
+ if "priority" in settings and settings["priority"]:
2895
+ try:
2896
+ settings["priority"] = int(settings["priority"])
2897
+ if settings["priority"] < 0 or settings["priority"] > 100:
2898
+ raise ProgrammingError(
2899
+ "Invalid priority value, must be between 0 and 100",
2900
+ 4007,
2901
+ )
2902
+ except NameError:
2903
+ raise ProgrammingError("Invalid priority", 4007) from None
2904
+ except ValueError:
2905
+ raise ProgrammingError(
2906
+ f"Invalid priority: {settings['priority']}", 4007
2907
+ ) from None
2908
+
2909
+ if "port" in settings and settings["port"]:
2910
+ try:
2911
+ settings["port"] = int(settings["port"])
2912
+ except NameError:
2913
+ raise InterfaceError("Invalid port") from None
2914
+ elif "host" in settings and default_port:
2915
+ settings["port"] = default_port
2916
+
2917
+
2918
+ def _validate_connection_attributes(settings: Dict[str, Any]) -> None:
2919
+ """Validate connection-attributes.
2920
+
2921
+ Args:
2922
+ settings (dict): Settings dictionary.
2923
+
2924
+ Raises:
2925
+ :class:`mysqlx.InterfaceError`: If attribute name or value exceeds size.
2926
+ """
2927
+ attributes = {}
2928
+ if "connection-attributes" not in settings:
2929
+ return
2930
+
2931
+ conn_attrs = settings["connection-attributes"]
2932
+
2933
+ if isinstance(conn_attrs, str):
2934
+ if conn_attrs == "":
2935
+ settings["connection-attributes"] = {}
2936
+ return
2937
+ if not (
2938
+ conn_attrs.startswith("[") and conn_attrs.endswith("]")
2939
+ ) and conn_attrs not in ["False", "false", "True", "true"]:
2940
+ raise InterfaceError(
2941
+ "The value of 'connection-attributes' must be a boolean or a "
2942
+ f"list of key-value pairs, found: '{conn_attrs}'"
2943
+ )
2944
+ if conn_attrs in ["False", "false", "True", "true"]:
2945
+ if conn_attrs in ["False", "false"]:
2946
+ settings["connection-attributes"] = False
2947
+ else:
2948
+ settings["connection-attributes"] = {}
2949
+ return
2950
+ conn_attributes = conn_attrs[1:-1].split(",")
2951
+ for attr in conn_attributes:
2952
+ if attr == "":
2953
+ continue
2954
+ attr_name_val = attr.split("=")
2955
+ attr_name = attr_name_val[0]
2956
+ attr_val = attr_name_val[1] if len(attr_name_val) > 1 else ""
2957
+ if attr_name in attributes:
2958
+ raise InterfaceError(
2959
+ f"Duplicate key '{attr_name}' used in connection-attributes"
2960
+ )
2961
+ attributes[attr_name] = attr_val
2962
+ elif isinstance(conn_attrs, dict):
2963
+ for attr_name in conn_attrs:
2964
+ attr_value = conn_attrs[attr_name]
2965
+ if not isinstance(attr_value, str):
2966
+ attr_value = repr(attr_value)
2967
+ attributes[attr_name] = attr_value
2968
+ elif isinstance(conn_attrs, bool) or conn_attrs in [0, 1]:
2969
+ if conn_attrs:
2970
+ settings["connection-attributes"] = {}
2971
+ else:
2972
+ settings["connection-attributes"] = False
2973
+ return
2974
+ elif isinstance(conn_attrs, set):
2975
+ for attr_name in conn_attrs:
2976
+ attributes[attr_name] = ""
2977
+ elif isinstance(conn_attrs, list):
2978
+ for attr in conn_attrs:
2979
+ if attr == "":
2980
+ continue
2981
+ attr_name_val = attr.split("=")
2982
+ attr_name = attr_name_val[0]
2983
+ attr_val = attr_name_val[1] if len(attr_name_val) > 1 else ""
2984
+ if attr_name in attributes:
2985
+ raise InterfaceError(
2986
+ f"Duplicate key '{attr_name}' used in connection-attributes"
2987
+ )
2988
+ attributes[attr_name] = attr_val
2989
+ elif not isinstance(conn_attrs, bool):
2990
+ raise InterfaceError(
2991
+ "connection-attributes must be Boolean or a list of key-value "
2992
+ f"pairs, found: '{conn_attrs}'"
2993
+ )
2994
+
2995
+ if attributes:
2996
+ for attr_name, attr_value in attributes.items():
2997
+ # Validate name type
2998
+ if not isinstance(attr_name, str):
2999
+ raise InterfaceError(
3000
+ f"Attribute name '{attr_name}' must be a string type"
3001
+ )
3002
+ # Validate attribute name limit 32 characters
3003
+ if len(attr_name) > 32:
3004
+ raise InterfaceError(
3005
+ f"Attribute name '{attr_name}' exceeds 32 characters limit size"
3006
+ )
3007
+ # Validate names in connection-attributes cannot start with "_"
3008
+ if attr_name.startswith("_"):
3009
+ raise InterfaceError(
3010
+ "Key names in connection-attributes cannot start with "
3011
+ f"'_', found: '{attr_name}'"
3012
+ )
3013
+
3014
+ # Validate value type
3015
+ if not isinstance(attr_value, str):
3016
+ raise InterfaceError(
3017
+ f"Attribute '{attr_name}' value: '{attr_value}' must be "
3018
+ "a string type"
3019
+ )
3020
+ # Validate attribute value limit 1024 characters
3021
+ if len(attr_value) > 1024:
3022
+ raise InterfaceError(
3023
+ f"Attribute '{attr_name}' value: '{attr_value}' exceeds "
3024
+ "1024 characters limit size"
3025
+ )
3026
+
3027
+ settings["connection-attributes"] = attributes
3028
+
3029
+
3030
+ def _validate_tls_versions(settings: Dict[str, Any]) -> None:
3031
+ """Validate tls-versions.
3032
+
3033
+ Args:
3034
+ settings (dict): Settings dictionary.
3035
+
3036
+ Raises:
3037
+ :class:`mysqlx.InterfaceError`: If tls-versions name is not valid.
3038
+ """
3039
+ tls_versions = []
3040
+ if "tls-versions" not in settings:
3041
+ return
3042
+
3043
+ tls_versions_settings = settings["tls-versions"]
3044
+
3045
+ if isinstance(tls_versions_settings, str):
3046
+ if not (
3047
+ tls_versions_settings.startswith("[")
3048
+ and tls_versions_settings.endswith("]")
3049
+ ):
3050
+ raise InterfaceError(
3051
+ f"tls-versions must be a list, found: '{tls_versions_settings}'"
3052
+ )
3053
+ tls_vers = tls_versions_settings[1:-1].split(",")
3054
+ for tls_ver in tls_vers:
3055
+ tls_version = tls_ver.strip()
3056
+ if tls_version == "":
3057
+ continue
3058
+ if tls_version in tls_versions:
3059
+ raise InterfaceError(
3060
+ DUPLICATED_IN_LIST_ERROR.format(
3061
+ list="tls_versions", value=tls_version
3062
+ )
3063
+ )
3064
+ tls_versions.append(tls_version)
3065
+ elif isinstance(tls_versions_settings, list):
3066
+ if not tls_versions_settings:
3067
+ raise InterfaceError(
3068
+ "At least one TLS protocol version must be "
3069
+ "specified in 'tls-versions' list."
3070
+ )
3071
+ for tls_ver in tls_versions_settings:
3072
+ if tls_ver in tls_versions:
3073
+ raise InterfaceError(
3074
+ DUPLICATED_IN_LIST_ERROR.format(list="tls_versions", value=tls_ver)
3075
+ )
3076
+ tls_versions.append(tls_ver)
3077
+
3078
+ elif isinstance(tls_versions_settings, set):
3079
+ for tls_ver in tls_versions_settings:
3080
+ tls_versions.append(tls_ver)
3081
+ else:
3082
+ raise InterfaceError(
3083
+ "tls-versions should be a list with one or more of versions in "
3084
+ f"{', '.join(SUPPORTED_TLS_VERSIONS)}. found: '{tls_versions}'"
3085
+ )
3086
+
3087
+ if not tls_versions:
3088
+ raise InterfaceError(
3089
+ "At least one TLS protocol version must be specified in "
3090
+ "'tls-versions' list."
3091
+ )
3092
+
3093
+ use_tls_versions = []
3094
+ unacceptable_tls_versions = []
3095
+ not_tls_versions = []
3096
+ for tls_ver in tls_versions:
3097
+ if tls_ver in SUPPORTED_TLS_VERSIONS:
3098
+ use_tls_versions.append(tls_ver)
3099
+ if tls_ver in UNACCEPTABLE_TLS_VERSIONS:
3100
+ unacceptable_tls_versions.append(tls_ver)
3101
+ else:
3102
+ not_tls_versions.append(tls_ver)
3103
+
3104
+ if use_tls_versions:
3105
+ if use_tls_versions == ["TLSv1.3"] and not TLS_V1_3_SUPPORTED:
3106
+ raise NotSupportedError(
3107
+ TLS_VER_NO_SUPPORTED.format(tls_versions, SUPPORTED_TLS_VERSIONS)
3108
+ )
3109
+ settings["tls-versions"] = use_tls_versions
3110
+ elif unacceptable_tls_versions:
3111
+ raise NotSupportedError(
3112
+ TLS_VERSION_UNACCEPTABLE_ERROR.format(
3113
+ unacceptable_tls_versions, SUPPORTED_TLS_VERSIONS
3114
+ )
3115
+ )
3116
+ elif not_tls_versions:
3117
+ raise InterfaceError(TLS_VERSION_ERROR.format(tls_ver, SUPPORTED_TLS_VERSIONS))
3118
+
3119
+
3120
+ def _validate_tls_ciphersuites(settings: Dict[str, Any]) -> None:
3121
+ """Validate tls-ciphersuites.
3122
+
3123
+ Args:
3124
+ settings (dict): Settings dictionary.
3125
+
3126
+ Raises:
3127
+ :class:`mysqlx.InterfaceError`: If tls-ciphersuites name is not valid.
3128
+ """
3129
+ tls_ciphersuites = []
3130
+ if "tls-ciphersuites" not in settings:
3131
+ return
3132
+
3133
+ tls_ciphersuites_settings = settings["tls-ciphersuites"]
3134
+
3135
+ if isinstance(tls_ciphersuites_settings, str):
3136
+ if not (
3137
+ tls_ciphersuites_settings.startswith("[")
3138
+ and tls_ciphersuites_settings.endswith("]")
3139
+ ):
3140
+ raise InterfaceError(
3141
+ "tls-ciphersuites must be a list, found: "
3142
+ f"'{tls_ciphersuites_settings}'"
3143
+ )
3144
+ tls_css = tls_ciphersuites_settings[1:-1].split(",")
3145
+ if not tls_css:
3146
+ raise InterfaceError(
3147
+ "No valid cipher suite found in the 'tls-ciphersuites' list"
3148
+ )
3149
+ for tls_cs in tls_css:
3150
+ tls_cs = tls_cs.strip().upper()
3151
+ if tls_cs:
3152
+ tls_ciphersuites.append(tls_cs)
3153
+ elif isinstance(tls_ciphersuites_settings, (list, set)):
3154
+ tls_ciphersuites = [tls_cs for tls_cs in tls_ciphersuites_settings if tls_cs]
3155
+ else:
3156
+ raise InterfaceError(
3157
+ "tls-ciphersuites should be a list with one or more ciphersuites. "
3158
+ f"Found: '{tls_ciphersuites_settings}'"
3159
+ )
3160
+
3161
+ tls_versions = (
3162
+ SUPPORTED_TLS_VERSIONS[:]
3163
+ if settings.get("tls-versions", None) is None
3164
+ else settings["tls-versions"][:]
3165
+ )
3166
+
3167
+ # A newer TLS version can use a cipher introduced on
3168
+ # an older version.
3169
+ tls_versions.sort(reverse=True)
3170
+ newer_tls_ver = tls_versions[0]
3171
+
3172
+ translated_names = []
3173
+ iani_cipher_suites_names = {}
3174
+ ossl_cipher_suites_names: List[str] = []
3175
+
3176
+ # Old ciphers can work with new TLS versions.
3177
+ # Find all the ciphers introduced on previous TLS versions
3178
+ for tls_ver in SUPPORTED_TLS_VERSIONS[
3179
+ : SUPPORTED_TLS_VERSIONS.index(newer_tls_ver) + 1
3180
+ ]:
3181
+ iani_cipher_suites_names.update(TLS_CIPHER_SUITES[tls_ver])
3182
+ ossl_cipher_suites_names.extend(OPENSSL_CS_NAMES[tls_ver])
3183
+
3184
+ for name in tls_ciphersuites:
3185
+ if "-" in name and name in ossl_cipher_suites_names:
3186
+ translated_names.append(name)
3187
+ elif name in iani_cipher_suites_names:
3188
+ translated_name = iani_cipher_suites_names[name]
3189
+ if translated_name in translated_names:
3190
+ raise AttributeError(
3191
+ DUPLICATED_IN_LIST_ERROR.format(
3192
+ list="tls_ciphersuites", value=translated_name
3193
+ )
3194
+ )
3195
+ translated_names.append(translated_name)
3196
+ else:
3197
+ raise InterfaceError(
3198
+ f"The value '{name}' in cipher suites is not a valid cipher suite"
3199
+ )
3200
+
3201
+ if not translated_names:
3202
+ raise InterfaceError(
3203
+ "No valid cipher suite found in the 'tls-ciphersuites' list"
3204
+ )
3205
+
3206
+ # raise an error when using an unacceptable cipher
3207
+ for cipher_as_ossl in translated_names:
3208
+ for tls_ver in SUPPORTED_TLS_VERSIONS[
3209
+ : SUPPORTED_TLS_VERSIONS.index(newer_tls_ver) + 1
3210
+ ]:
3211
+ if (
3212
+ cipher_as_ossl
3213
+ in UNACCEPTABLE_TLS_CIPHERSUITES.get(tls_ver, {}).values()
3214
+ ):
3215
+ raise NotSupportedError(
3216
+ f"Cipher {cipher_as_ossl} when used with {tls_ver} is unacceptable."
3217
+ )
3218
+
3219
+ settings["tls-ciphersuites"] = translated_names
3220
+
3221
+
3222
+ def _get_connection_settings(*args: Any, **kwargs: Any) -> Dict[str, Any]:
3223
+ """Parses the connection string and returns a dictionary with the
3224
+ connection settings.
3225
+
3226
+ Args:
3227
+ *args: Variable length argument list with the connection data used
3228
+ to connect to the database. It can be a dictionary or a
3229
+ connection string.
3230
+ **kwargs: Arbitrary keyword arguments with connection data used to
3231
+ connect to the database.
3232
+
3233
+ Returns:
3234
+ mysqlx.Session: Session object.
3235
+
3236
+ Raises:
3237
+ TypeError: If connection timeout is not a positive integer.
3238
+ :class:`mysqlx.InterfaceError`: If settings not provided.
3239
+ """
3240
+ settings = {}
3241
+ if args:
3242
+ if isinstance(args[0], str):
3243
+ settings = _parse_connection_uri(args[0])
3244
+ elif isinstance(args[0], dict):
3245
+ for key, val in args[0].items():
3246
+ settings[key.replace("_", "-")] = val
3247
+ elif kwargs:
3248
+ for key, val in kwargs.items():
3249
+ settings[key.replace("_", "-")] = val
3250
+
3251
+ if not settings:
3252
+ raise InterfaceError("Settings not provided")
3253
+
3254
+ _validate_settings(settings)
3255
+ return settings
3256
+
3257
+
3258
+ def get_session(*args: Any, **kwargs: Any) -> Session:
3259
+ """Creates a Session instance using the provided connection data.
3260
+
3261
+ Args:
3262
+ *args: Variable length argument list with the connection data used
3263
+ to connect to a MySQL server. It can be a dictionary or a
3264
+ connection string.
3265
+ **kwargs: Arbitrary keyword arguments with connection data used to
3266
+ connect to the database.
3267
+
3268
+ Returns:
3269
+ mysqlx.Session: Session object.
3270
+ """
3271
+ settings = _get_connection_settings(*args, **kwargs)
3272
+ return Session(settings)
3273
+
3274
+
3275
+ def get_client(
3276
+ connection_string: Union[str, Dict[str, Any]],
3277
+ options_string: Union[str, Dict[str, Any]],
3278
+ ) -> Client:
3279
+ """Creates a Client instance with the provided connection data and settings.
3280
+
3281
+ Args:
3282
+ connection_string: A string or a dict type object to indicate the \
3283
+ connection data used to connect to a MySQL server.
3284
+
3285
+ The string must have the following uri format::
3286
+
3287
+ cnx_str = 'mysqlx://{user}:{pwd}@{host}:{port}'
3288
+ cnx_str = ('mysqlx://{user}:{pwd}@['
3289
+ ' (address={host}:{port}, priority=n),'
3290
+ ' (address={host}:{port}, priority=n), ...]'
3291
+ ' ?[option=value]')
3292
+
3293
+ And the dictionary::
3294
+
3295
+ cnx_dict = {
3296
+ 'host': 'The host where the MySQL product is running',
3297
+ 'port': '(int) the port number configured for X protocol',
3298
+ 'user': 'The user name account',
3299
+ 'password': 'The password for the given user account',
3300
+ 'ssl-mode': 'The flags for ssl mode in mysqlx.SSLMode.FLAG',
3301
+ 'ssl-ca': 'The path to the ca.cert'
3302
+ "connect-timeout": '(int) milliseconds to wait on timeout'
3303
+ }
3304
+
3305
+ options_string: A string in the form of a document or a dictionary \
3306
+ type with configuration for the client.
3307
+
3308
+ Current options include::
3309
+
3310
+ options = {
3311
+ 'pooling': {
3312
+ 'enabled': (bool), # [True | False], True by default
3313
+ 'max_size': (int), # Maximum connections per pool
3314
+ "max_idle_time": (int), # milliseconds that a
3315
+ # connection will remain active while not in use.
3316
+ # By default 0, means infinite.
3317
+ "queue_timeout": (int), # milliseconds a request will
3318
+ # wait for a connection to become available.
3319
+ # By default 0, means infinite.
3320
+ }
3321
+ }
3322
+
3323
+ Returns:
3324
+ mysqlx.Client: Client object.
3325
+
3326
+ .. versionadded:: 8.0.13
3327
+ """
3328
+ if not isinstance(connection_string, (str, dict)):
3329
+ raise InterfaceError("connection_data must be a string or dict")
3330
+
3331
+ settings_dict = _get_connection_settings(connection_string)
3332
+
3333
+ if not isinstance(options_string, (str, dict)):
3334
+ raise InterfaceError("connection_options must be a string or dict")
3335
+
3336
+ if isinstance(options_string, str):
3337
+ try:
3338
+ options_dict = json.loads(options_string)
3339
+ except JSONDecodeError as err:
3340
+ raise InterfaceError(
3341
+ "'pooling' options must be given in the form of a document or dict"
3342
+ ) from err
3343
+ else:
3344
+ options_dict = {}
3345
+ for key, value in options_string.items():
3346
+ options_dict[key.replace("-", "_")] = value
3347
+
3348
+ if not isinstance(options_dict, dict):
3349
+ raise InterfaceError(
3350
+ "'pooling' options must be given in the form of a document or dict"
3351
+ )
3352
+ pooling_options_dict = {}
3353
+ if "pooling" in options_dict:
3354
+ pooling_options = options_dict.pop("pooling")
3355
+ if not isinstance(pooling_options, (dict)):
3356
+ raise InterfaceError(
3357
+ "'pooling' options must be given in the form document or dict"
3358
+ )
3359
+ # Fill default pooling settings
3360
+ pooling_options_dict["enabled"] = pooling_options.pop("enabled", True)
3361
+ pooling_options_dict["max_size"] = pooling_options.pop("max_size", 25)
3362
+ pooling_options_dict["max_idle_time"] = pooling_options.pop("max_idle_time", 0)
3363
+ pooling_options_dict["queue_timeout"] = pooling_options.pop("queue_timeout", 0)
3364
+
3365
+ # No other options besides pooling are supported
3366
+ if len(pooling_options) > 0:
3367
+ raise InterfaceError(f"Unrecognized pooling options: {pooling_options}")
3368
+ # No other options besides pooling are supported
3369
+ if len(options_dict) > 0:
3370
+ raise InterfaceError(
3371
+ f"Unrecognized connection options: {options_dict.keys()}"
3372
+ )
3373
+
3374
+ return Client(settings_dict, pooling_options_dict)