
    dh+                    2   S r SSKJr  SSKrSSKrSSKrSSKJrJrJ	r	J
r
JrJrJr  SSKrSSKrSSKJrJr  SSKJrJrJrJr  SSKJr  \R2                  " \5      r\R8                  " SS	5      r\(       a  SS
KJr   " S S\5      r  S     SS jjr!SS jr"g)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                     \ rS rSr% SrS\S'   S\S'   SrS\S	'   SrS
\S'   SrS\S'   Sr	S\S'   \
" SSSS9rS\S'   \
" \S9rS\S'   SrS\S'   \" SS9r\" SS9\S.S j5       5       r\S/S j5       r\S0S j5       rS1S  jrS/S! jr\S/S" j5       r S2   S3S# jjrS4S$ jrS5S% jr S2   S6S& jjr S2   S6S' jjrS7S( jrS7S) jr S8S* jr!S9S+ jr"S9S, jr#S-r$g):PowerBIDataset   a;  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                    UR                  S/ 5      nU Vs/ sH  n[        U5      PM     snUS'   SU;   d  SU;   a  U$ [        S5      es  snf )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       ]/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/utilities/powerbi.pyvalidate_paramsPowerBIDataset.validate_params4   sX     jj3DO PK5!6K P}f 6MIJJ !Qs   A
c                    U R                   (       a#  [         SU R                    SU R                   S3$ [         SU R                   S3$ )zGet the request url.z/groups/z
/datasets/z/executeQueries)r   BASE_URLr   selfs    r5   request_urlPowerBIDataset.request_url>   sF     ==Zxj@QQ`aa:doo%6oFF    c                   U R                   (       a  SSU R                   -   S.$ SSKJn  U R                  (       a.   U R                  R	                  S5      R                   nSSU-   S.$ U" S	5      e! [
         a  nU" S5      UeSnAff = f)
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.exceptionsrA   r   	get_token	Exception)r;   rA   r   excs       r5   headersPowerBIDataset.headersE   s     :: 2!*TZZ!7 	
 ??11G%  %7%.%6  ((JKK	  /Js   ,A1 1
B	;	BB	c                    U R                   $ )zGet names of tables available.)r   r:   s    r5   get_table_namesPowerBIDataset.get_table_names`   s    r>   c           	         U R                   (       aB  SR                  U R                   R                  5        VVs/ sH  u  pU SU 3PM     snn5      $ gs  snnf )zGet the available schema's., z: z9No known schema's yet. Use the schema_powerbi tool first.)r)   joinitems)r;   keyvalues      r5   get_schemasPowerBIDataset.get_schemasd   sL    <<99$,,BTBTBVWBVJCRw/BVWXXJ Xs   A
c                "    U R                  5       $ )z-Information about all tables in the database.)get_table_infor:   s    r5   
table_infoPowerBIDataset.table_infoj   s     ""$$r>   c                J   UGb  [        U[        5      (       a  [        U5      S:  a  US   S:w  a  U Vs/ sH  n[        U5      PM     nnU Vs/ sH  o"U R                  ;  d  M  UPM     nnU(       a%  [
        R                  SSR                  U5      5        U Vs/ sH  o"U;  d  M
  UPM     nnU(       a  U$ S$ [        U[        5      (       a8  US:w  a2  XR                  ;  a  [
        R                  SU5        g[        U5      /$ U R                  $ s  snf s  snf s  snf )zHGet the tables names that need to be queried, after checking they exist.Nr    z!Table(s) %s not found in dataset.rL   zTable %s not found in dataset.)	
isinstancelistlenr0   r   loggerwarningrM   r   )r;   r   r4   fixed_tablesnon_existing_tablestabless         r5   _get_tables_to_query#PowerBIDataset._get_tables_to_queryo   s     ";--$q(Nb(CNO;%u 5;O'3''3eDDTDT7TE| $ ' 'NN;		"56
 (4'3eDW7WE|   "(v1T1+s++r0A&6&66NN#C[Q&{344%  P's   DD&DD *D c                R    U Vs/ sH  o"U R                   ;  d  M  UPM     sn$ s  snf )z-Get the tables that still need to be queried.)r)   )r;   tables_todor4   s      r5   _get_tables_todoPowerBIDataset._get_tables_todo   s#    #.L;%t||2K;LLLs   $$c                    U R                   R                  5        VVs/ sH  u  p#X!;   d  M  UPM     nnnSR                  U5      $ s  snnf )z=Create a string of the table schemas for the supplied tables.rL   )r)   rN   rM   )r;   r   r4   schemar)   s        r5   _get_schema_for_tables%PowerBIDataset._get_schema_for_tables   sK     )-(:(:(<
(<}u@TF(< 	 
 yy!!
s
   
AAc                    U R                  U5      nUc  gU R                  U5      nU H  nU R                  U5        M     U R                  U5      $ )'Get information about specified tables.No (valid) tables requested.)ra   re   _get_schemari   r;   r   tables_requestedrd   r4   s        r5   rT   PowerBIDataset.get_table_info   sY      44[A#1++,<= EU# !**+;<<r>   c                   #    U R                  U5      nUc  gU R                  U5      n[        R                  " U Vs/ sH  o@R	                  U5      PM     sn6 I Sh  vN   U R                  U5      $ s  snf  N7f)rl   Nrm   )ra   re   asynciogather_aget_schemari   ro   s        r5   aget_table_infoPowerBIDataset.aget_table_info   sw       44[A#1++,<=nn[Q[E007[QRRR**+;<< RRs   ;A:A3A:A8A:c                p    U R                  SU R                   SU S35      n[        US   S   S   S   S   5      U R                  U'   g! [         a(    [
        R                  SU5        S	U R                  U'    g[         a/  n[
        R                  S
X5        S	U R                  U'    SnAgSnAff = f)Get the schema for a table.EVALUATE TOPN(rL   )resultsr   r`   rows'Timeout while getting table info for %sunknown)Error while getting table info for %s: %sN)runr&   
json_to_mdr)   r   r\   r]   rD   r;   r4   resultrE   s       r5   rn   PowerBIDataset._get_schema   s    
	,XX !?!? @5'KF #-VI->q-A(-KA-Nv-V"WDLL 	,NNDeL"+DLL 	,NNFS"+DLL	,s   A	A /B5=	B5%B00B5c                  #     U R                  SU R                   SU S35      I Sh  vN n[        US   S   S   S   S   5      U R                  U'   g N,! [         a(    [
        R                  S	U5        S
U R                  U'    g[         a/  n[
        R                  SX5        S
U R                  U'    SnAgSnAff = f7f)ry   rz   rL   r{   Nr|   r   r`   r}   r~   r   r   )arunr&   r   r)   r   r\   r]   rD   r   s       r5   ru   PowerBIDataset._aget_schema   s     
	,99 !?!? @5'K F #-VI->q-A(-KA-Nv-V"WDLL " 	,NNDeL"+DLL 	,NNFS"+DLL	,sJ   C%A A+A CA /CC		C%B<7C<CCc                .    SU 0/U R                   SS0S.$ )z(Create the json content for the request.queryincludeNullsT)queriesimpersonatedUserNameserializerSettings)r   )r;   commands     r5   _create_json_content#PowerBIDataset._create_json_content   s,     !gY01$($?$?#14"8
 	
r>   c                    [         R                  SU5        [        R                  " U R                  U R                  U5      U R                  SS9nUR                  S:X  a   gUR                  5       $ )zAExecute a DAX command and return a json representing the results.Running command: %sr!   )jsonrF   timeout  FTokenError: Could not login to PowerBI, please check your credentials.)	r\   debugrequestspostr<   r   rF   status_coder   )r;   r   responses      r5   r   PowerBIDataset.run   sf    *G4==**73LL	
 3&X }}r>   c           
     F  #    [         R                  SU5        U R                  (       a  U R                  R                  U R                  U R
                  U R                  U5      [        SS9S9 ISh  vN nUR                  S:X  a   SSS5      ISh  vN   gUR                  UR                  S9I Sh  vN nUsSSS5      ISh  vN   $ [        R                  " 5        ISh  vN nUR                  U R                  U R
                  U R                  U5      [        SS9S9 ISh  vN nUR                  S:X  a"   SSS5      ISh  vN   SSS5      ISh  vN   gUR                  UR                  S9I Sh  vN nUsSSS5      ISh  vN   sSSS5      ISh  vN   $  GN5 GN N N! , ISh  vN  (       d  f       N= f N N N Nt NT ND N5! , ISh  vN  (       d  f       O= fSSS5      ISh  vN    g! , ISh  vN  (       d  f       g= f7f)	z;Execute a DAX command and return the result asynchronously.r   r!   )total)rF   r   r   Nr   r   )content_type)r\   r   r*   r   r<   rF   r   r   statusr   r   aiohttpClientSession)r;   r   r   response_jsonsessions        r5   r   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]  A2H!4F)5H!8F3
H!F,H!F37F/8F3=H!	F1
H!(G)H!,AH-G.H1GHGHH!GH!$G GGHGHH!#G$H!,H!/F31H!3G
9F<:G
H!HHH!GHH!G2	!G$"G2	.H5H! HH!HHHH! )r3   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]])rd   r   r   r   )r   r   r   r   )r   r   r   r   )r4   r   r   None)r   r   r   zdict[str, Any])r   r   r   r   )%__name__
__module____qualname____firstlineno____doc____annotations__r   r   r   r   r   r&   dictr)   r*   r   model_configr   classmethodr6   propertyr<   rF   rI   rQ   rU   ra   re   ri   rT   rv   rn   ru   r   r   r   __static_attributes__r   r>   r5   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                V   [        U 5      S:X  a  gSnU S   R                  5       nU HJ  nUR                  SS5      R                  SS5        U(       a  UR                  U S3S5        USU S3-  nML     US-  nU  H(  nUR                  5        H  nUSU S3-  nM     US-  nM*     U$ )	z*Convert a JSON object to a markdown table.r   rX   [.]z|  z|
)r[   keysreplacer3   )json_contents
table_name	output_mdrF   headerrowrP   s          r5   r   r      s    
 =QIA##%GsC ((b1NNj\+R0r&^#		 
 IZZ\E2eWA&I "U	  r>   c                v    SU ;   a2  U R                  S5      (       d  U R                  S5      (       d  SU  S3$ U $ )z9Add single quotes around table names that contain spaces.r   ')
startswithendswith)r4   s    r5   r0   r0     s:    
e|E,,S11%..:M:M5'|Lr>   r   )r   z'List[Dict[str, Union[str, int, float]]]r   r   r   r   )r4   r   r   r   )#r   
__future__r   rs   loggingostypingr   r   r   r   r   r	   r
   r   r   r   r   pydanticr   r   r   r   requests.exceptionsr   	getLoggerr   r\   getenvr9   azure.core.credentialsr   r   r   r0   r   r>   r5   <module>r      s    ) "   	 L L L   5  (			8	$99')MN6]%Y ]%D !%: 	,r>   