o
    EDi3                     @   s   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 d dlm	Z	m
Z
mZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZ d dlmZ d dl m!Z! e"e#Z$G dd dZ%e% Z&G dd dZ'dS )    N)ThreadPoolExecutor)tzinfo)OptionalUnionDictAnySequenceIterable	GeneratorBinaryIO)Client)StreamContext)
HttpClient)ExternalData)QueryContextQueryResult)QuerySummary)ClickHouseType)InsertContextc                   @   s   e Zd ZdS )DefaultThreadPoolExecutorN)__name__
__module____qualname__ r   r   ^/var/www/Datamplify/venv/lib/python3.10/site-packages/clickhouse_connect/driver/asyncclient.pyr      s    r   c                *   @   s  e Zd ZdZdeddededeede	f fdd	Z
d
d Zdee fddZdefddZdedefddZdd Z																drdee deeeeeef f  deeeef  deeeef  deeeeeeeef f f  dee dee dee dee d ee d!ed"eeeef  d#eeeeeef f  d$ee d%ee d&eeeef  def"d'd(Z													dsdee deeeeeef f  deeeef  deeeef  deeeeeeeef f f  dee dee d!ed"eeeef  d#eeeeeef f  d$ee d%ee d&eeeef  defd)d*Z													dsdee deeeeeef f  deeeef  deeeef  deeeeeeeef f f  dee dee d!ed"eeeef  d#eeeeeef f  d$ee d%ee d&eeeef  defd+d,Z													dsdee deeeeeef f  deeeef  deeeef  deeeeeeeef f f  dee dee d!ed"eeeef  d#eeeeeef f  d$ee d%ee d&eeeef  defd-d.Z				/		dtdedeeeeeef f  deeeef  d0ed1ed%ee d&eeeef  defd2d3Z 				/		dtdedeeeeeef f  deeeef  d0ed1ed%ee d&eeeef  de!j"fd4d5Z#											dudee deeeeeef f  deeeef  deeeef  deeeef  dee dee d ee d!ed%ee d&eeeef  fd6d7Z$											dudee deeeeeef f  deeeef  deeeef  deeeef  dee dee d ee d!ed%ee d&eeeef  defd8d9Z%																drdee deeeeeef f  deeeef  deeeef  deeeef  dee dee d ee d:ee d"ee d#eeeeeef f  d$ee d!ed%ee d;ee d&eeeef  f d<d=Z&						>dvdedeeeeeef f  deeeef  d?ee d%ee d&eeeef  d@ededA fdBdCZ'																drdee deeeeeef f  deeeef  deeeef  deeeef  dee dee d ee d:ee d"ee d#eeeeeef f  d$ee d!ed%ee d;ee d&eeeef  def"dDdEZ(						>dvdedeeeeeef f  deeeef  d?ee d%ee d&eeeef  d@edefdFdGZ)									H						H	H			dwdeeeef  deeeeeef f  deeeef  deeeef  deeeeeeeef f f  dee dee dee dee d ee d!ee d"eeeef  d#eeeeeef f  d:ee dIedJed%ee d;ee d&eeeef  def(dKdLZ*					dxdedeeeeeef f  deeeef  d?ee d%ee d&eeeef  fdMdNZ+					dxdedeeeeeef f  deeeef  d?ee d%ee d&eeeef  defdOdPZ,				/		dtdQedeeeeeef f  dReeef deeeef  d1ed%ee d&eeeef  deeeee e-f fdSdTZ.defdUdVZ/			W				H			dydXee dReee  dYeee0e f dZee d[ee1 d\ee dedeeeef  d!e2d&eeeef  de-fd]d^Z3									dzdXedZee dee dYeee  d[ee1 d\ee d!e2d&eeeef  de-fd_d`Z4			d{dXedZedee d&eeeef  de-f
dadbZ5			d{dXedcedA dZee dee d&eeeef  de-fdddeZ6					H			d|dXedYeeeee f  dZee d[ee1 d\ee dedeeeef  dReeee   d&eeeef  de2fdfdgZ7d!e2de-fdhdiZ8						d}dXedYeee  djeeee9eddf e:f dee d0ee dkee d&eeeef  de-fdldmZ;d~dndoZ<ddpdqZ=dS )AsyncClientz
    AsyncClient is a wrapper around the ClickHouse Client object that allows for async calls to the ClickHouse server.
    Internally, each of the methods that uses IO is wrapped in a call to EventLoop.run_in_executor.
    r   )executor_threadsexecutorclientr   r   Nc                C   s   t |tr|jd dd|jd< || _|dkr#tdt pdd }|tu r2d| _	t
