
    q-Phc                       d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	 d dl
mZ d dlmZ d dlmZmZmZmZ er8d 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 d dlmZmZ d dl m!Z! d dl"m#Z#  ej$        e%          5  d dl&m'Z'  e'j(        eeee           ddd           n# 1 swxY w Y    G d d          Z) G d d          Z*ddZ+dS )    )annotationsN)TYPE_CHECKINGAnyLiteral)issue_unstable_warning)wrap_ldf)CatalogInfo
ColumnInfoNamespaceInfo	TableInfo)	Generator)datetime)
SchemaDict)DataSourceFormat	TableType)	DataFrame)CredentialProviderFunction CredentialProviderFunctionReturnCredentialProviderBuilder)	LazyFrame)PyCatalogClient)catalog_info_clsnamespace_info_clstable_info_clscolumn_info_clsc                      e Zd ZdZddddQdZdRdZdSdZdTdZdUdZdVdZ	dddddddWd*Z
d+ddddd,dXd5Zddd6dYd:Zd;d<dZd>Zddd6d[d@Zd;d<d\dAZdddddBd]dJZd^dKZd_dOZed`dP            ZdS )aCatalogz
    Unity catalog client.

    .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.
    autoT)bearer_tokenrequire_httpsworkspace_urlstrr    
str | Noner!   boolreturnNonec                  t          d           |r*|                    d          sd| d}t          |          |dk    sk|dk    rydt          j        v rk|                    d          rV|                    d                              dd	          d
                             d          r|                                 }|dk    rd}t          j
        ||          | _        dS )a  
        Initialize a catalog client.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        workspace_url
            URL of the workspace, or alternatively the URL of the Unity catalog
            API endpoint.
        bearer_token
            Bearer token to authenticate with. This can also be set to:

            * "auto": Automatically retrieve bearer tokens from the environment.
            * "databricks-sdk": Use the Databricks SDK to retrieve and use the
              bearer token from the environment.
        require_https
            Require the `workspace_url` to use HTTPS.
        z/`Catalog` functionality is considered unstable.zhttps://z%a non-HTTPS workspace_url was given (z5). To allow non-HTTPS URLs, pass require_https=False.zdatabricks-sdkr   DATABRICKS_RUNTIME_VERSION/   r   z.cloud.databricks.comN)r   
startswith
ValueErrorosenvironremoveprefixsplitendswith_get_databricks_tokenr   new_client)selfr"   r    r!   msgs        [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/polars/catalog/unity/client.py__init__zCatalog.__init__6   s   8 	PQQQ 	"!9!9*!E!E 	"B B B B  S//!+++F"" -
::((44 ; **:66sAq"122 ;  5577L6!!L&*=,GG    list[CatalogInfo]c                4    | j                                         S )z
        List the available catalogs.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.
        )r5   list_catalogs)r6   s    r8   r=   zCatalog.list_catalogso   s     |))+++r:   catalog_namelist[NamespaceInfo]c                6    | j                             |          S )ac  
        List the available namespaces (unity schema) under the specified catalog.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        )r5   list_namespaces)r6   r>   s     r8   rA   zCatalog.list_namespacesy   s     |++L999r:   	namespacelist[TableInfo]c                8    | j                             ||          S )a  
        List the available tables under the specified schema.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        )r5   list_tables)r6   r>   rB   s      r8   rE   zCatalog.list_tables   s     |''i@@@r:   
table_namer   c                :    | j                             |||          S )a  
        Retrieve the metadata of the specified table.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        table_name
            Name of the table.
        )r5   get_table_infor6   r>   rB   rF   s       r8   rH   zCatalog.get_table_info   s    & |**<JOOOr:   table_idwrite1tuple[dict[str, str] | None, dict[str, str], int]c               :    | j                             ||          S )N)rJ   rK   )r5   get_table_credentials)r6   rJ   rK   s      r8   _get_table_credentialszCatalog._get_table_credentials   s     |11851QQQr:   N   )delta_table_versiondelta_table_optionsstorage_optionscredential_providerretriesrQ   int | str | datetime | NonerR   dict[str, Any] | NonerS   rT   3CredentialProviderFunction | Literal['auto'] | NonerU   intr   c          
        |                      |||          }	t          |	d          \  }
}|                     |||	dd          \  }}|dv rddlm}  ||
||||          S |d
| }t          |          |d| }t          |          |r"t          |                                          }nd	}t          | j	        
                    ||||||                    S )a  
        Retrieve the metadata of the specified table.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        table_name
            Name of the table.
        delta_table_version
            Version of the table to scan (Deltalake only).
        delta_table_options
            Additional keyword arguments while reading a Deltalake table.
        storage_options
            Options that indicate how to connect to a cloud provider.

            The cloud providers currently supported are AWS, GCP, and Azure.
            See supported keys here:

            * `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
            * `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
            * `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
            * Hugging Face (`hf://`): Accepts an API key under the `token` parameter:             `{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.

            If `storage_options` is not provided, Polars will try to infer the
            information from environment variables.
        credential_provider
            Provide a function that can be called to provide cloud storage
            credentials. The function is expected to return a dictionary of
            credential keys along with an optional credential expiry time.

            .. warning::
                This functionality is considered **unstable**. It may be changed
                at any point without it being considered a breaking change.
        retries
            Number of retries if accessing a cloud instance fails.

        
scan tableFzCatalog.scan_tablerK   caller_nameDELTADELTASHARINGr   )
scan_delta)versionrR   rS   rT   Nz3cannot apply delta_table_version for table of type z3cannot apply delta_table_options for table of type )rT   cloud_optionsrU   )rH   !_extract_location_and_data_format_init_credentialspolars.io.deltara   r-   listitemsr   r5   
scan_table)r6   r>   rB   rF   rQ   rR   rS   rT   rU   
table_infostorage_locationdata_source_formatra   r7   s                 r8   ri   zCatalog.scan_table   sq   v ((y*MM
/P0
 0
,, 04/E/E, 0F 0
 0
,_ !:::222222: +$7 /$7    *(%( (  S//!*(%( (  S//! 	#"?#8#8#:#:;;OO #OL##$7- $  	
 	
 		
r:   error)
delta_modedelta_write_optionsdelta_merge_optionsrS   rT   dfr   rn   :Literal['error', 'append', 'overwrite', 'ignore', 'merge']ro   rp   dict[str, str] | None"None | deltalake.table.TableMergerc          	     
   |                      |||          }
t          |
d          \  }}|                     |	||
dd          \  }	}|dv r|                    |||	|||          S d| d| d| d	| d
	}t	          |          )a  
        Write a DataFrame to a catalog table.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        df
            DataFrame to write.
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        table_name
            Name of the table.
        delta_mode : {'error', 'append', 'overwrite', 'ignore', 'merge'}
            (For delta tables) How to handle existing data.

            - If 'error', throw an error if the table already exists (default).
            - If 'append', will add new data.
            - If 'overwrite', will replace table with new data.
            - If 'ignore', will not write anything if table already exists.
            - If 'merge', return a `TableMerger` object to merge data from the DataFrame
              with the existing data.
        delta_write_options
            (For delta tables) Additional keyword arguments while writing a
            Delta lake Table.
            See a list of supported write options `here <https://delta-io.github.io/delta-rs/api/delta_writer/#deltalake.write_deltalake>`__.
        delta_merge_options
            (For delta tables) Keyword arguments which are required to `MERGE` a
            Delta lake Table.
            See a list of supported merge options `here <https://delta-io.github.io/delta-rs/api/delta_table/#deltalake.DeltaTable.merge>`__.
        storage_options
            Options that indicate how to connect to a cloud provider.

            The cloud providers currently supported are AWS, GCP, and Azure.
            See supported keys here:

            * `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
            * `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
            * `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
            * Hugging Face (`hf://`): Accepts an API key under the `token` parameter:             `{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.

            If `storage_options` is not provided, Polars will try to infer the
            information from environment variables.
        credential_provider
            Provide a function that can be called to provide cloud storage
            credentials. The function is expected to return a dictionary of
            credential keys along with an optional credential expiry time.

            .. warning::
                This functionality is considered **unstable**. It may be changed
                at any point without it being considered a breaking change.
        r[   TzCatalog.write_tabler\   r^   )rS   rT   modero   rp   zwrite_table: table format of .z (z) is unsupported.)rH   rd   re   write_deltaNotImplementedError)r6   rq   r>   rB   rF   rn   ro   rp   rS   rT   rj   rk   rl   r7   s                 r8   write_tablezCatalog.write_table%  s    T ((y*MM
/P0
 0
,, 04/E/E- 0F 0
 0
,_ !:::>>  /$7$7$7 "   :: :"+: :.8: :&: : : 
 &c***r:   )commentstorage_rootr{   r|   r	   c               <    | j                             |||          S )a  
        Create a catalog.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        comment
            Leaves a comment about the catalog.
        storage_root
            Base location at which to store the catalog.
        )r>   r{   r|   )r5   create_catalog)r6   r>   r{   r|   s       r8   r~   zCatalog.create_catalog  s*    . |**%w\ + 
 
 	
r:   F)forcer   c               >    | j                             ||           dS )a_  
        Delete a catalog.

        Note that depending on the table type and catalog server, this may not
        delete the actual data files from storage. For more details, please
        consult the documentation of the catalog provider you are using.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        force
            Forcibly delete the catalog even if it is not empty.
        )r>   r   N)r5   delete_catalog)r6   r>   r   s      r8   r   zCatalog.delete_catalog  s%    0 	##U#KKKKKr:   r   c               >    | j                             ||||          S )a  
        Create a namespace (unity schema) in the catalog.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        comment
            Leaves a comment about the table.
        storage_root
            Base location at which to store the namespace.
        )r>   rB   r{   r|   )r5   create_namespace)r6   r>   rB   r{   r|   s        r8   r   zCatalog.create_namespace  s/    4 |,,%%	 - 
 
 	
r:   c               @    | j                             |||           dS )a  
        Delete a namespace (unity schema) in the catalog.

        Note that depending on the table type and catalog server, this may not
        delete the actual data files from storage. For more details, please
        consult the documentation of the catalog provider you are using.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        force
            Forcibly delete the namespace even if it is not empty.
        )r>   rB   r   N)r5   delete_namespace)r6   r>   rB   r   s       r8   r   zCatalog.delete_namespace  s4    6 	%%%% 	& 	
 	
 	
 	
 	
