3
(hg}              -   @   s  d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZmZ ddlmZmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZ dd	lmZ dd
lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZC ejEdZFejEdejGZHejEdejGZIejEdZJddddddgZKeKddddddddd d!d"d#d$d%d&g ZLejMeNjOejP  d'ZQd(ZRd)ZSd*d+d,d-gZd.ZTeUed/rejVrd0ZTd1d2 ZWd3d4 ZXd5d6 ZYdpd7d8ZZd9d: Z[d;d< Z\d=d> Z]d?d@ Z^dAdB Z_dCdD Z`dEdFdDdBdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndog-ZadS )qz$MySQL X DevAPI Python implementation    N   )	constants)	INT_TYPESSTRING_TYPESJSONDecodeErrorurlparseunquote	parse_qsl)ClientSession)AuthLockContentionOPENSSL_CS_NAMESSSLModeTLS_VERSIONSTLS_CIPHER_SUITES)Schema
CollectionTableView)DbDoc)ErrorInterfaceErrorDatabaseErrorNotSupportedError	DataErrorIntegrityErrorProgrammingErrorOperationalErrorInternalError	PoolErrorTimeoutError)ColumnRowResultBufferingResult	RowResult	SqlResult	DocResult
ColumnType)	StatementFilterableStatementSqlStatementFindStatementAddStatementRemoveStatementModifyStatementSelectStatementInsertStatementDeleteStatementUpdateStatementCreateCollectionIndexStatementExprReadStatementWriteStatement)
ExprParserz,(?![^\(\)]*\))z!^\(address=(.+),priority=(\d+)\)$z^\(address=(.+)[,]*\)$z"^([a-zA-Z][a-zA-Z0-9+\-.]+)://(.*)zssl-certzssl-cazssl-keyzssl-crlztls-versionsztls-ciphersuitesuserpasswordschemahostportrouterssocketzssl-modeauthzuse-purezconnect-timeoutzconnection-attributescompressionzcompression-algorithmszdns-srvzVThe '{list}' list must not contain repeated values, the value '{value}' is duplicated.zdThe given tls-version: '{}' is not recognized as a valid TLS protocol version (should be one of {}).zINo supported TLS protocol version found in the 'tls-versions' list '{}'. ZTLSv1zTLSv1.1zTLSv1.2zTLSv1.3FHAS_TLSv1_3Tc       	      C   s  | j dd} d| ko.| jddko.| jddk oD| jdoD| jd}g }tj|r^| dd n| }d}x|D ]}i }tj|}|r|jd}t	|jd	|d
< |d7 }n t
j|}|r|jd}d|d
< tdj|}|jstdj|y|j|j|jd W n4 tk
r6 } ztdj|dW Y dd}~X nX |j| qnW d|  k o^t|k n  rptdd|r~d|iS |d S )zParses a list of host, port pairs

    Args:
        path: String containing a list of routers or just router

    Returns:
        Returns a dict with parsed values of host, port and priority if
        specified.
      ,:r   []r      priorityd   z//{0}zInvalid address: {0})r=   r>   zInvalid URI: {0}i  Nz\You must either assign no priority to any of the routers or give a priority for every routeri  r?   )replacecount
startswithendswith	_SPLIT_REsplit_PRIORITY_REmatchgroupint
_ROUTER_REr   formathostnamer   updater>   
ValueErrorr   appendlen)	patharrayr?   Zaddress_listZpriority_countaddressrouterrU   err rd   C/tmp/pip-install-q3hcpn_q/mysql-connector-python/mysqlx/__init__.py_parse_address_listY   s<    







" rf   c             C   s  ddi}t j| }|r|j nd| f\}} |d#kr@tdj||dkrPd|d< | jdd	d	d
 \}}|jdd	d	d
 \}}|jd}||d	 jdd$kr|dkr|jdd\}|d< |j	d}| s| sd|krtdj| |j
dd\}	}
t|	t|
 |d< |d< |jd%r,t||d< n$|jdrBtdn|jt| d&}xt|dD ]\}}|jddj }||krtdj|||krtdj||tkrt|j	d||< n8|j }|d'krd||< n|d(krd"||< n|||< q`W |S ))a  Parses the connection string and returns a dictionary with the
    connection settings.

    Args:
        uri: mysqlx URI scheme to connect to a MySQL server/farm.

    Returns:
        Returns a dict with parsed values of credentials and address of the
        MySQL server/farm.

    Raises:
        :class:`mysqlx.InterfaceError`: If contains a duplicate option or
                                        URI scheme is not valid.
    r<   rE   mysqlx