|d	| _d S |dkr;td
 d| _	|| _d S )Nz
User-Agentz
mode:sync;zmode:async;r             T)max_workerszEexecutor_threads parameter is ignored when passing an executor objectF)
isinstancer   headersreplacer   minos	cpu_countNEW_THREAD_POOL_EXECUTORnew_executorr   r   loggerwarning)selfr   r   r   r   r   r   __init__$   s   


zAsyncClient.__init__c                 C   s   | j j||d dS )a  
        Set a clickhouse setting for the client after initialization.  If a setting is not recognized by ClickHouse,
        or the setting is identified as "read_only", this call will either throw a Programming exception or attempt
        to send the setting anyway based on the common setting 'invalid_setting_action'.
        :param key: ClickHouse setting name
        :param value: ClickHouse setting value
        )keyvalueN)r   set_client_setting)r-   r/   r0   r   r   r   r1   8   s   zAsyncClient.set_client_settingreturnc                 C   s   | j j|dS )zu
        :param key: The setting key
        :return: The string value of the setting, if it exists, or None
        )r/   )r   get_client_setting)r-   r/   r   r   r   r3   B   s   zAsyncClient.get_client_settingaccess_tokenc                 C   s   | j | dS )zq
        Set the ClickHouse access token for the client
        :param access_token: Access token string
        N)r   set_access_token)r-   r4   r   r   r   r5   I   s   zAsyncClient.set_access_tokenversion_strc                 C   s   | j |S )a  
        Determine whether the connected server is at least the submitted version
        For Altinity Stable versions like 22.8.15.25.altinitystable
        the last condition in the first list comprehension expression is added
        :param version_str: A version string consisting of up to 4 integers delimited by dots
        :return: True if version_str is greater than the server_version, False if less than
        )r   min_version)r-   r6   r   r   r   r7   P   s   zAsyncClient.min_versionc                    s0   | j   | jrt| jjdI dH  dS dS )ze
        Subclass implementation to close the connection to the server/deallocate the client
        TN)r   closer*   asyncio	to_threadr   shutdownr-   r   r   r   r8   Z   s
   
zAsyncClient.closequery
parameterssettingsquery_formatscolumn_formatsencodinguse_nonecolumn_oriented	use_numpymax_str_lencontextquery_tz
column_tzsutc_tz_awareexternal_datatransport_settingsc                    sN    	
fdd}t  }|j|I dH }|S )z
        Main query method for SELECT, DESCRIBE and other SQL statements that return a result matrix.
        For parameters, see the create_query_context method.
        :return: QueryResult -- data and metadata from response
        c                      sn   j jdi dddd	d dddd	d
dd
ddddS )Nr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   r   )r   r=   r   rA   rD   rI   rG   rB   rK   rF   r>   r=   r@   rH   r-   r?   rL   rC   rE   rJ   r   r   _queryz   s2   $z!AsyncClient.query.<locals>._queryNr9   get_running_looprun_in_executorr   )r-   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rN   loopresultr   rM   r   r=   c   s
   ,zAsyncClient.queryc                    H    	