r:   )rl   r{   r|   
propertiesschemaSchemaDict | None
table_typer   rl   DataSourceFormat | Noner   c                   | j                             ||||||||t          |	pi                                           	  	        S )a  
        Create a table in the catalog.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        table_name
            Name of the table.
        schema
            Schema of the table.
        table_type
            Type of the table
        data_source_format
            Storage format of the table.
        comment
            Leaves a comment about the table.
        storage_root
            Base location at which to store the table.
        properties
            Extra key-value metadata to store.
        )	r>   rB   rF   r   r   rl   r{   r|   r   )r5   create_tablerg   rh   )
r6   r>   rB   rF   r   r   rl   r{   r|   r   s
             r8   r   zCatalog.create_table  sX    R |((%!!1%Z-2446677 ) 

 

 
	
r:   c                @    | j                             |||           dS )a%  
        Delete the table stored at this location.

        Note that depending on the table type and catalog server, this may not
        delete the actual data files from storage. For more details, please
        consult the documentation of the catalog provider you are using.

        If you would like to perform manual deletions, the storage location of
        the files can be found using `get_table_info`.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.

        Parameters
        ----------
        catalog_name
            Name of the catalog.
        namespace
            Name of the namespace (unity schema).
        table_name
            Name of the table.
        )r>   rB   rF   N)r5   delete_tablerI   s       r8   r   zCatalog.delete_table8  s6    : 	!!%! 	" 	
 	
 	
 	
 	
