o
    EDi}                     @   s   d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlmZ ddl	m
Z
mZ ddlmZmZ dd	lmZ dd
lmZ ddl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 G dd de Z!dS )    N)deque)contextmanager)time)urlparse   )errorsdefines)ColumnOrientedBlockRowOrientedBlock)
Connection)	log_block)ServerPacketTypes)IterQueryResultProgressQueryResultQueryResult	QueryInfo)escape_params)column_chunkschunks	parse_urlc                       sr  e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	dd Z
dd Z		dGddZdHddZdd Zdd Zdd Zdd Zdd Zed d! Z		"	dId#d$Z		"	dId%d&Z		"	'dJd(d)Z	"	*dKd+d,Z	"	"dLd-d.Z		"	dMd/d0Z		"	dMd1d2Z		"	dNd3d4Z	"	dOd5d6Zd7d8 ZdPd9d:Zd;d< Z d=d> Z!d?d@ Z"dHdAdBZ#dCdD Z$e%dEdF Z&  Z'S )QClienta  
    Client for communication with the ClickHouse server.
    Single connection is established per each connected instance of the client.

    :param settings: Dictionary of settings that passed to every query (except
                     for the client settings, see below). Defaults to ``None``
                     (no additional settings). See all available settings in
                     `ClickHouse docs
                     <https://clickhouse.com/docs/en/operations/settings/settings/>`_.
    :param \**kwargs: All other args are passed to the
                       :py:class:`~clickhouse_driver.connection.Connection`
                       constructor.

    The following keys when passed in ``settings`` are used for configuring the
    client itself:

        * ``insert_block_size`` -- chunk size to split rows for ``INSERT``.
          Defaults to ``1048576``.
        * ``strings_as_bytes`` -- turns off string column encoding/decoding.
        * ``strings_encoding`` -- specifies string encoding. UTF-8 by default.
        * ``use_numpy`` -- Use NumPy for columns reading. New in version
                           *0.2.0*.
        * ``opentelemetry_traceparent`` -- OpenTelemetry traceparent header as
                           described by W3C Trace Context recommendation.
                           New in version *0.2.2*.
        * ``opentelemetry_tracestate`` -- OpenTelemetry tracestate header as
                           described by W3C Trace Context recommendation.
                           New in version *0.2.2*.
        * ``quota_key`` -- A string to differentiate quotas when the user have
                           keyed quotas configured on server.
                           New in version *0.2.3*.
        * ``input_format_null_as_default`` -- Initialize null fields with
                           default values if data type of this field is not
                           nullable. Does not work for NumPy. Default: False.
                           New in version *0.2.4*.
        * ``round_robin`` -- If ``alt_hosts`` are provided the query will be
                           executed on host picked with round-robin algorithm.
                           New in version *0.2.5*.
        * ``namedtuple_as_json`` -- Controls named tuple and nested types
                           deserialization. To interpret these column alongside
                           with ``allow_experimental_object_type=1`` as Python
                           tuple set ``namedtuple_as_json`` to ``False``.
                           Default: True.
                           New in version *0.2.6*.
        * ``server_side_params`` -- Species on which side query parameters
                           should be rendered into placeholders.
                           Default: False. Means that parameters are rendered
                           on driver's side.
                           New in version *0.2.7*.
    
insert_block_sizestrings_as_bytesstrings_encoding	use_numpyopentelemetry_traceparentopentelemetry_tracestate	quota_keyinput_format_null_as_defaultnamedtuple_as_jsonserver_side_paramsc                    s  | dd pi  | _t| j dtj| j dd| j dtj| j dd| j dd | j dd	| j d
d	| j dd| j dd| j ddd
| _| jd ruzddlm	}m
}m} || _|| _|| _W n tyt   tdw t| _t| _t| _| dd}tt|i |g| _|rd|v r| d}|dD ]O}td| }	| }
t|}|dkr|	j|	jf|dd   }n!|dkr|	jf|dd   }|	j|
d< nt }|	j|
d< |	j|
d< t|i |
}| j| q|  | _|    t!t"| #  d S )Nsettingsr   r   Fr   r   r   r    r   r   r    Tr!   r   r   )NumpyIterQueryResultNumpyProgressQueryResultNumpyQueryResult"Extras for NumPy must be installedround_robin	alt_hosts,zclickhouse://   porthost)$popcopyr"   intr   DEFAULT_INSERT_BLOCK_SIZESTRINGS_ENCODINGclient_settingsnumpy.resultr$   r%   r&   query_result_clsiter_query_result_clsprogress_query_result_clsImportErrorRuntimeErrorr   r   r   r   r   connectionssplitr   lenhostnamer,   tupleappendget_connection
connectionreset_last_querysuperr   __init__)selfargskwargsr$   r%   r&   r(   r)   r-   urlconnection_kwargsnum_argsconnection_argsrA   	__class__ Q/var/www/Datamplify/venv/lib/python3.10/site-packages/clickhouse_driver/client.pyrD   U   s   
!




