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