r:   rj   r]   >tuple[CredentialProviderBuilder | None, dict[str, Any] | None]c          
     t   ddl m} |dk    r|r |j        |          |fS d |fS t          j        d          dk    }t          | |j        |          }	 |                                }	t          |	          }
|
ri |pi |
}|	D ]}	 |r2|j	        }|j        }d|d|d	}t          |t          j        
            |j        |          |fS # t          $ rD}|r8|j	        }|j        }d|d|d|d|d		}t          |t          j        
           Y d }~nd }~ww xY wddl m}  |d|j        ||          |fS )Nr   r   r   POLARS_VERBOSE1rK   z9auto-selected CatalogCredentialProvider for table_name = z (table_id = ))filez3error auto-initializing CatalogCredentialProvider: z table_name = z) (write = )!_init_credential_provider_builder),polars.io.cloud.credential_provider._builderr   from_initialized_providerr.   getenvCatalogCredentialProviderrJ   _credentials_iternextnameprintsysstderr	Exceptionr   rk   )r6   rT   rS   rj   rK   r]   r   verbosecatalog_credential_providervstorage_update_options_rF   rJ   r7   er   s                    r8   re   zCatalog._init_credentials[  sU   	
 	
 	
 	
 	
 	
 &((" -J0J' "# # _,,),--4&?*%U'
 '
 '
#	+==??A%)!WW"% X"Wo&;"W@V"W    ,'_
%.7!7 7(07 7 7  c
++++F,F+  '  	, 	, 	, ,'_
%.D! D D!D D(0D D8=D D D  c
++++	,6	
 	
 	
 	
 	
 	
 10J/+
 
 	s   2C 
D:DDc                   t           j                            d          d}t          |          t          j        d          j        }   |d                      |d                                           d         dd          S )Nzdatabricks.sdkz?could not get Databricks token: databricks-sdk is not installedzdatabricks.sdk.coreDefaultCredentialsConfigAuthorization   )	importlibutil	find_specImportErrorimport_module__dict__)clsr7   ms      r8   r3   zCatalog._get_databricks_token  s    >##$455=SCc""" #$9::C7(&q%&((87799/J122NNr:   )r"   r#   r    r$   r!   r%   r&   r'   )r&   r;   )r>   r#   r&   r?   )r>   r#   rB   r#   r&   rC   )r>   r#   rB   r#   rF   r#   r&   r   )rJ   r#   rK   r%   r&   rL   )r>   r#   rB   r#   rF   r#   rQ   rV   rR   rW   rS   rW   rT   rX   rU   rY   r&   r   )rq   r   r>   r#   rB   r#   rF   r#   rn   rr   ro   rW   rp   rW   rS   rs   rT   rX   r&   rt   )r>   r#   r{   r$   r|   r$   r&   r	   )r>   r#   r   r%   r&   r'   )
r>   r#   rB   r#   r{   r$   r|   r$   r&   r   )r>   r#   rB   r#   r   r%   r&   r'   )r>   r#   rB   r#   rF   r#   r   r   r   r   rl   r   r{   r$   r|   r$   r   rs   r&   r   )r>   r#   rB   r#   rF   r#   r&   r'   )rT   rX   rS   rW   rj   r   rK   r%   r]   r#   r&   r   )r&   r#   )__name__
__module____qualname____doc__r9   r=   rA   rE   rH   rO   ri   rz   r~   r   r   r   r   r   re   classmethodr3    r:   r8   r   r   -   sG         $*"7H 7H 7H 7H 7H 7Hr, , , ,: : : :A A A A"P P P P*R R R R <@5915 p
 p
 p
 p
 p
 p