zClient.__init__c                 C   s   | S NrN   rE   rN   rN   rO   	__enter__   s   zClient.__enter__c                 C   s   |    d S rP   )
disconnect)rE   exc_typeexc_valexc_tbrN   rN   rO   __exit__   s   zClient.__exit__c                 C   s:   t | dr| j| j | j }| j|j_| j|j_|S )NrA   )hasattrr:   r?   rA   popleftr"   contextr3   rE   rA   rN   rN   rO   r@      s   



zClient.get_connectionc                 C   s    |    | jD ]}|  qd S rP   )disconnect_connectionr:   rS   r[   rN   rN   rO   rS      s   

zClient.disconnectc                 C   s   | j   |   dS )z.
        Disconnects from the server.
        N)rA   rS   rB   rQ   rN   rN   rO   r\      s   
zClient.disconnect_connectionc                 C   s
   d | _ d S rP   )
last_queryrQ   rN   rN   rO   rB      s   
zClient.reset_last_queryFc                 C   s4   |   }|r| j|||dS | j|||d}| S )Nwith_column_typescolumnar)packet_generatorr7   r5   
get_result)rE   r_   progressr`   genresultrN   rN   rO   receive_result   s   zClient.receive_resultc                 c   s6    |   }| j||d}|D ]
}|D ]}|V  qqd S Nr_   )ra   r6   )rE   r_   rd   re   rowsrowrN   rN   rO   iter_receive_result   s   zClient.iter_receive_resultc              	   c   sL    	 z|   }|sW d S |du rW q|V  W n ttfy$   |    w q)NT)receive_packet	ExceptionKeyboardInterruptrS   rE   packetrN   rN   rO   ra      s   
zClient.packet_generatorc                 C   s   | j  }|jtjkr|j|jtjkr| j|j	 |S |jtj
kr%dS |jtjkr-|S |jtjkr5|S |jtjkr=|S |jtjkrL| j|j dS dS )NFT)rA   rl   typer   	EXCEPTION	exceptionPROGRESSr]   store_progressrc   END_OF_STREAMDATATOTALSEXTREMESPROFILE_INFOstore_profileprofile_inforo   rN   rN   rO   rl      s$   
zClient.receive_packetc                 C   sd   t |pi }| j }| jD ]}||v r||||< q|| jj_| j }|| || jj_d S rP   )	dictr3   r/   available_client_settingsr.   rA   rZ   r"   update)rE   r"   r3   keyquery_settingsrN   rN   rO   make_query_settings  s   




zClient.make_query_settingsc                 C   s4   | d}| dr|dd    | j_d S d S )Nz; zuse    )striplower
startswithrA   database)rE   queryrN   rN   rO   track_current_database  s   
zClient.track_current_databasec              
   C   s   t | j}t| dr|d7 }t|D ]-}z|  | _| | | j  t | _	W  d S  t
jt
jfy?   ||d k r>Y q w d S )NrA   r   )r<   r:   rX   ranger@   rA   r   force_connectr   r]   r   SocketTimeoutErrorNetworkError)rE   r"   num_connectionsirN   rN   rO   establish_connection#  s    





zClient.establish_connectionc              	   c   sJ    z|  | d | jj_d V  | | W d S  ttfy$   |    w rP   )r   rA   server_infosession_timezoner   rm   rn   rS   )rE   r   r"   rN   rN   rO   disconnect_on_error6  s   

zClient.disconnect_on_errorNc	              
   C   s   t  }	| ||6 t|tttjf}
|
r!| j||||||d}n| j|||||||d}| j	
t  |	  |W  d   S 1 sBw   Y  dS )a  
        Executes query.

        Establishes new connection if it wasn't established yet.
        After query execution connection remains intact for next queries.
        If connection can't be reused it will be closed and new connection will
        be created.

        :param query: query that will be send to server.
        :param params: substitution parameters for SELECT queries and data for
                       INSERT queries. Data for INSERT can be `list`, `tuple`
                       or :data:`~types.GeneratorType`.
                       Defaults to ``None`` (no parameters  or data).
        :param with_column_types: if specified column names and types will be
                                  returned alongside with result.
                                  Defaults to ``False``.
        :param external_tables: external tables to send.
                                Defaults to ``None`` (no external tables).
        :param query_id: the query identifier. If no query id specified
                         ClickHouse server will generate it.
        :param settings: dictionary of query settings.
                         Defaults to ``None`` (no additional settings).
        :param types_check: enables type checking of data for INSERT queries.
                            Causes additional overhead. Defaults to ``False``.
        :param columnar: if specified the result of the SELECT query will be
                         returned in column-oriented form.
                         It also allows to INSERT data in columnar form.
                         Defaults to ``False`` (row-like form).

        :return: * number of inserted rows for INSERT queries with data.
                   Returning rows count from INSERT FROM SELECT is not
                   supported.
                 * if `with_column_types=False`: `list` of `tuples` with
                   rows/columns.
                 * if `with_column_types=True`: `tuple` of 2 elements:
                    * The first element is `list` of `tuples` with
                      rows/columns.
                    * The second element information is about columns: names
                      and types.
        )external_tablesquery_idtypes_checkr`   paramsr_   r   r   r   r`   N)r   r   
isinstancelistr>   typesGeneratorTypeprocess_insert_queryprocess_ordinary_queryr]   store_elapsed)rE   r   r   r_   r   r   r"   r   r`   
start_time	is_insertrvrN   rN   rO   executeD  s$   ,$zClient.executec	           	   
   C   sH   |  || | j|||||||dW  d   S 1 sw   Y  dS )a  
        Executes SELECT query with progress information.
        See, :ref:`execute-with-progress`.

        :param query: query that will be send to server.
        :param params: substitution parameters for SELECT queries and data for
                       INSERT queries. Data for INSERT can be `list`, `tuple`
                       or :data:`~types.GeneratorType`.
                       Defaults to ``None`` (no parameters  or data).
        :param with_column_types: if specified column names and types will be
                                  returned alongside with result.
                                  Defaults to ``False``.
        :param external_tables: external tables to send.
                                Defaults to ``None`` (no external tables).
        :param query_id: the query identifier. If no query id specified
                         ClickHouse server will generate it.
        :param settings: dictionary of query settings.
                         Defaults to ``None`` (no additional settings).
        :param types_check: enables type checking of data for INSERT queries.
                            Causes additional overhead. Defaults to ``False``.
        :param columnar: if specified the result will be returned in
                         column-oriented form.
                         Defaults to ``False`` (row-like form).
        :return: :ref:`progress-query-result` proxy.
        r   N)r   $process_ordinary_query_with_progress)	rE   r   r   r_   r   r   r"   r   r`   rN   rN   rO   execute_with_progress  s   $zClient.execute_with_progressr   c	           
   	   C   s\   |  || | j||||||d}	|dkrt|	|n|	W  d   S 1 s'w   Y  dS )a  
        *New in version 0.0.14.*

        Executes SELECT query with results streaming. See, :ref:`execute-iter`.

        :param query: query that will be send to server.
        :param params: substitution parameters for SELECT queries and data for
                       INSERT queries. Data for INSERT can be `list`, `tuple`
                       or :data:`~types.GeneratorType`.
                       Defaults to ``None`` (no parameters  or data).
        :param with_column_types: if specified column names and types will be
                                  returned alongside with result.
                                  Defaults to ``False``.
        :param external_tables: external tables to send.
                                Defaults to ``None`` (no external tables).
        :param query_id: the query identifier. If no query id specified
                         ClickHouse server will generate it.
        :param settings: dictionary of query settings.
                         Defaults to ``None`` (no additional settings).
        :param types_check: enables type checking of data for INSERT queries.
                            Causes additional overhead. Defaults to ``False``.
        :param chunk_size: chunk query results.
        :return: :ref:`iter-query-result` proxy.
        )r   r_   r   r   r   r   N)r   iter_process_ordinary_queryr   )
