
    %e0                        d dl mZ d dlmZ d dlmZmZ d dlZd dl	m
Z
 d dlmZ d dlmZ d dlmZ erd d	lmZ d d
lmZ d dlmZ  G d de
d                   ZdS )    )annotations)	timedelta)TYPE_CHECKINGcastN)BaseConnection)running_in_sis)StreamlitAPIException)
cache_data)SnowflakeConnection)SnowflakeCursorSessionc                  d    e Zd ZdZddZddddddZ	 	 	 d d!dZd"dZedd            Z	d#dZ
dS )$r   a  A connection to Snowflake using the Snowflake Python Connector. Initialize using
    ``st.connection("<name>", type="snowflake")``.

    SnowflakeConnection supports direct SQL querying using ``.query("...")``, access to
    the underlying Snowflake Python Connector object with ``.raw_connection``, and other
    convenience functions. See the methods below for more information.
    SnowflakeConnections should always be created using ``st.connection()``, **not**
    initialized directly.
    return'InternalSnowflakeConnection'c                   dd l }ddl m} ddlm} t	                      r- |            }t          |d          r|j        S |j        j        S d|j        _	        	 | j
                                        }t          |          ri ||} |j        j        di |S t          |j        j        d          r_|j        j        j        }d}		 |d         }	n# |j        j        j        $ r Y nw xY w| j        d	k    r|	n| j        }
 |j        j        dd