fdd}t  }|	j|I dH }|S )z
        Variation of main query method that returns a stream of column oriented blocks.
        For parameters, see the create_query_context method.
        :return: StreamContext -- Iterable stream context that returns column oriented blocks
        c                      &   	j j
 dS N)r=   r>   r?   r@   rA   rB   rC   rG   rH   rI   rJ   rK   rL   )r   query_column_block_streamr   rA   rI   rG   rB   rK   r>   r=   r@   rH   r-   r?   rL   rC   rJ   r   r   _query_column_block_stream      zIAsyncClient.query_column_block_stream.<locals>._query_column_block_streamNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rG   rH   rI   rJ   rK   rL   rY   rR   rS   r   rX   r   rW      s
   &z%AsyncClient.query_column_block_streamc                    rT   )
        Variation of main query method that returns a stream of row oriented blocks.
        For parameters, see the create_query_context method.
        :return: StreamContext -- Iterable stream context that returns blocks of rows
        c                      rU   rV   )r   query_row_block_streamr   rX   r   r   _query_row_block_stream   rZ   zCAsyncClient.query_row_block_stream.<locals>._query_row_block_streamNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rG   rH   rI   rJ   rK   rL   r]   rR   rS   r   rX   r   r\      
   &z"AsyncClient.query_row_block_streamc                    rT   )r[   c                      rU   rV   )r   query_rows_streamr   rX   r   r   _query_rows_stream   rZ   z9AsyncClient.query_rows_stream.<locals>._query_rows_streamNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rG   rH   rI   rJ   rK   rL   r`   rR   rS   r   rX   r   r_      r^   zAsyncClient.query_rows_streamTfmtuse_databasec                    <    fdd}t  }	|	j|I dH }
|
S )a  
        Query method that simply returns the raw ClickHouse format bytes.
        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param fmt: ClickHouse output format
        :param use_database  Send the database parameter to ClickHouse so the command will be executed in the client
         database context
        :param external_data  External data to send with the query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: bytes representing raw ClickHouse return value based on format
        c                	         j j dS N)r=   r>   r?   ra   rb   rK   rL   )r   	raw_queryr   rK   ra   r>   r=   r-   r?   rL   rb   r   r   
_raw_query      z)AsyncClient.raw_query.<locals>._raw_queryNrO   )r-   r=   r>   r?   ra   rb   rK   rL   rh   rR   rS   r   rg   r   rf      s
   zAsyncClient.raw_queryc                    rc   )a  
        Query method that returns the result as an io.IOBase iterator.
        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param fmt: ClickHouse output format
        :param use_database  Send the database parameter to ClickHouse so the command will be executed in the client
         database context
        :param external_data  External data to send with the query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: io.IOBase stream/iterator for the result
        c                	      rd   re   )r   
raw_streamr   rg   r   r   _raw_stream  s   z+AsyncClient.raw_stream.<locals>._raw_streamNrO   )r-   r=   r>   r?   ra   rb   rK   rL   rk   rR   rS   r   rg   r   rj     s
   zAsyncClient.raw_streamc                    D    	
fdd}t  }|j|I dH }|S )z
        Query method that returns the results as a numpy array.
        For parameter values, see the create_query_context method.
        :return: Numpy array representing the result set
        c                      "   j j	 
dS N)r=   r>   r?   r@   rA   rB   rC   rF   rG   rK   rL   )r   query_npr   rA   rG   rB   rK   rF   r>   r=   r@   r-   r?   rL   rC   r   r   	_query_np3  s
   z'AsyncClient.query_np.<locals>._query_npNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rF   rG   rK   rL   rq   rR   rS   r   rp   r   ro   !  
   "zAsyncClient.query_npc                    rl   )z
        Query method that returns the results as a stream of numpy arrays.
        For parameter values, see the create_query_context method.
        :return: Generator that yield a numpy array per block representing the result set
        c                      rm   rn   )r   query_np_streamr   rp   r   r   _query_np_streamO  s
   z5AsyncClient.query_np_stream.<locals>._query_np_streamNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rF   rG   rK   rL   rt   rR   rS   r   rp   r   rs   =  rr   zAsyncClient.query_np_streamuse_na_valuesuse_extended_dtypesc                    N    	
fdd}t  }|
j|I dH }|S )z
        Query method that results the results as a pandas dataframe.
        For parameter values, see the create_query_context method.
        :return: Pandas dataframe representing the result set
        c                      n   
