a
    bg+                     @  s   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZmZmZ ddlZddlZddlmZmZ ddlmZmZmZmZ ddlmZ eeZedd	Zerdd
lmZ G dd deZ dddddddZ!dddddZ"dS )z#Wrapper around a Power BI endpoint.    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalUnion)ClientTimeoutServerTimeoutError)	BaseModel
ConfigDictFieldmodel_validator)TimeoutZPOWERBI_BASE_URLz"https://api.powerbi.com/v1.0/myorg)TokenCredentialc                   @  s  e Zd ZU dZded< ded< dZded< dZd	ed
< dZded< dZded< e	ddddZ
ded< e	edZded< dZded< eddZeddeddddd Zedd!d"d#Zedd!d$d%Zd&d!d'd(Zdd!d)d*Zedd!d+d,ZdId-d.d/d0d1Zddd2d3d4Zddd/d5d6ZdJd-dd/d7d8ZdKd-dd/d9d:Zdd;d<d=d>Zdd;d<d?d@ZddAdBdCdDZ dddBdEdFZ!dddBdGdHZ"dS )LPowerBIDatasetaO  Create PowerBI engine from dataset ID and credential or token.

    Use either the credential or a supplied token to authenticate.
    If both are supplied the credential is used to generate a token.
    The impersonated_user_name is the UPN of a user to be impersonated.
    If the model is not RLS enabled, this will be ignored.
    str
dataset_idz	List[str]table_namesNOptional[str]group_idzOptional[TokenCredential]
credentialtokenimpersonated_user_name   r   
   )defaultgtleintsample_rows_in_table_info)default_factoryzDict[str, str]schemaszOptional[aiohttp.ClientSession]
aiosessionT)Zarbitrary_types_allowedbefore)modezDict[str, Any]r   )valuesreturnc                 C  s>   | dg }dd |D |d< d|v s.d|v r2|S tddS )z?Validate that at least one of token and credentials is present.r   c                 S  s   g | ]}t |qS  fix_table_name.0tabler)   r)   s/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/utilities/powerbi.py
<listcomp>9       z2PowerBIDataset.validate_params.<locals>.<listcomp>r   r   z.Please provide either a credential or a token.N)get
ValueError)clsr'   r   r)   r)   r/   validate_params4   s
    zPowerBIDataset.validate_params)r(   c                 C  s2   | j r t d| j  d| j dS t d| j dS )zGet the request url.z/groups/z
/datasets/z/executeQueries)r   BASE_URLr   selfr)   r)   r/   request_url>   s    zPowerBIDataset.request_urlc              
   C  s   | j rdd| j  dS ddlm} | jrvz| jdj }dd| dW S  tyt } z|d|W Y d}~n
