
    7|h+                    "   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j2                  e      Z ej8                  dd	      Zerdd
lmZ  G d de      Z 	 d	 	 	 	 	 ddZ!ddZ"y)z#Wrapper around a Power BI endpoint.    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalUnion)ClientTimeoutServerTimeoutError)	BaseModel
ConfigDictFieldmodel_validator)TimeoutPOWERBI_BASE_URLz"https://api.powerbi.com/v1.0/myorg)TokenCredentialc                     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      Z
ded<    e	e      Zded<   dZded<    ed      Z ed      ed,d              Zed-d       Zed.d       Zd/dZd-d Zed-d!       Z	 d0	 	 	 d1d"Zd2d#Zd3d$Z	 d0	 	 	 d4d%Z	 d0	 	 	 d4d&Zd5d'Zd5d(Zd6d)Z d7d*Z!d7d+Z"y)8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_id	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_factoryDict[str, str]schemaszOptional[aiohttp.ClientSession]
aiosessionT)arbitrary_types_allowedbefore)modec                    |j                  dg       }|D cg c]  }t        |       c}|d<   d|v sd|v r|S t        d      c c}w )z?Validate that at least one of token and credentials is present.r   r   r   z.Please provide either a credential or a token.)getfix_table_name
ValueError)clsvaluesr   tables       d/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/utilities/powerbi.pyvalidate_paramszPowerBIDataset.validate_params4   sT     jj3DO P5!6 P}f 6MIJJ !Qs   Ac                    | 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   selfs    r4   request_urlzPowerBIDataset.request_url>   sF     ==Zxj@QQ`aa:doo%6oFF    c                   | j                   rdd| j                   z   dS ddlm} | j                  r.	 | j                  j	                  d      j                   }dd|z   dS  |d	      # t
        $ r} |d      |d}~ww xY w)
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   azure.core.exceptionsr>   r   	get_token	Exception)r9   r>   r   excs       r4   headerszPowerBIDataset.headersE   s     :: 2!*TZZ!7 	
 ??11G%  %7%.%6  ((JKK	  /Js   ,A' '	A>0	A99A>c                    | j                   S )zGet names of tables available.)r   r8   s    r4   get_table_nameszPowerBIDataset.get_table_names`   s    r;   c           	         | j                   rAdj                  | j                   j                         D cg c]  \  }}| d|  c}}      S yc c}}w )zGet the available schema's., z: z9No known schema's yet. Use the schema_powerbi tool first.)r(   joinitems)r9   keyvalues      r4   get_schemaszPowerBIDataset.get_schemasd   sH    <<99$,,BTBTBVWJCRw/WXXJ Xs   A
c                "    | j                         S )z-Information about all tables in the database.)get_table_infor8   s    r4   
table_infozPowerBIDataset.table_infoj   s     ""$$r;   c                   |t        |t              rt        |      dkD  r|d   dk7  rw|D cg c]  }t        |       }}|D cg c]  }|| j                  vs| }}|r%t
        j                  ddj                  |             |D cg c]	  }||vs| }}|r|S dS t        |t              r6|dk7  r1|| j                  vrt
        j                  d|       yt        |      gS | j                  S c c}w c c}w c c}w )zHGet the tables names that need to be queried, after checking they exist.Nr    z!Table(s) %s not found in dataset.rG   zTable %s not found in dataset.)	
isinstancelistlenr/   r   loggerwarningrH   r   )r9   r   r3   fixed_tablesnon_existing_tablestabless         r4   _get_tables_to_queryz#PowerBIDataset._get_tables_to_queryo   s    ";-$q(Nb(CNO%u 5OO'3'#uDDTDT7TE'# ' 'NN;		"56
 (4#uDW7WE  "(v1T1+s+r0Ad&6&66NN#C[Q&{344%  P's   C2C7C7
	C<C<c                J    |D cg c]  }|| j                   vs| c}S c c}w )z-Get the tables that still need to be queried.)r(   )r9   tables_todor3   s      r4   _get_tables_todozPowerBIDataset._get_tables_todo   s!    #.L%%t||2KLLLs     c                    | j                   j                         D cg c]  \  }}||v s| }}}dj                  |      S c c}}w )z=Create a string of the table schemas for the supplied tables.rG   )r(   rI   rH   )r9   r   r3   schemar(   s        r4   _get_schema_for_tablesz%PowerBIDataset._get_schema_for_tables   sL     )-(:(:(<
$uf@TF
 
 yy!!
s
   AAc                    | j                  |      }|y| j                  |      }|D ]  }| j                  |        | j                  |      S )'Get information about specified tables.No (valid) tables requested.)rZ   r]   _get_schemar`   r9   r   tables_requestedr\   r3   s        r4   rN   zPowerBIDataset.get_table_info   s^      44[A#1++,<=  	$EU#	$**+;<<r;   c                   K   | j                  |      }|y| j                  |      }t        j                  |D cg c]  }| j	                  |       c}  d{    | j                  |      S c c}w 7 w)rb   Nrc   )rZ   r]   asynciogather_aget_schemar`   re   s        r4   aget_table_infozPowerBIDataset.aget_table_info   sv       44[A#1++,<=nn[QEt007QRRR**+;<< RRs   9A7A0A7A5A7c                n   	 | j                  d| j                   d| d      }t        |d   d   d   d   d         | j                  |<   y# t        $ r( t
        j                  d|       d	| j                  |<   Y yt        $ r0}t
        j                  d