j jdi ddddd dddd	d
	ddddddS Nr=   r>   r?   r@   rA   rB   rC   rF   ru   rH   rI   rJ   rG   rK   rv   rL   r   )r   query_dfr   rA   rI   rG   rB   rK   rF   r>   r=   r@   rH   r-   r?   rL   rv   ru   rC   rJ   r   r   	_query_dfp  s6   z'AsyncClient.query_df.<locals>._query_dfNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rF   ru   rH   rI   rJ   rG   rK   rv   rL   r|   rR   rS   r   r{   r   rz   Y  s
   ,	zAsyncClient.query_dfpandasuse_stringsdataframe_library)zpd.DataFramezpl.DataFramec                    rc   )a  
        Query method using the ClickHouse Arrow format to return a DataFrame
        with PyArrow dtype backend. This provides better performance and memory efficiency
        compared to the standard query_df method, though fewer output formatting options.

        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param use_strings: Convert ClickHouse String type to Arrow string type (instead of binary)
        :param external_data: ClickHouse "external data" to send with query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :param dataframe_library: Library to use for DataFrame creation ("pandas" or "polars")
        :return: DataFrame (pandas or polars based on dataframe_library parameter)
        c                	         j j dS N)r=   r>   r?   r~   rK   rL   r   )r   query_df_arrowr   r   rK   r>   r=   r-   r?   rL   r~   r   r   _query_df_arrow     z3AsyncClient.query_df_arrow.<locals>._query_df_arrowNrO   )r-   r=   r>   r?   r~   rK   rL   r   r   rR   rS   r   r   r   r   }  s
   zAsyncClient.query_df_arrowc                    rw   )z
        Query method that returns the results as a StreamContext.
        For parameter values, see the create_query_context method.
        :return: Generator that yields a Pandas dataframe per block representing the result set
        c                      rx   ry   )r   query_df_streamr   r{   r   r   _query_df_stream  s6   z5AsyncClient.query_df_stream.<locals>._query_df_streamNrO   )r-   r=   r>   r?   r@   rA   rB   rC   rF   ru   rH   rI   rJ   rG   rK   rv   rL   r   rR   rS   r   r{   r   r     s
   ,
zAsyncClient.query_df_streamc                    rc   )ao  
        Query method that returns the results as a stream of DataFrames with PyArrow dtype backend.
        Each DataFrame represents a block from the ClickHouse response.

        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param use_strings: Convert ClickHouse String type to Arrow string type (instead of binary)
        :param external_data: ClickHouse "external data" to send with query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :param dataframe_library: Library to use for DataFrame creation ("pandas" or "polars")
        :return: StreamContext that yields DataFrames (pandas or polars based on dataframe_library parameter)
        c                	      r   r   )r   query_df_arrow_streamr   r   r   r   _query_df_arrow_stream  r   zAAsyncClient.query_df_arrow_stream.<locals>._query_df_arrow_streamNrO   )r-   r=   r>   r?   r~   rK   rL   r   r   rR   rS   r   r   r   r     s
   z!AsyncClient.query_df_arrow_streamF	streaming	as_pandasc                 C   s   | j jdi d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|d|S )a	  
        Creates or updates a reusable QueryContext object
        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param query_formats: See QueryContext __init__ docstring
        :param column_formats: See QueryContext __init__ docstring
        :param encoding: See QueryContext __init__ docstring
        :param use_none: Use None for ClickHouse NULL instead of default values.  Note that using None in Numpy
          arrays will force the numpy array dtype to 'object', which is often inefficient.  This effect also
          will impact the performance of Pandas dataframes.
        :param column_oriented: Deprecated. Controls orientation of the QueryResult result_set property
        :param use_numpy: Return QueryResult columns as one-dimensional numpy arrays
        :param max_str_len: Limit returned ClickHouse String values to this length, which allows a Numpy
          structured array even with ClickHouse variable length String columns.  If 0, Numpy arrays for
          String columns will always be object arrays
        :param context: An existing QueryContext to be updated with any provided parameter values
        :param query_tz  Either a string or a pytz tzinfo object.  (Strings will be converted to tzinfo objects).
          Values for any DateTime or DateTime64 column in the query will be converted to Python datetime.datetime
          objects with the selected timezone
        :param column_tzs A dictionary of column names to tzinfo objects (or strings that will be converted to
          tzinfo objects).  The timezone will be applied to datetime objects returned in the query
        :param use_na_values: Deprecated alias for use_advanced_dtypes
        :param as_pandas Return the result columns as pandas.Series objects
        :param streaming Marker used to correctly configure streaming queries
        :param external_data ClickHouse "external data" to send with query
        :param use_extended_dtypes:  Only relevant to Pandas Dataframe queries.  Use Pandas "missing types", such as
          pandas.NA and pandas.NaT for ClickHouse NULL values, as well as extended Pandas dtypes such as IntegerArray
          and StringArray.  Defaulted to True for query_df methods
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: Reusable QueryContext
        r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   ru   r   r   rK   rv   rL   Nr   )r   create_query_context)r-   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   ru   r   r   rK   rv   rL   r   r   r   r     sB   5	