v 595915 g+ g+ g+ g+ g+ g+Z ##'
 
 
 
 
 
> 	L L L L L L> ##'
 
 
 
 
 
L 
 
 
 
 
 
N 7;"#',03
 3
 3
 3
 3
 3
j!
 !
 !
 !
FI I I IV O O O [O O Or:   r   c                  *    e Zd ZdZdd
ZddZddZdS )r   zGRetrieves credentials from the Unity catalog temporary credentials API.catalogr   rJ   r#   rK   r%   r&   r'   c               0    || _         || _        || _        d S N)r   rJ   rK   )r6   r   rJ   rK   s       r8   r9   z"CatalogCredentialProvider.__init__  s     


r:   r   c                >    |                                  \  }\  }}||fS r   )r   )r6   r   credsexpirys       r8   __call__z"CatalogCredentialProvider.__call__  s&    !3355?E6f}r:   Generator[Any]c              #     K   | j                             | j        | j                  \  }}}|V  |s| j        }d|}t	          |          ||fV  d S )Nr   zJdid not receive credentials from temporary credentials API for table_id = )r   rO   rJ   rK   r   )r6   r   r   r   rJ   r7   s         r8   r   z+CatalogCredentialProvider._credentials_iter  s       150S0SM 1T 1
 1
-%v %$$$ 	!}H!! !  C.. Vmr:   N)r   r   rJ   r#   rK   r%   r&   r'   )r&   r   )r&   r   )r   r   r   r   r9   r   r   r   r:   r8   r   r     sV        QQ   
        r:   r   rj   r   	operationr#   r&   tuple[str, DataSourceFormat]c                    | j         d| d}t          |          | j        d| d}t          |          | j         | j        fS )Nzcannot z: no storage_location foundz: no data_source_format found)rk   r-   rl   )rj   r   r7   s      r8   rd   rd     s_     "*>	>>>oo$,@	@@@oo&
(EEEr:   )rj   r   r   r#   r&   r   ),
__future__r   
contextlibr   r.   r   typingr   r   r   polars._utils.unstabler   polars._utils.wrapr   polars.catalog.unity.modelsr	   r
   r   r   collections.abcr   r   	deltalakepolars._typingr   r   r   polars.dataframe.framer   polars.io.cloudr   r   r   r   polars.lazyframer   suppressr   polars.polarsr   init_classesr   r   rd   r   r:   r8   <module>r      s   " " " " " "         				 



 . . . . . . . . . . 9 9 9 9 9 9 ' ' ' ' ' '             +))))))!!!!!!))))))GGGGGGGG000000        WVVVVV******Z%%  ------ O $( "	                 B
O B
O B
O B
O B
O B
O B
O B
OJ       @F F F F F Fs   B**B.1B.