|
i|S  |j        j        di |S # |$ r4}t          |          st          |          st%          d          |d }~ww xY w)Nr   )Errorget_active_session
connectionqmarkCONFIG_MANAGERdefaultdefault_connection_name	snowflakeconnection_namea?  Missing Snowflake connection configuration. Did you forget to set this in `secrets.toml`, a Snowflake configuration file, or as kwargs to `st.connection`? See the [SnowflakeConnection configuration documentation](https://docs.streamlit.io/st.connections.snowflakeconnection-configuration) for more details and examples. )snowflake.connectorr   snowflake.snowpark.contextr   r   hasattrr   _conn	connector
paramstyle_secretsto_dictlenconnectr   errorsConfigSourceError_connection_namer	   )selfkwargsr   SnowflakeErrorr   session
st_secretsconn_kwargs
config_mgrr   r   es               Jlib/python3.11/site-packages/streamlit/connections/snowflake_connection.py_connectzSnowflakeConnection._connect4   s   """"??????AAAAAA  	'((**Gw-- *)) =&& *1	&(	..00J: B66v62y*2AA[AAA y*57GHH &0;J
*3'.89R.S++ *1C    D	 ,;; ,+.  
 3y*2  $3  
 /9&.88888 		 		 		z?? 3v;; +5   G		sH   ?D$ -D$ C D$ C'$D$ &C''*D$ D$ $E)/EENzRunning `snowflake.query(...)`.)ttlshow_spinnerparamssqlstrr5   float | int | timedelta | Noner6   
bool | strpd.DataFramec          	         ddl m ddlm}m}m}m}	m}
m} ddl	m
}m}m}m} d |||
||	|fD              | fd |d          d |fd	           |d
                    d fd            }t          |                              dd          }|j         d j         d| |_         t%          ||          |          } ||          S )a  Run a read-only SQL query.

        This method implements both query result caching (with caching behavior
        identical to that of using ``@st.cache_data``) as well as simple error handling/retries.

        .. note::
            Queries that are run without a specified ttl are cached indefinitely.

        Parameters
        ----------
        sql : str
            The read-only SQL query to execute.
        ttl : float, int, timedelta or None
            The maximum number of seconds to keep results in the cache, or
            None if cached results should not expire. The default is None.
        show_spinner : boolean or string
            Enable the spinner. The default is to show a spinner when there is a
            "cache miss" and the cached resource is being created. If a string, the value
            of the show_spinner param will be used for the spinner text.
        params : list, tuple, dict or None
            List of parameters to pass to the execute method. This connector supports
            binding data to a SQL statement using qmark bindings. For more information
            and examples, see the `Snowflake Python Connector documentation
            <https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example#using-qmark-or-numeric-binding>`_.
            Default is None.

        Returns
        -------
        pandas.DataFrame
            The result of running the query, formatted as a pandas DataFrame.

        Example
        -------
        >>> import streamlit as st
        >>>
        >>> conn = st.connection("snowflake")
        >>> df = conn.query("select * from pet_owners")
        >>> st.dataframe(df)
        r   )ProgrammingError)BAD_REQUEST_GS_CODEID_TOKEN_EXPIRED_GS_CODEMASTER_TOKEN_EXPIRED_GS_CODEMASTER_TOKEN_INVALD_GS_CODEMASTER_TOKEN_NOTFOUND_GS_CODESESSION_EXPIRED_GS_CODE)retryretry_if_exceptionstop_after_attempt
wait_fixedc                ,    h | ]}t          |          S r   )int).0codes     r3   	<setcomp>z,SnowflakeConnection.query.<locals>.<setcomp>   s.     
!
 
!
 
!
 II
!
 
!
 
!
    c                ,                                     S )N)reset)_r+   s    r3   <lambda>z+SnowflakeConnection.query.<locals>.<lambda>   s    DJJLL rN      Tc                V    t          |           ot          | d          o| j        v S )Nerrno)
isinstancer    rU   )r2   r>   retryable_error_codess    r3   rR   z+SnowflakeConnection.query.<locals>.<lambda>   s7    *Q(899 5Aw''5G44 rN      )afterstopreraiserE   waitr8   r9   r   r<   c                ~    j                                         } |j        | fdi |                                S )Nr7   )	_instancecursorexecutefetch_pandas_all)r8   curr,   r7   r+   s     r3   _queryz)SnowflakeConnection.query.<locals>._query   sI     .''))CCK55F5f555'')))rN   .rQ   )r6   r5   )r8   r9   r   r<   )snowflake.connector.errorsr>   snowflake.connector.networkr?   r@   rA   rB   rC   rD   tenacityrE   rF   rG   rH   r9   replace__qualname__r*   r
   )r+   r8   r5   r6   r7   r,   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rc   ttl_strr>   rW   s   `   ``            @@r3   queryzSnowflakeConnection.queryu   s   ` 	@?????	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	WVVVVVVVVVVV
!
 
!
 )'-,+#
!
 
!
 
!
 
((((##A&& %$5 5 5 5 5 
 A

 

 

	* 	* 	* 	* 	* 	* 	*

 

	* 
 

'#s

 	 "(!4XXt7LXXwXX
%
 
 
  
 vc{{rN   df
table_namedatabase
str | Noneschema
chunk_size
int | Nonetuple[bool, int, int]c           
     J    ddl m}  |d| j        |||||d|\  }}	}
}||	|
fS )a  Call snowflake.connector.pandas_tools.write_pandas with this connection.

        This convenience method is simply a thin wrapper around the ``write_pandas``
        function of the same name from ``snowflake.connector.pandas_tools``. For more
        information, see the `Snowflake Python Connector documentation
        <https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api#write_pandas>`_.

        Returns
        -------
        tuple[bool, int, int]
            A tuple containing three values:
                1. A bool that is True if the write was successful.
                2. An int giving the number of chunks of data that were copied.
                3. An int giving the number of rows that were inserted.
        r   )write_pandas)connrl   rm   rn   rp   rq   r   ) snowflake.connector.pandas_toolsru   r^   )r+   rl   rm   rn   rp   rq   r,   ru   successnchunksnrowsrQ   s               r3   ru   z SnowflakeConnection.write_pandas   sh    0 	BAAAAA%1\ &
!!&
 &
 &
 &
"% %((rN   'SnowflakeCursor'c                4    | j                                         S )zReturn a PEP 249-compliant cursor object.

        For more information, see the `Snowflake Python Connector documentation
        <https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-api#object-cursor>`_.
        )r^   r_   r+   s    r3   r_   zSnowflakeConnection.cursor  s     ~$$&&&rN   c                    | j         S )a&  Access the underlying Snowflake Python connector object.

        Information on how to use the Snowflake Python Connector can be found in the
        `Snowflake Python Connector documentation <https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example>`_.
        )r^   r}   s    r3   raw_connectionz"SnowflakeConnection.raw_connection  s     ~rN   	'Session'c                    ddl m} ddlm} t	                      r
 |            S t          ||j                            d| j        i          	                                          S )a   Create a new Snowpark Session from this connection.

        Information on how to use Snowpark sessions can be found in the `Snowpark documentation
        <https://docs.snowflake.com/en/developer-guide/snowpark/python/working-with-dataframes>`_.
        r   r   r   r   )
r   r   snowflake.snowpark.sessionr   r   r   builderconfigsr^   create)r+   r   r   s      r3   r.   zSnowflakeConnection.session  s     	BAAAAA666666 	(%%'''W_,,lDN-KLLSSUU
 
 	
rN   )r   r   )r8   r9   r5   r:   r6   r;   r   r<   )NNN)rl   r<   rm   r9   rn   ro   rp   ro   rq   rr   r   rs   )r   r{   )r   r   )__name__
__module__ri   __doc__r4   rk   ru   r_   propertyr   r.   r   rN   r3   r   r   )   s         ? ? ? ?J /3#Dg g g g g gZ  $!!%$) $) $) $) $)L' ' ' '    X
 
 
 
 
 
rN   r   InternalSnowflakeConnection)
__future__r   datetimer   typingr   r   pandaspdstreamlit.connectionsr   streamlit.connections.utilr   streamlit.errorsr	   streamlit.runtime.cachingr
   r   r   r   snowflake.connector.cursorr   r   r   r   rN   r3   <module>r      s'  * # " " " " "       & & & & & & & &     0 0 0 0 0 0 5 5 5 5 5 5 2 2 2 2 2 2 0 0 0 0 0 0 3      ;:::::222222z
 z
 z
 z
 z
.)FG z
 z
 z
 z
 z
rN   