mysqlx+srvzScheme '{0}' is not validTdns-srv@NrJ   ?/)r   r   z()rG   zMalformed URI '{0}'r:   r;   ...r@   z\.zWindows Pipe is not supported_-zInvalid option: '{0}'zDuplicate option: '{0}'1true0falseF)rg   rh   rM   )rl   rn   ro   )r:   r;   ri   )rr   rs   )rt   ru   )_URI_SCHEME_RErU   groupsr   rY   	partitionrfindfindrsplitstriprS   r   rP   r[   rf   r	   rN   lower	_SSL_OPTS)urisettingsrU   schemeuserinfotmpr=   Z	query_strposr:   r;   Zinvalid_optionskeyvaloptZval_strrd   rd   re   _parse_connection_uri   sL    










r   c                s  t  j jt}|r*tdjdj|d krPx, d D ]}t|d q<W nd kr`t  d kry" d j  d< t	j
 d  W n* ttfk
r   tdj d Y nX  d t	jkrt fdd	tD rtd
d krd krtdd krd krtdd kr@ jdt	jt	jgkr@tdd krj jdt	jt	jgkrjtdd kry" d j  d< tj
 d  W n, ttfk
r   tdj d Y nX d kr d j j }|d,krtdj d | d< d krt d trN d j jd}|rD|jd d< nd d< nt d ttfsjtd jddkrd d< d krt  d  kryHt d  trt d   d < t d  t s d  d!k rtW n tk
r   td"Y nX d# krft d# ts(td$ jd%r<td& jd'rPtd( jdrtd)n d kr jd' rd d'< d* krt  d+ krt   dS )-an  Validates the settings to be passed to a Session object
    the port values are converted to int if specified or set to 33060
    otherwise. The priority values for each router is converted to int
    if specified.

    Args:
        settings: dict containing connection settings.

    Raises:
        :class:`mysqlx.InterfaceError`: On any configuration issue.
    zInvalid option(s): '{0}'z', 'r?   i$  r=   zssl-modezInvalid SSL Mode '{0}'c             3   s   | ]}| kV  qd S )Nrd   ).0r   )r   rd   re   	<genexpr>   s    z%_validate_settings.<locals>.<genexpr>z)SSL options used with ssl-mode 'disabled'zssl-crlzssl-cazCA Certificate not providedzssl-keyzssl-certzClient Certificate not providedzCannot verify Server without CAz$Must verify Server if CA is providedrA   zInvalid Auth '{0}'rB   	preferredrequireddisabledzThe connection property 'compression' acceptable values are: 'preferred', 'required', or 'disabled'. The value '{0}' is not acceptablezcompression-algorithmsz[]rF   Nz@Invalid type of the connection property 'compression-algorithms'zconnection-attributeszconnect-timeoutr   zEThe connection timeout value must be a positive integer (including 0)zdns-srvz(The value of 'dns-srv' must be a booleanr@   z<Using Unix domain sockets with DNS SRV lookup is not allowedr>   z;Specifying a port number with DNS SRV lookup is not allowedzASpecifying multiple hostnames with DNS SRV look up is not allowedztls-versionsztls-ciphersuites)r   r   r   )!setkeys
difference
_SESS_OPTSr   rY   join_validate_hostsr}   r   indexAttributeErrorr\   ZDISABLEDanyr~   getZVERIFY_IDENTITYZ	VERIFY_CAr   r|   
isinstancer   rS   listtuple_validate_connection_attributesrW   r   	TypeErrorbool_validate_tls_versions_validate_tls_ciphersuites)r   Zinvalid_optsrb   rB   Zcompression_algorithmsrd   )r   re   _validate_settings   s    










r   c             C   s   d| kr| d ry6t | d | d< | d dk s:| d dkrDtddW nD tk
rd   tddY n( tk
r   tdj| d dY nX d| kr| d ryt | d | d< W q tk
r   td	Y qX nd
| kr|r|| d< dS )zValidate hosts.

    Args:
        settings (dict): Settings dictionary.
        default_port (int): Default connection port.

    Raises:
        :class:`mysqlx.InterfaceError`: If priority or port are invalid.
    rK   r   rL   z1Invalid priority value, must be between 0 and 100i  zInvalid priorityzInvalid priority: {}r>   zInvalid portr=   N)rW   r   	NameErrorr\   rY   r   )r   default_portrd   rd   re   r   ?  s$    

r   c       	      C   s  i }d| krdS | d }t |tr|dkr8i | d< dS |jdoJ|jd rf|dkrftd
j|n|dkr|dkrd| d< ni | d< dS |dd jd}xb|D ]Z}|dkrq|jd}|d }t|dkr|d nd}||k rtdj|q|||< qW n.t |trHx2|D ]*}|| }t |ts8t	|}|||< qW nt |t
s^|dkrz|rni | d< nd| d< dS t |trx|D ]}d||< qW nt |trx|D ]b}|dkrĐq|jd}|d }t|dkr|d nd}||kr
tdj|n|||< qW nt |t
s4tdj||rx|D ]}|| }t |tsftdj|t|dkrtdj||jdrtdj|t |tstdj||t|dkr@tdj||q@W || d< dS )zValidate connection-attributes.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If attribute name or value exceeds size.
    zconnection-attributesNrE   rH   rI   Falseru   Truers   z`The value of 'connection-attributes' must be a boolean or a list of key-value pairs, found: '{}'Fr   rF   =r   z0Duplicate key '{}' used in connection-attributeszOconnection-attributes must be Boolean or a list of key-value pairs, found: '{}'z(Attribute name '{}' must be a stringtype    z4Attribute name '{}' exceeds 32 characters limit sizerp   zEKey names in connection-attributes cannot start with '_', found: '{}'z0Attribute '{}' value: '{}' must be a string typei   z=Attribute '{}' value: '{}' exceeds 1024 characters limit size)r   ru   r   rs   )r   ru   r   rs   )r   ru   rM   )r   r   )r   r   rP   rQ   r   rY   rS   r^   dictreprr   r   r   )	r   