z AsyncClient.create_query_contextc           
         :    fdd}t  }|j|I dH }	|	S )ae  
        Query method using the ClickHouse Arrow format to return a PyArrow table
        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param use_strings:  Convert ClickHouse String type to Arrow string type (instead of binary)
        :param external_data ClickHouse "external data" to send with query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: PyArrow.Table
        c                         j j dS N)r=   r>   r?   r~   rK   rL   )r   query_arrowr   rK   r>   r=   r-   r?   rL   r~   r   r   _query_arrowD     z-AsyncClient.query_arrow.<locals>._query_arrowNrO   )
r-   r=   r>   r?   r~   rK   rL   r   rR   rS   r   r   r   r   2  
   zAsyncClient.query_arrowc           
         r   )a  
        Query method that returns the results as a stream of Arrow tables
        :param query: Query statement/format string
        :param parameters: Optional dictionary used to format the query
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param use_strings:  Convert ClickHouse String type to Arrow string type (instead of binary)
        :param external_data ClickHouse "external data" to send with query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: Generator that yields a PyArrow.Table for per block representing the result set
        c                      r   r   )r   query_arrow_streamr   r   r   r   _query_arrow_stream_  r   z;AsyncClient.query_arrow_stream.<locals>._query_arrow_streamNrO   )
r-   r=   r>   r?   r~   rK   rL   r   rR   rS   r   r   r   r   M  r   zAsyncClient.query_arrow_streamcmddatac                    rc   )a  
        Client method that returns a single value instead of a result set
        :param cmd: ClickHouse query/command as a python format string
        :param parameters: Optional dictionary of key/values pairs to be formatted
        :param data: Optional 'data' for the command (for INSERT INTO in particular)
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param use_database: Send the database parameter to ClickHouse so the command will be executed in the client
         database context.  Otherwise, no database will be specified with the command.  This is useful for determining
         the default user database
        :param external_data ClickHouse "external data" to send with command/query
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: Decoded response from ClickHouse as either a string, int, or sequence of strings, or QuerySummary
        if no data returned
        c                	      s   j j dS )N)r   r>   r   r?   rb   rK   rL   )r   commandr   r   r   rK   r>   r-   r?   rL   rb   r   r   _command  ri   z%AsyncClient.command.<locals>._commandNrO   )r-   r   r>   r   r?   rb   rK   rL   r   rR   rS   r   r   r   r   h  s
   zAsyncClient.commandc                    s.    fdd}t  }| j|I dH }|S )z
        Validate the connection, does not throw an Exception (see debug logs)
        :return: ClickHouse server is up and reachable
        c                      s
    j  S N)r   pingr   r<   r   r   _ping  s   
zAsyncClient.ping.<locals>._pingNrO   )r-   r   rR   rS   r   r<   r   r     s
   zAsyncClient.ping*tablecolumn_namesdatabasecolumn_typescolumn_type_namesc                    sB    	