rE   r   r   r_   r   r   r"   r   
chunk_sizer   rN   rN   rO   execute_iter  s   $zClient.execute_iterTc           
   	   C   s~   zddl }W n ty   tdw | j|dd||||d\}}	dd |	D }	|r0dd |	D }	|jd	d
 t||	D |	dS )aQ  
        *New in version 0.2.0.*

        Queries DataFrame with specified SELECT query.

        :param query: query that will be send to server.
        :param params: substitution parameters.
                       Defaults to ``None`` (no parameters  or data).
        :param external_tables: external tables to send.
                                Defaults to ``None`` (no external tables).
        :param query_id: the query identifier. If no query id specified
                         ClickHouse server will generate it.
        :param settings: dictionary of query settings.
                         Defaults to ``None`` (no additional settings).
        :param replace_nonwords: boolean to replace non-words in column names
                                 to underscores. Defaults to ``True``.
        :return: pandas DataFrame.
        r   Nr'   T)r`   r_   r   r   r   r"   c                 S   s   g | ]\}}|qS rN   rN   ).0nametype_rN   rN   rO   
<listcomp>      z*Client.query_dataframe.<locals>.<listcomp>c                 S   s   g | ]	}t d d|qS )z\W_)resubr   xrN   rN   rO   r     s    c                 S   s   i | ]\}}||qS rN   rN   )r   dcolrN   rN   rO   
<dictcomp>      z*Client.query_dataframe.<locals>.<dictcomp>)columns)pandasr8   r9   r   	DataFramezip)
rE   r   r   r   r   r"   replace_nonwordspddatar   rN   rN   rO   query_dataframe  s    
zClient.query_dataframec                    s  zddl }W n ty   tdw t }| ||^ | jj||d | j| |  }d}	|rgdd |j	D }
t
|
t
 j }t|rRd}t|t| fdd|