||       d	| j                  |<   Y d}~yd}~ww xY w)Get the schema for a table.EVALUATE TOPN(rG   )resultsr   rY   rows'Timeout while getting table info for %sunknown)Error while getting table info for %s: %sN)runr%   
json_to_mdr(   r   rU   rV   rA   r9   r3   resultrB   s       r4   rd   zPowerBIDataset._get_schema   s    
	,XX !?!? @5'KF #-VI->q-A(-KA-Nv-V"WDLL 	,NNDeL"+DLL 	,NNFsS"+DLL	,s   A	A .B4<B4&B//B4c                  K   	 | j                  d| j                   d| d       d{   }t        |d   d   d   d   d         | j                  |<   y7 ,# t        $ r( t
        j                  d	|       d
| j                  |<   Y yt        $ r0}t
        j                  d||       d
| j                  |<   Y d}~yd}~ww xY ww)rm   rn   rG   ro   Nrp   r   rY   rq   rr   rs   rt   )arunr%   rv   r(   r   rU   rV   rA   rw   s       r4   rj   zPowerBIDataset._aget_schema   s     
	,99 !?!? @5'K F #-VI->q-A(-KA-Nv-V"WDLL " 	,NNDeL"+DLL 	,NNFsS"+DLL	,sJ   C%A A+A CA .C CC &B;6C;C  Cc                .    d| ig| j                   ddidS )z(Create the json content for the request.queryincludeNullsT)queriesimpersonatedUserNameserializerSettings)r   )r9   commands     r4   _create_json_contentz#PowerBIDataset._create_json_content   s,     !gY01$($?$?#14"8
 	
r;   c                    t         j                  d|       t        j                  | j                  | j                  |      | j                  d      }|j                  dk(  r	 y|j                         S )zAExecute a DAX command and return a json representing the results.Running command: %sr    )jsonrC   timeout  FTokenError: Could not login to PowerBI, please check your credentials.)	rU   debugrequestspostr:   r   rC   status_coder   )r9   r   responses      r4   ru   zPowerBIDataset.run   sf    *G4==**73LL	
 3&X }}r;   c           	     <  K   t         j                  d|       | j                  r| j                  j                  | j                  | j
                  | j                  |      t        d            4 d{   }|j                  dk(  r	 ddd      d{    y|j                  |j                         d{   }|cddd      d{    S t        j                         4 d{   }|j                  | j                  | j
                  | j                  |      t        d            4 d{   }|j                  dk(  r"	 ddd      d{    ddd      d{    y|j                  |j                         d{   }|cddd      d{    cddd      d{    S 7 >7 !7 7 # 1 d{  7  sw Y   xY w7 7 7 7 r7 O7 ?7 0# 1 d{  7  sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)	z;Execute a DAX command and return the result asynchronously.r   r    )total)rC   r   r   Nr   r   )content_type)rU   r   r)   r   r:   rC   r   r   statusr   r   aiohttpClientSession)r9   r   r   response_jsonsessions        r4   rz   zPowerBIDataset.arun   s    *G4??++  ..w7%B/	 ,  	% 	%
 ??c)c	% 	% 	% '/mmAVAVm&W W$	% 	% 	% ((* 
	% 
	%g||  ..w7%B/	 $  	% 	%
 ??c)c	% 	%
	% 
	% 
	% '/mmAVAVm&W W$	% 	% 	%
	% 
	% 
	%	% 	% !X	% 	% 	% 	%
	%	% 	%
	% !X	%
	%	% 	% 	%
	% 
	% 
	% 
	% 
	%s]  A3H5F36H9F=
HF6HF=:F9;F= HF;H*G+H.AH5G6H9G 
HGHH%G&H+G 
GG HGH!H-G.H6H9F=;H=GGGHHHHG HH G2	&G)'G2	.H5H HHHHHH)r2   zDict[str, Any]returnr   )r   r   )r   r'   )r   zIterable[str]N)r   Optional[Union[List[str], str]]r   zOptional[List[str]])r\   r   r   r   )r   r   r   r   )r   r   r   r   )r3   r   r   None)r   r   r   zdict[str, Any])r   r   r   r   )#__name__
__module____qualname____doc____annotations__r   r   r   r   r   r%   dictr(   r)   r   model_configr   classmethodr5   propertyr:   rC   rE   rL   rO   rZ   r]   r`   rN   rk   rd   rj   r   ru   rz    r;   r4   r   r      s\    O"Hm",0J)0E=,0M0%*1r%BsB#D9G^926J/6 $L (#K  $K G G L L4 K % %
 >B : 	 <M" >B
=:
=	
= >B	=:	=		=,,
%r;   r   c                >   t        |       dk(  ryd}| d   j                         }|D ]D  }|j                  dd      j                  dd       |r|j                  | dd       |d| dz  }F |dz  }| D ]%  }|j                         D ]  }|d| dz  } |dz  }' |S )	z*Convert a JSON object to a markdown table.r   rQ   [.]z|  z|
)rT   keysreplacer2   )json_contents
table_name	output_mdrC   headerrowrK   s          r4   rv   rv      s    
 =QIA##%G $sC ((b1NNj\+R0r&^#		$
 I ZZ\ 	'E2eWA&I	'U	 r;   c                ^    d| v r(| j                  d      s| j                  d      sd|  dS | S )z9Add single quotes around table names that contain spaces.r   ')
startswithendswith)r3   s    r4   r/   r/     s4    
e|E,,S1%..:M5'|Lr;   r   )r   z'List[Dict[str, Union[str, int, float]]]r   r   r   r   )r3   r   r   r   )#r   
__future__r   rh   loggingostypingr   r   r   r   r   r	   r
   r   r   r   r   pydanticr   r   r   r   requests.exceptionsr   	getLoggerr   rU   getenvr7   azure.core.credentialsr   r   rv   r/   r   r;   r4   <module>r      s    ) "   	 L L L   5  (			8	$299')MN6]%Y ]%D !%: 	,r;   