fdd}t  }|j|I dH }|S )a  
        Method to insert multiple rows/data matrix of native Python objects.  If context is specified arguments
        other than data are ignored
        :param table: Target table
        :param data: Sequence of sequences of Python data
        :param column_names: Ordered list of column names or '*' if column types should be retrieved from the
            ClickHouse table definition
        :param database: Target database -- will use client default database if not specified.
        :param column_types: ClickHouse column types.  If set then column data does not need to be retrieved from
            the server
        :param column_type_names: ClickHouse column type names.  If set then column data does not need to be
            retrieved from the server
        :param column_oriented: If true the data is already "pivoted" in column form
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param context: Optional reusable insert context to allow repeated inserts into the same table with
            different data batches
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: QuerySummary with summary information, throws exception if insert fails
        c                      s    j j	 
d
S )N)
r   r   r   r   r   r   rD   r?   rG   rL   )r   insertr   r   rD   r   r   rG   r   r   r-   r?   r   rL   r   r   _insert  s
   z#AsyncClient.insert.<locals>._insertNrO   )r-   r   r   r   r   r   r   rD   r?   rG   rL   r   rR   rS   r   r   r   r     s
    zAsyncClient.insertc
              
      @    	f
dd}
t  }|j|
I dH }|S )aX  
        Insert a pandas DataFrame into ClickHouse.  If context is specified arguments other than df are ignored
        :param table: ClickHouse table
        :param df: two-dimensional pandas dataframe
        :param database: Optional ClickHouse database
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param column_names: An optional list of ClickHouse column names.  If not set, the DataFrame column names
           will be used
        :param column_types: ClickHouse column types.  If set then column data does not need to be retrieved from
            the server
        :param column_type_names: ClickHouse column type names.  If set then column data does not need to be
            retrieved from the server
        :param context: Optional reusable insert context to allow repeated inserts into the same table with
            different data batches
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: QuerySummary with summary information, throws exception if insert fails
        c                      s   j j 	d	S )N)	r   dfr   r?   r   r   r   rG   rL   )r   	insert_dfr   
r   r   r   rG   r   r   r-   r?   r   rL   r   r   
_insert_df  s
   z)AsyncClient.insert_df.<locals>._insert_dfNrO   )r-   r   r   r   r?   r   r   r   rG   rL   r   rR   rS   r   r   r   r     
   zAsyncClient.insert_dfc           	         8    fdd}t  }|j|I dH }|S )a   
        Insert a PyArrow table DataFrame into ClickHouse using raw Arrow format
        :param table: ClickHouse table
        :param arrow_table: PyArrow Table object
        :param database: Optional ClickHouse database
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: QuerySummary with summary information, throws exception if insert fails
        c                      s   j j dS )N)r   arrow_tabler   r?   rL   )r   insert_arrowr   r   r   r-   r?   r   rL   r   r   _insert_arrow  s   z/AsyncClient.insert_arrow.<locals>._insert_arrowNrO   )	r-   r   r   r   r?   rL   r   rR   rS   r   r   r   r     s
   zAsyncClient.insert_arrowr   c           	         r   )a  
        Insert a pandas DataFrame with PyArrow backend or a polars DataFrame into ClickHouse using Arrow format.
        This method is optimized for DataFrames that already use Arrow format, providing
        better performance than the standard insert_df method.
        
        Validation is performed and an exception will be raised if this requirement is not met.
        Polars DataFrames are natively Arrow-based and don't require additional validation.
        
        :param table: ClickHouse table name
        :param df: Pandas DataFrame with PyArrow dtype backend or Polars DataFrame
        :param database: Optional ClickHouse database name
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: QuerySummary with summary information, throws exception if insert fails
        c                      s   j j dS )N)r   r   r   r?   rL   )r   insert_df_arrowr   r   r   r-   r?   r   rL   r   r   _insert_df_arrow  s   z5AsyncClient.insert_df_arrow.<locals>._insert_df_arrowNrO   )	r-   r   r   r   r?   rL   r   rR   rS   r   r   r   r     s
   	zAsyncClient.insert_df_arrowc
              
      r   )a  
        Builds a reusable insert context to hold state for a duration of an insert
        :param table: Target table
        :param database: Target database.  If not set, uses the client default database
        :param column_names: Optional ordered list of column names.  If not set, all columns ('*') will be assumed
          in the order specified by the table definition
        :param database: Target database -- will use client default database if not specified
        :param column_types: ClickHouse column types.  Optional  Sequence of ClickHouseType objects.  If neither column
           types nor column type names are set, actual column types will be retrieved from the server.
        :param column_type_names: ClickHouse column type names.  Specified column types by name string
        :param column_oriented: If true the data is already "pivoted" in column form
        :param settings: Optional dictionary of ClickHouse settings (key/string values)
        :param data: Initial dataset for insert
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :return: Reusable insert context
        c                      s   j j 	d	S )N)	r   r   r   r   r   rD   r?   r   rL   )r   create_insert_contextr   