D }| j||d	d
}	|   | jt |  |	W  d   S 1 s|w   Y  dS )ay  
        *New in version 0.2.0.*

        Inserts pandas DataFrame with specified query.

        :param query: query that will be send to server.
        :param dataframe: pandas DataFrame.
        :param external_tables: external tables to send.
                                Defaults to ``None`` (no external tables).
        :param query_id: the query identifier. If no query id specified
                         ClickHouse server will generate it.
        :param settings: dictionary of query settings.
                         Defaults to ``None`` (no additional settings).
        :return: number of inserted rows.
        r   Nr'   r   c                 S   s   g | ]}|d  qS )r   rN   r   rN   rN   rO   r     r   z+Client.insert_dataframe.<locals>.<listcomp>z&DataFrame missing required columns: {}c                    s   g | ]} | j qS rN   )values)r   column	dataframerN   rO   r   !  r   T)r`   )r   r8   r9   r   r   rA   
send_querysend_external_tablesreceive_sample_blockcolumns_with_typessetr   r<   
ValueErrorformatr   	send_datareceive_end_of_queryr]   r   )rE   r   r   r   r   r"   r   r   sample_blockr   r   diffmsgr   rN   r   rO   insert_dataframe  s.   $zClient.insert_dataframec                 C   sL   |d ur|  ||| jj}| jj|||d | jj||d | j|d|dS )Nr   r   r   T)r_   rc   r`   substitute_paramsrA   rZ   r   r   rf   rE   r   r   r_   r   r   r   r`   rN   rN   rO   r   (  s   
z+Client.process_ordinary_query_with_progressc                 C   sJ   |d ur|  ||| jj}| jj|||d | jj||d | j||dS )Nr   r   r^   r   r   rN   rN   rO   r   8  s   
zClient.process_ordinary_queryc                 C   sH   |d ur|  ||| jj}| jj|||d | jj||d | j|dS )Nr   r   rh   )r   rA   rZ   r   r   rk   )rE   r   r   r_   r   r   r   rN   rN   rO   r   G  s   
z"Client.iter_process_ordinary_queryc           	      C   sN   | j j||d | j j||d |  }|r%| j||||d}|   |S d S )Nr   r   )r   r`   )rA   r   r   r   r   receive_end_of_insert_query)	rE   query_without_datar   r   r   r   r`   r   r   rN   rN   rO   r   V  s   zClient.process_insert_queryc                 C   sr   	 | j  }|jtjkr|jS |jtjkr|j|jtjkr$t	|j n|jtj
kr+n| j d|j}t|q)NTz$Data, Exception, Log or TableColumns)rA   rl   rq   r   rw   blockrr   rs   LOGr   TABLE_COLUMNSunexpected_packet_messager   UnexpectedPacketFromServerErrorrE   rp   messagerN   rN   rO   r   d  s   