d}~0 0 |d	dS )
zGet the token.zapplication/jsonzBearer )zContent-TypeAuthorizationr   )ClientAuthenticationErrorz1https://analysis.windows.net/powerbi/api/.defaultz4Could not get a token from the supplied credentials.Nz No credential or token supplied.)r   Zazure.core.exceptionsr;   r   	get_token	Exception)r8   r;   r   excr)   r)   r/   headersE   s(    zPowerBIDataset.headerszIterable[str]c                 C  s   | j S )zGet names of tables available.r   r7   r)   r)   r/   get_table_names`   s    zPowerBIDataset.get_table_namesc                 C  s$   | j r ddd | j  D S dS )zGet the available schema's., c                 S  s   g | ]\}}| d | qS )z: r)   )r-   keyvaluer)   r)   r/   r0   g   r1   z.PowerBIDataset.get_schemas.<locals>.<listcomp>z9No known schema's yet. Use the schema_powerbi tool first.)r#   joinitemsr7   r)   r)   r/   get_schemasd   s    zPowerBIDataset.get_schemasc                 C  s   |   S )z-Information about all tables in the database.)get_table_infor7   r)   r)   r/   
table_infoj   s    zPowerBIDataset.table_infozOptional[Union[List[str], str]]zOptional[List[str]])r   r(   c                   s   |durt |tr~t|dkr~|d dkr~dd |D }fdd|D   r`tdd   fd	d|D }|rz|S dS t |tr|dkr|jvrtd
| dS t|gS jS )zHGet the tables names that need to be queried, after checking they exist.Nr    c                 S  s   g | ]}t |qS r)   r*   r,   r)   r)   r/   r0   y   r1   z7PowerBIDataset._get_tables_to_query.<locals>.<listcomp>c                   s   g | ]}| j vr|qS r)   r@   r,   r7   r)   r/   r0   z   s   z!Table(s) %s not found in dataset.rB   c                   s   g | ]}| vr|qS r)   r)   r,   )non_existing_tablesr)   r/   r0      s   zTable %s not found in dataset.)	
isinstancelistlenloggerwarningrE   r   r   r+   )r8   r   Zfixed_tablestablesr)   )rK   r8   r/   _get_tables_to_queryo   s4    





z#PowerBIDataset._get_tables_to_query)tables_todor(   c                   s    fdd|D S )z-Get the tables that still need to be queried.c                   s   g | ]}| j vr|qS r)   )r#   r,   r7   r)   r/   r0      r1   z3PowerBIDataset._get_tables_todo.<locals>.<listcomp>r)   )r8   rS   r)   r7   r/   _get_tables_todo   s    zPowerBIDataset._get_tables_todoc                   s"    fdd| j  D }d|S )z=Create a string of the table schemas for the supplied tables.c                   s   g | ]\}}| v r|qS r)   r)   )r-   r.   Zschemar@   r)   r/   r0      s   z9PowerBIDataset._get_schema_for_tables.<locals>.<listcomp>rB   )r#   rF   rE   )r8   r   r#   r)   r@   r/   _get_schema_for_tables   s    
z%PowerBIDataset._get_schema_for_tablesc                 C  s>   |  |}|du rdS | |}|D ]}| | q$| |S )'Get information about specified tables.NNo (valid) tables requested.)rR   rT   _get_schemarU   )r8   r   tables_requestedrS   r.   r)   r)   r/   rH      s    

zPowerBIDataset.get_table_infoc                   sH     |}|du rdS  |}tj fdd|D  I dH   |S )rV   NrW   c                   s   g | ]}  |qS r)   )_aget_schemar,   r7   r)   r/   r0      r1   z2PowerBIDataset.aget_table_info.<locals>.<listcomp>)rR   rT   asynciogatherrU   )r8   r   rY   rS   r)   r7   r/   aget_table_info   s    

zPowerBIDataset.aget_table_infoNoner.   r(   c              
   C  s   z@|  d| j d| d}t|d d d d d | j|< W nb tyh   td| d	| j|< Y n< ty } z$td
|| d	| j|< W Y d}~n
d}~0 0 dS )Get the schema for a table.EVALUATE TOPN(rB   )resultsr   rQ   rows'Timeout while getting table info for %sunknown)Error while getting table info for %s: %sN)runr!   
json_to_mdr#   r   rO   rP   r=   r8   r.   resultr>   r)   r)   r/   rX      s    &zPowerBIDataset._get_schemac              
     s   zF|  d| j d| dI dH }t|d d d d d | j|< W nb tyn   td	| d
| j|< Y n< ty } z$td|| d
| j|< W Y d}~n
d}~0 0 dS )r`   ra   rB   rb   Nrc   r   rQ   rd   re   rf   rg   )arunr!   ri   r#   r   rO   rP   r=   rj   r)   r)   r/   rZ      s    
&zPowerBIDataset._aget_schemazdict[str, Any])commandr(   c                 C  s   d| ig| j ddidS )z(Create the json content for the request.queryZincludeNullsT)ZqueriesZimpersonatedUserNameZserializerSettings)r   )r8   rm   r)   r)   r/   _create_json_content   s    
z#PowerBIDataset._create_json_contentc                 C  s>   t d| tj| j| || jdd}|jdkr6dS | S )zAExecute a DAX command and return a json representing the results.Running command: %sr   )jsonr?   timeout  FTokenError: Could not login to PowerBI, please check your credentials.)	rO   debugrequestspostr9   ro   r?   status_coderq   )r8   rm   responser)   r)   r/   rh      s    
zPowerBIDataset.runc              
     s  t d| | jr| jj| j| j| |tddd4 I dH N}|jdkr`W d  I dH  dS |j	|j
dI dH }|W  d  I dH  S 1 I dH s0    Y  t 4 I dH }|j| j| j| |tddd4 I dH v}|jdkrW d  I dH  W d  I dH  dS |j	|j
dI dH }|W  d  I dH  W  d  I dH  S 1 I dH sb0    Y  W d  I dH  q1 I dH s0    Y  dS )	z;Execute a DAX command and return the result asynchronously.rp   r   )total)r?   rq   rr   Nrs   rt   )content_type)rO   ru   r$   rw   r9   r?   ro   r
   statusrq   r{   aiohttpZClientSession)r8   rm   ry   Zresponse_jsonsessionr)   r)   r/   rl      s2    
.(zPowerBIDataset.arun)N)N)N)#__name__
__module____qualname____doc____annotations__r   r   r   r   r   r!   dictr#   r$   r   Zmodel_configr   classmethodr5   propertyr9   r?   rA   rG   rI   rR   rT   rU   rH   r]   rX   rZ   ro   rh   rl   r)   r)   r)   r/   r      sJ   
   r   z'List[Dict[str, Union[str, int, float]]]r   r   )json_contents
table_namer(   c                 C  s   t | dkrdS d}| d  }|D ]>}|dddd |rR|| dd |d| d7 }q$|d7 }| D ]*}| D ]}|d| d7 }q||d7 }qp|S )	z*Convert a JSON object to a markdown table.r   rJ   [.]z|  z|
)rN   keysreplacer'   )r   r   Z	output_mdr?   headerrowrD   r)   r)   r/   ri      s    
ri   r_   c                 C  s,   d| v r(|  ds(| ds(d|  dS | S )z9Add single quotes around table names that contain spaces.r   ')
startswithendswith)r.   r)   r)   r/   r+     s    r+   )N)#r   
__future__r   r[   loggingostypingr   r   r   r   r   r   r	   r}   rv   r
   r   Zpydanticr   r   r   r   Zrequests.exceptionsr   	getLoggerr   rO   getenvr6   Zazure.core.credentialsr   r   ri   r+   r)   r)   r)   r/   <module>   s&   $
 c 