r   rD   r   r   r   r   r-   r?   r   rL   r   r   _create_insert_context9  s
   zAAsyncClient.create_insert_context.<locals>._create_insert_contextNrO   )r-   r   r   r   r   r   rD   r?   r   rL   r   rR   rS   r   r   r   r     r   z!AsyncClient.create_insert_contextc                    s0    fdd}t  }|j|I dH }|S )z
        Subclass implementation of the data insert
        :context: InsertContext parameter object
        :return: No return, throws an exception if the insert fails
        c                      s   j j dS )N)rG   )r   data_insertr   rG   r-   r   r   _data_insertJ  s   z-AsyncClient.data_insert.<locals>._data_insertNrO   )r-   rG   r   rR   rS   r   r   r   r   C  s
   zAsyncClient.data_insertinsert_blockcompressionc                    rc   )ar  
        Insert data already formatted in a bytes object
        :param table: Table name (whether qualified with the database name or not)
        :param column_names: Sequence of column names
        :param insert_block: Binary or string data already in a recognized ClickHouse format
        :param settings:  Optional dictionary of ClickHouse settings (key/string values)
        :param compression:  Recognized ClickHouse `Accept-Encoding` header compression value
        :param transport_settings: Optional dictionary of transport level settings (HTTP headers, etc.)
        :param fmt: Valid clickhouse format
        c                	      s   j j dS )N)r   r   r   r?   ra   r   rL   )r   
raw_insertr   r   r   ra   r   r-   r?   r   rL   r   r   _raw_insertc  s   z+AsyncClient.raw_insert.<locals>._raw_insertNrO   )r-   r   r   r   r?   ra   r   rL   r   rR   rS   r   r   r   r   Q  s
   zAsyncClient.raw_insertc                    s   | S r   r   r<   r   r   r   
__aenter__l  s   zAsyncClient.__aenter__c                    s   |   I d H  d S r   )r8   )r-   exc_typeexc_valexc_tbr   r   r   	__aexit__o  s   zAsyncClient.__aexit__)NNNNNNNNNNNNNNNN)NNNNNNNNNNNNN)NNNTNN)NNNNNNNNNNN)NNNNNr}   )NNNNNNNNFr   NNNNFFNNN)NNNNN)
NNr   NNNFNNN)	NNNNNNNNN)NNN)NNNNFNNN)NNNNNN)r2   r   )r2   N)>r   r   r   __doc__r)   r   intr   r   r   r.   r1   r   strr3   r5   boolr7   r8   r   r   r   r   r   r   r   r=   r   rW   r\   r_   bytesrf   ioIOBaserj   ro   rs   rz   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      s   



	

$	

"	

!	

"

	

	

	

'	
)	

(	
(	

C



 
	


)

&

'		
%


r   )(r9   r   loggingr'   concurrent.futures.threadr   datetimer   typingr   r   r   r   r   r	   r
   r    clickhouse_connect.driver.clientr    clickhouse_connect.driver.commonr   $clickhouse_connect.driver.httpclientr   "clickhouse_connect.driver.externalr   clickhouse_connect.driver.queryr   r   !clickhouse_connect.driver.summaryr   !clickhouse_connect.datatypes.baser    clickhouse_connect.driver.insertr   	getLoggerr   r+   r   r)   r   r   r   r   r   <module>   s&    (