zClient.receive_sample_blockc                 C   s   d}| j jj}|rtnt}|d r.zddlm} |r|}	ntdW n ty-   t	dw |r2tnt
}	|	||d D ]}
||j|
|d}| j | ||j7 }|   q;| j |  |   |S )	Nr   r   r   )r   z0NumPy inserts is only allowed with columnar=Truer'   r   r   )rA   rZ   r3   r	   r
   numpy.helpersr   r   r8   r9   r   r   r   num_rowsreceive_profile_events)rE   r   r   r   r`   inserted_rowsr3   	block_clsnumpy_column_chunksslicerchunkr   rN   rN   rO   r   z  s4   


zClient.send_datac                 C   s   	 | j  }|jtjkrd S |jtjkr| j|j n7|jtj	kr%|j
|jtjkr1t|j n"|jtjkr8n|jtjkrF| j|j n| j d|j}t|q)NTzDException, EndOfStream, Progress, TableColumns, ProfileEvents or Log)rA   rl   rq   r   rv   rt   r]   ru   rc   rr   rs   r   r   r   r   PROFILE_EVENTSr{   r|   r   r   r   r   rN   rN   rO   r     s(   

zClient.receive_end_of_queryc                 C   s~   	 | j  }|jtjkrd S |jtjkrt|j n$|jtjkr(| j	
|j n|jtjkr1|j| j d|j}t|q)NTz'EndOfStream, Log, Progress or Exception)rA   rl   rq   r   rv   r   r   r   rt   r]   ru   rc   rr   rs   r   r   r   r   rN   rN   rO   r     s   

z"Client.receive_end_of_insert_queryc                 C   s   | j jj}|tjk rd S 	 | j  }|jtjkr!| j	
|j d S |jtjkr/| j	|j n)|jtjkr;t|j n|jtjkrD|j|jtjkrKn| j d|j}t|q)NTz9ProfileEvents, Progress, Log, Exception or TimezoneUpdate)rA   r   used_revisionr   7DBMS_MIN_PROTOCOL_VERSION_WITH_PROFILE_EVENTS_IN_INSERTrl   rq   r   r   r]   r{   r|   rt   ru   rc   r   r   r   rr   rs   TIMEZONE_UPDATEr   r   r   )rE   revisionrp   r   rN   rN   rO   r     s0   


zClient.receive_profile_eventsc                 C   s   | j   | j|dS rg   )rA   send_cancelrf   )rE   r_   rN   rN   rO   cancel  s   
zClient.cancelc                 C   s6   | j jjd r	|S t|tstdt||}|| S )a  
        Substitutes parameters into a provided query.

        For example::

            client = Client(...)

            substituted_query = client.substitute_params(
                query='SELECT 1234, %(foo)s',
                params={'foo': 'bar'},
                context=client.connection.context
            )

            # prints: SELECT 1234, 'bar'
            print(substituted_query)
        r!   z$Parameters are expected in dict form)rA   rZ   r3   r   r}   r   r   )rE   r   r   rZ   escapedrN   rN   rO   r     s   

zClient.substitute_paramsc                 C   s   t |\}}| |fi |S )a  
        Return a client configured from the given URL.

        For example::

            clickhouse://[user:password]@localhost:9000/default
            clickhouses://[user:password]@localhost:9440/default

        Three URL schemes are supported:

            * clickhouse:// creates a normal TCP socket connection
            * clickhouses:// creates a SSL wrapped TCP socket connection

        Any additional querystring arguments will be passed along to
        the Connection class's initializer.
        )r   )clsrH   r-   rG   rN   rN   rO   from_url  s   zClient.from_url)FFF)F)NFNNNFF)NFNNNFr   )NNNNT)NNN)NFNNFF)NFNNF)NNFF)FF)(__name__
__module____qualname____doc__r~   rD   rR   rW   r@   rS   r\   rB   rf   rk   ra   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr   __classcell__rN   rN   rL   rO   r      s~    3R




D
&
%
*
0




(
"r   )"r   collectionsr   
contextlibr   r   r   urllib.parser   r#   r   r   r   r	   r
   rA   r   logr   protocolr   re   r   r   r   r   util.escaper   util.helpersr   r   r   objectr   rN   rN   rN   rO   <module>   s    