attributesZ
conn_attrsZconn_attributesattrZattr_name_val	attr_nameZattr_val
attr_valuerd   rd   re   r   ^  s    	















r   c             C   s  g }d| krdS | d }t |tr|jdo4|jdsFtdj|np|dd jd}x\|D ]T}|j }|dkrtq^|tkrtt	j|tq^||krtt
jd	|d
|j| q^W nt |tr"|stdx|D ]F}|tkrtt	j|tq||krtt
jd	|d
q|j| qW nZt |trfxL|D ],}|tkrTtt	j|tn
|j| q4W ntdjdjt||std|dgkrt rttj|t|| d< dS )zValidate tls-versions.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If tls-versions name is not valid.
    ztls-versionsNrH   rI   z(tls-versions must be a list, found: '{}'r   rF   rE   tls_versions)r   valuezKAt least one TLS protocol version must be specified in 'tls-versions' list.zMtls-versions should be a list with one or more of versions in {}. found: '{}'z, zTLSv1.3rM   )r   r   rP   rQ   r   rY   rS   r|   r   TLS_VERSION_ERRORDUPLICATED_IN_LIST_ERRORr]   r   r   r   TLS_V1_3_SUPPORTEDTLS_VER_NO_SUPPORTED)r   r   Ztls_versions_settingsZtls_verstls_verZtls_versionrd   rd   re   r     s`    	











r   c             C   s  g }d| krdS | d }t |tr|jdo4|jdsFtdj|q|dd jd}|sdtdxx|D ]}|j j }|rj|j	| qjW nPt |t
rd	d
 |D }n6t |trx*|D ]}|r|j	| qW ntdj|| jdddk rtdd n| d dd }|jdd |d }g }i }g }	x<tdtj|d  D ]"}
|jt|
  |	jt|
  qDW xx|D ]p}d|kr||	kr|j	| nJ||kr|| }||krttjd|dn
|j	| ntdj|qpW |std|| d< dS )zValidate tls-ciphersuites.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If tls-ciphersuites name is not valid.
    ztls-ciphersuitesNrH   rI   z,tls-ciphersuites must be a list, found: '{}'r   rF   z;No valid cipher suite found in the 'tls-ciphersuites' list.c             S   s   g | ]}|r|qS rd   rd   )r   tls_csrd   rd   re   
<listcomp>2  s    z._validate_tls_ciphersuites.<locals>.<listcomp>zLtls-ciphersuites should be a list with one or more ciphersuites. Found: '{}'ztls-versionsT)reverser   rq   tls_ciphersuites)r   r   z;The value '{}' in cipher suites is not a valid cipher suiterM   )r   r   rP   rQ   r   rY   rS   r|   upperr]   r   r   r   r   sortr   r[   r   extendr   r   r   )r   r   Ztls_ciphersuites_settingsZtls_cssr   r   Znewer_tls_verZtranslated_namesZiani_cipher_suites_namesZossl_cipher_suites_namesr   nameZtranslated_namerd   rd   re   r     sd    	








$


r   c              O   s   i }| r^t | d tr$t| d }qt | d trxT| d j D ]\}}|||jdd< q@W n*|rx$|j D ]\}}|||jdd< qlW |stdt| |S )aZ  Parses the connection string and returns a dictionary with the
    connection settings.

    Args:
        *args: Variable length argument list with the connection data used
               to connect to the database. It can be a dictionary or a
               connection string.
        **kwargs: Arbitrary keyword arguments with connection data used to
                  connect to the database.

    Returns:
        mysqlx.Session: Session object.

    Raises:
        TypeError: If connection timeout is not a positive integer.
        :class:`mysqlx.InterfaceError`: If settings not provided.
    r   rp   rq   zSettings not provided)r   r   r   r   itemsrN   r   r   )argskwargsr   r   r   rd   rd   re   _get_connection_settingsg  s    r   c              O   s   t | |}t|S )a  Creates a Session instance using the provided connection data.

    Args:
        *args: Variable length argument list with the connection data used
               to connect to a MySQL server. It can be a dictionary or a
               connection string.
        **kwargs: Arbitrary keyword arguments with connection data used to
                  connect to the database.

    Returns:
        mysqlx.Session: Session object.
    )r   r   )r   r   r   rd   rd   re   get_session  s    
r   c             C   sX  t | ttfstdt| }t |ttfs4tdt |trlytj|}W q tk
rh   tdY qX n*i }x$|j D ]\}}|||j	dd< qzW t |tstdi }d|krN|j
d}t |tstd|j
dd	|d< |j
d
d|d
< |j
dd|d< |j
dd|d< t|dkr.tdj|t|dkrNtdj|j t||S )a8  Creates a Client instance with the provided connection data and settings.

    Args:
        connection_string: A string or a dict type object to indicate the             connection data used to connect to a MySQL server.

            The string must have the following uri format::

                cnx_str = 'mysqlx://{user}:{pwd}@{host}:{port}'
                cnx_str = ('mysqlx://{user}:{pwd}@['
                           '    (address={host}:{port}, priority=n),'
                           '    (address={host}:{port}, priority=n), ...]'
                           '       ?[option=value]')

            And the dictionary::

                cnx_dict = {
                    'host': 'The host where the MySQL product is running',
                    'port': '(int) the port number configured for X protocol',
                    'user': 'The user name account',
                    'password': 'The password for the given user account',
                    'ssl-mode': 'The flags for ssl mode in mysqlx.SSLMode.FLAG',
                    'ssl-ca': 'The path to the ca.cert'
                    "connect-timeout": '(int) milliseconds to wait on timeout'
                }

        options_string: A string in the form of a document or a dictionary             type with configuration for the client.

            Current options include::

                options = {
                    'pooling': {
                        'enabled': (bool), # [True | False], True by default
                        'max_size': (int), # Maximum connections per pool
                        "max_idle_time": (int), # milliseconds that a
                            # connection will remain active while not in use.
                            # By default 0, means infinite.
                        "queue_timeout": (int), # milliseconds a request will
                            # wait for a connection to become available.
                            # By default 0, means infinite.
                    }
                }

    Returns:
        mysqlx.Client: Client object.

    .. versionadded:: 8.0.13
    z(connection_data must be a string or dictz+connection_options must be a string or dictzA'pooling' options must be given in the form of a document or dictrq   rp   Zpoolingz<'pooling' options must be given in the form document or dictZenabledTmax_size   Zmax_idle_timer   Zqueue_timeoutz Unrecognized pooling options: {}z#Unrecognized connection options: {})r   r   r   r   r   jsonloadsr   r   rN   popr^   rY   r   r
   )Zconnection_stringZoptions_stringZsettings_dictZoptions_dictr   r   Zpooling_options_dictZpooling_optionsrd   rd   re   
get_client  s>    2




r   r
   r   exprr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   )N)b__doc__rer   loggingsslrE   r   compatr   r   r   r   r   r	   
connectionr
   r   r   r   r   r   r   r   Zcrudr   r   r   r   Zdbdocr   errorsr   r   r   r   r   r   r   r   r   r    r!   resultr"   r#   r$   r%   r&   r'   r(   r)   Z	statementr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r   r9   compilerR   VERBOSErT   rX   rv   r~   r   	getLogger__name__
addHandlerNullHandlerr   r   r   r   hasattrrC   rf   r   r   r   r   r   r   r   r   r   __all__rd   rd   rd   re   <module>   sl     4(D



3Bq
mIS$d

