
    dh$a                       S r SSKJr  SSKrSSKJrJrJrJrJ	r	J
r
JrJr  SSKrSSKJr  SSKJr  SSKJrJrJrJrJrJr  SSKJrJrJr  SS	KJrJr  SS
KJ r   SSK!J"r"  SSK#J$r$  SS jr%SS.SS jjr&SS jr' " S S5      r(g)%SQLAlchemy wrapper around a database.    )annotationsN)AnyDictIterableListLiteralOptionalSequenceUnion)
deprecated)get_from_env)MetaDataTablecreate_engineinspectselecttext)URLEngineResult)ProgrammingErrorSQLAlchemyError)CreateTable)
Executable)NullTypec           	     <    SU S    SU S    S[        U S   5       3$ )NzName: namez
, Unique: uniquez, Columns: column_namesstr)indexs    b/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/utilities/sql_database.py_format_indexr%      s7    
vz%/): ;~./0	2    z...)suffixc                   [        U [        5      (       a  US::  a  U $ [        U 5      U::  a  U $ U SU[        U5      -
   R                  SS5      S   U-   $ )zQ
Truncate a string to a certain number of words, based on the max string
length.
r   N    )
isinstancer"   lenrsplit)contentlengthr'   s      r$   truncate_wordr0   !   s[     gs##v{
7|v)Vc&k)*11#q9!<vEEr&   c                \    [         R                  " SU 5      (       d  [        SU  S35      eU $ )zHSanitize a schema name to only contain letters, digits, and underscores.z^[a-zA-Z0-9_]+$zSchema name 'z_' contains invalid characters. Schema names must contain only letters, digits, and underscores.)rematch
ValueErrorschemas    r$   sanitize_schemar7   0   s;    88&//F8 $O O
 	
 Mr&   c                  F   \ rS rSrSr          S                     SS jjr\ S       S S jj5       r\\" SSSS	9     S!                 S"S
 jj5       5       r	\     S#           S$S jj5       r
\S%S j5       rS&S jr\" SSSS9S&S j5       r\S%S j5       r S'     S(S jjrS)S jrS)S jr S*SSS.         S+S jjjr  S,SSS.           S-S jjjrSS.S jjr  S,SSS.           S/S jjjrS0S jrSrg)1SQLDatabase:   r   Nc                  ^ ^ UT l         UT l        U(       a  U(       a  [        S5      e[        T R                   5      T l        [        [        T R                  R                  US95      U	(       a  T R                  R                  US9O/ -   5      T l	        U(       a  [        U5      O	[        5       T l
        T R                  (       a/  T R                  T R                  -
  nU(       a  [        SU S35      eU(       a  [        U5      O	[        5       T l        T R                  (       a/  T R                  T R                  -
  nU(       a  [        SU S35      eT R                  5       nU(       a  [        U5      OT R                  T l        [        U[        5      (       d  [!        S5      eUT l        UT l        UT l        T R&                  (       a}  [        T R&                  [(        5      (       d  [!        S5      e[        T R&                  5      R+                  T R                  5      m[)        UU 4S jT R&                   5       5      T l        U
T l        U	T l        U=(       d
    [1        5       T l        U(       dD  T R2                  R5                  U	T R                   [        T R                  5      T R                  S	9  g
g
)z Create engine from database URI.z4Cannot specify both include_tables and ignore_tablesr5   zinclude_tables  not found in databasezignore_tables z,sample_rows_in_table_info must be an integerz]table_info must be a dictionary with table names as keys and the desired table info as valuesc              3  T   >#    U H  nUT;   d  M  UTR                   U   4v   M      g 7fN)_custom_table_info).0tableintersectionselfs     r$   	<genexpr>'SQLDatabase.__init__.<locals>.<genexpr>z   s2      +4EL( 8//674s   	((viewsbindonlyr6   N)_engine_schemar4   r   
_inspectorsetlistget_table_namesget_view_names_all_tables_include_tables_ignore_tablesget_usable_table_names_usable_tablesr+   int	TypeError_sample_rows_in_table_info_indexes_in_table_infor?   dictrB   _max_string_length_view_supportr   	_metadatareflect)rC   enginer6   metadataignore_tablesinclude_tablessample_rows_in_table_infoindexes_in_table_infocustom_table_infoview_supportmax_string_lengthlazy_table_reflectionmissing_tablesusable_tablesrB   s   `             @r$   __init__SQLDatabase.__init__=   sK    mSTT!$,,/ 000?@@Lt--V-<RTV

 7Es>2#%!11D4D4DDN %n%55KL  5Bc-0su!0043C3CCN $^$44JK  3354Ac-0tGWGW3S99JKK*C'&;#"3""d55t<<3 
 t667DDTEUEUVL&* +!44+ 'D# #4)!/XZ$NN"""\\$--.||	 #  %r&   c                >    U=(       d    0 nU " [        U40 UD640 UD6$ )z'Construct a SQLAlchemy engine from URI.)r   )clsdatabase_uriengine_argskwargs_engine_argss        r$   from_uriSQLDatabase.from_uri   s(     #(b=>>I&IIr&   z0.3.18zFor performing structured retrieval using Databricks SQL, see the latest best practices and recommended APIs at https://docs.unitycatalog.io/ai/integrations/langchain/ insteadz1.0)messageremovalc           
         SSK Jn	  Sn
 SSKJn  U" 5       n
U
R
                  nUc  [        SSU5      nU
(       a  U
R                  OSnUc  [        SS	U5      nUc"  Uc  U
(       a  U
R                  nO[        S
5      eU(       a  U(       a  [        S5      eU(       a  SU 3nOSU 3nSU SU SU SU SU 3
nU R                  " SXS.UD6$ ! [         a    [        S5      ef = f! [        [        4 a    Sn Nf = f)a  
Class method to create an SQLDatabase instance from a Databricks connection.
This method requires the 'databricks-sql-connector' package. If not installed,
it can be added using `pip install databricks-sql-connector`.

Args:
    catalog (str): The catalog name in the Databricks database.
    schema (str): The schema name in the catalog.
    host (Optional[str]): The Databricks workspace hostname, excluding
        'https://' part. If not provided, it attempts to fetch from the
        environment variable 'DATABRICKS_HOST'. If still unavailable and if
        running in a Databricks notebook, it defaults to the current workspace
        hostname. Defaults to None.
    api_token (Optional[str]): The Databricks personal access token for
        accessing the Databricks SQL warehouse or the cluster. If not provided,
        it attempts to fetch from 'DATABRICKS_TOKEN'. If still unavailable
        and running in a Databricks notebook, a temporary token for the current
        user is generated. Defaults to None.
    warehouse_id (Optional[str]): The warehouse ID in the Databricks SQL. If
        provided, the method configures the connection to use this warehouse.
        Cannot be used with 'cluster_id'. Defaults to None.
    cluster_id (Optional[str]): The cluster ID in the Databricks Runtime. If
        provided, the method configures the connection to use this cluster.
        Cannot be used with 'warehouse_id'. If running in a Databricks notebook
        and both 'warehouse_id' and 'cluster_id' are None, it uses the ID of the
        cluster the notebook is attached to. Defaults to None.
    engine_args (Optional[dict]): The arguments to be used when connecting
        Databricks. Defaults to None.
    **kwargs (Any): Additional keyword arguments for the `from_uri` method.

Returns:
    SQLDatabase: An instance of SQLDatabase configured with the provided
        Databricks connection details.

Raises:
    ValueError: If 'databricks-sql-connector' is not found, or if both
        'warehouse_id' and 'cluster_id' are provided, or if neither
        'warehouse_id' nor 'cluster_id' are provided and it's not executing
        inside a Databricks notebook.
r   )sqlzfdatabricks-sql-connector package not found, please install with `pip install databricks-sql-connector`N)get_contexthostDATABRICKS_HOST	api_tokenDATABRICKS_TOKENz6Need to provide either 'warehouse_id' or 'cluster_id'.z/Can't have both 'warehouse_id' or 'cluster_id'.z/sql/1.0/warehouses/z/sql/protocolv1/o/0/zdatabricks://token:@z?http_path=z	&catalog=z&schema=)ro   rp    )
databricksrx   ImportError!dbruntime.databricks_repl_contextry   browserHostNameAttributeErrorr   apiToken	clusterIdr4   rs   )rn   catalogr6   rz   r|   warehouse_id
cluster_idrp   rq   rx   contextry   default_hostdefault_api_token	http_pathuris                   r$   from_databricksSQLDatabase.from_databricks   sF   x	& 	 E!mG"22L <(9<HD07G,,T$[2DFWXIJ$6$..
 L  JNOO.|n=I.zl;I ")AdV 4"9WIXfXG 	 ||PPPPS  	: 	 ^, 	 L	 s   C C' C$'C<;C<c                t     SSK Jn  U" XX4U5      nU R                  US9$ ! [         a    [        S5      ef = f)a  
Class method to create an SQLDatabase instance from a CnosDB connection.
This method requires the 'cnos-connector' package. If not installed, it
can be added using `pip install cnos-connector`.

Args:
    url (str): The HTTP connection host name and port number of the CnosDB
        service, excluding "http://" or "https://", with a default value
        of "127.0.0.1:8902".
    user (str): The username used to connect to the CnosDB service, with a
        default value of "root".
    password (str): The password of the user connecting to the CnosDB service,
        with a default value of "".
    tenant (str): The name of the tenant used to connect to the CnosDB service,
        with a default value of "cnosdb".
    database (str): The name of the database in the CnosDB tenant.

Returns:
    SQLDatabase: An instance of SQLDatabase configured with the provided
    CnosDB connection details.
r   )make_cnosdb_langchain_uri)ro   zRcnos-connector package not found, please install with `pip install cnos-connector`)cnosdb_connectorr   rs   r   )rn   urluserpasswordtenantdatabaser   r   s           r$   from_cnosdbSQLDatabase.from_cnosdb  sJ    <		B+CxRC<<S<11 	0 	s   ! 7c                B    U R                   R                  R                  $ )z/Return string representation of dialect to use.)rJ   dialectr   rC   s    r$   r   SQLDatabase.dialect*  s     ||##(((r&   c                    U R                   (       a  [        U R                   5      $ [        U R                  U R                  -
  5      $ zGet names of tables available.)rR   sortedrQ   rS   r   s    r$   rT   "SQLDatabase.get_usable_table_names/  s8    $..//d&&)<)<<==r&   z0.0.1rT   )alternativerv   c                "    U R                  5       $ r   )rT   r   s    r$   rO   SQLDatabase.get_table_names5  s     **,,r&   c                "    U R                  5       $ )z-Information about all tables in the database.)get_table_infor   s    r$   
table_infoSQLDatabase.table_info:  s     ""$$r&   c                   U R                  5       nUb2  [        U5      R                  U5      nU(       a  [        SU S35      eUnU R                  R
                   Vs/ sH  oUR                  PM     nn[        U5      [        U5      -
  nU(       aC  U R                  R                  U R                  U R                  [        U5      U R                  S9  U R                  R
                   Vs/ sHR  nUR                  [        U5      ;   d  M  U R                  S:X  a"  UR                  R                  S5      (       a  MP  UPMT     nn/ n	U GH  n
U R                  (       aD  U
R                  U R                  ;   a*  U	R                  U R                  U
R                     5        MY   U
R                   R#                  5        H>  u  p[%        UR$                  5      [&        L d  M#  U
R(                  R+                  U5        M@     [1        [3        U
5      R5                  U R                  5      5      nUR7                  5        nU(       aR   0 nU
R                    H/  nUR8                  (       d  M  UR8                  UUR                  '   M1     U(       a	  USU S3-  nU R<                  =(       d    U R>                  nU(       a  US	-  nU R<                  (       a  US
U RA                  U
5       S
3-  nU R>                  (       a  US
U RC                  U
5       S
3-  nU(       a  US-  nU	R                  U5        GM     U	RE                  5         SRG                  U	5      nU$ s  snf s  snf ! [,         ai    [/        U
R                   5      R#                  5        H>  u  p[%        UR$                  5      [&        L d  M#  U
R(                  R+                  U5        M@      GNf = f! [:         a    [        S5      ef = f)6  Get information about specified tables.

Follows best practices as specified in: Rajkumar et al, 2022
(https://arxiv.org/abs/2204.00498)

If `sample_rows_in_table_info`, the specified number of sample rows will be
appended to each table description. This can increase performance as
demonstrated in the paper.
ztable_names r<   rF   sqlitesqlite_z

/*
Column Comments: z
*/z:Column comments are available on PostgreSQL, MySQL, Oraclez

/*
z*/z

)$rT   rM   
differencer4   r]   sorted_tablesr   r^   r\   rJ   rN   rK   r   
startswithr?   appendcolumnsitemstyper   _columnsremover   rZ   r"   r   compilerstripcomment	ExceptionrY   rX   _get_table_indexes_get_sample_rowssortjoin)rC   table_namesget_col_commentsall_table_namesri   tblmetadata_table_names
to_reflectmeta_tablestablesrA   kvcreate_tabler   column_comments_dictcolumnhas_extra_info	final_strs                      r$   r   SQLDatabase.get_table_info?  s_    557" -88IN </??U!VWW)O48NN4P4PQ4PS4PQ)C0D,EE
NN""((\\*%||	 #  ~~33
3xx3//  \\X-#((2E2Ei2P 3 	 
  E&&5::9P9P+Pd55ejjAB	1!MM//1DAAFF|x/--a0 2 {5199$,,GHL(//12J  +-("'--!>>>@F0= #0 ,"78L7MTR
 ++Nt/N/N  h&
**4#:#:5#A"B"EE
..4#8#8#?"@CC
d"
MM*%c !d 	KK'	M  R
& " 1 /557DAAFF|x/--a0 81, ! $T sI   M-M.M?M%9M$"M$ O+-O$AO4OOO0c                    U R                   R                  UR                  5      nSR                  [	        [
        U5      5      nSU 3$ )Nr   zTable Indexes:
)rL   get_indexesr   r   mapr%   )rC   rA   indexesindexes_formatteds       r$   r   SQLDatabase._get_table_indexes  s?    //--ejj9 IIc-&AB!"3!455r&   c                D   [        U5      R                  U R                  5      nSR                  UR                   Vs/ sH  o3R
                  PM     sn5      n U R                  R                  5        nUR                  U5      n[        [        S U5      5      nS S S 5        SR                  W Vs/ sH  nSR                  U5      PM     sn5      n	U R                   SUR
                   SU SU	 3$ s  snf ! , (       d  f       Nd= fs  snf ! [         a    Sn	 NJf = f)N	c                H    U  Vs/ sH  n[        U5      S S PM     sn$ s  snf )Nd   r!   )lsis     r$   <lambda>.SQLDatabase._get_sample_rows.<locals>.<lambda>  s     "#="QCF4CL"#=#=s   r    z rows from z table:
)r   limitrX   r   r   r   rJ   connectexecuterN   r   r   )
rC   rA   commandcolcolumns_str
connectionsample_rows_resultsample_rowsrowsample_rows_strs
             r$   r   SQLDatabase._get_sample_rows  s   -%%d&E&EF iiU]] C]c] CD	!%%':%/%7%7%@""=?QR ( #ii;(O;C3;(OPO ../{5::,im2!	
' !D (' )P   	! O	!s;   C5D 4(C:D 3DD :
DD DD
parametersexecution_optionsc                  U=(       d    0 nU=(       d    0 nU R                   R                  5        nU R                  Gbj  U R                  S:X  a  UR	                  SU R                  4US9  GO<U R                  S:X  a  UR	                  SU R                  4US9  GOU R                  S:X  a  OU R                  S:X  a  UR	                  S	U R                  4US9  OU R                  S
:X  a  UR	                  SU R                   3US9  OU R                  S:X  a  UR	                  SU R                   3US9  OtU R                  S:X  a  OcU R                  S:X  a  UR	                  SU R                  4US9  O6U R                  S:X  a&  UR	                  S[        U R                  5       3US9  [        U[        5      (       a  [        U5      nO-[        U[        5      (       a  O[        S[        U5       35      eUR                  UUUS9nUR                  (       a  US:X  a-  UR                  5        Vs/ sH  owR                  5       PM     nnOIUS:X  a'  UR!                  5       n	U	c  / OU	R                  5       /nOUS:X  a  UsSSS5        $ [#        S5      eUsSSS5        $  SSS5        / $ s  snf ! , (       d  f       / $ = f)zo
Executes SQL command through underlying engine.

If the statement returns no rows, an empty list is returned.
N	snowflakez"ALTER SESSION SET search_path = %s)r   bigqueryzSET @@dataset_id=?mssqltrinozUSE ?duckdbzSET search_path TO oraclez#ALTER SESSION SET CURRENT_SCHEMA = sqlany
postgresqlzSET search_path TO %shanazSET SCHEMA z#Query expression has unknown type: allonecursorz8Fetch parameter must be either 'one', 'all', or 'cursor')rJ   beginrK   r   exec_driver_sqlr7   r+   r"   r   r   rW   r   r   returns_rowsfetchall_asdictfetchoner4   )
rC   r   fetchr   r   r   r   xresultfirst_results
             r$   _executeSQLDatabase._execute  s     %2
-3\\!Z||'<<;...<*; / 
 \\Z/..,*; / 
 \\W,\\W,..*; / 
 \\X-
 ..-dll^<*; /  \\X-..=dll^L*; /  \\X- \\\1../*; / 
 \\V+..%odll&C%DE*; / 
 '3''w-GZ00"Ed7m_ UVV''"3 ( F ""E>39??3DE3Daiik3DFEFe^#)??#4L#/#7Rl>R>R>T=UFh&!O "!R %R  Y "!@ #A "Z 	 FE "!Z 	s$   HJ12J,
7J1J1,J11
K c               l   U R                  XXES9nUS:X  a  U$ U VVV	s/ sH9  nUR                  5        VV	s0 sH  u  pU[        XR                  S9_M     sn	nPM;     n
nnn	U(       d(  U
 Vs/ sH  n[	        UR                  5       5      PM     n
nU
(       d  g[        U
5      $ s  sn	nf s  sn	nnf s  snf )zExecute a SQL command and return a string representing the results.

If the statement returns rows, a string of the results is returned.
If the statement returns no rows, an empty string is returned.
r   r   )r/   r   )r  r   r0   r[   tuplevaluesr"   )rC   r   r  include_columnsr   r   r  rr   valueresr   s               r$   runSQLDatabase.run  s     z  
 HM 

  &'WWY%.MF e4K4KLL%.  	 
 256#35&#C6s8O
 7s   B*B$B*-"B1$B*c                `     U R                  U5      $ ! [         a  n SU 3s SnA$ SnAff = f)r   Error: N)r   r4   )rC   r   es      r$   get_table_info_no_throw#SQLDatabase.get_table_info_no_throw@  s7    	!&&{33 	!*QC= 	!s    
-(--c               d     U R                  UUUUUS9$ ! [         a  n SU 3s SnA$ SnAff = f)a
  Execute a SQL command and return a string representing the results.

If the statement returns rows, a string of the results is returned.
If the statement returns no rows, an empty string is returned.

If the statement throws an error, the error message is returned.
)r   r   r
  r  N)r  r   )rC   r   r  r
  r   r   r  s          r$   run_no_throwSQLDatabase.run_no_throwP  sM     
	!88%"3 /     	!*QC= 	!s    
/*//c                |    [        U R                  5       5      nU R                  5       nUSR                  U5      S.$ )z4Return db context that you may want in agent prompt.z, )r   r   )rN   rT   r  r   )rC   r   r   s      r$   ry   SQLDatabase.get_contextl  s7    46689113
(;9OPPr&   )rQ   r?   rJ   rS   rR   rY   rL   r[   r]   rX   rK   rU   r\   )
NNNN   FNFi,  F)r_   r   r6   Optional[str]r`   zOptional[MetaData]ra   Optional[List[str]]rb   r  rc   rV   rd   boolre   Optional[dict]rf   r  rg   rV   rh   r  r>   )ro   zUnion[str, URL]rp   r  rq   r   returnr9   )NNNNN)r   r"   r6   r"   rz   r  r|   r  r   r  r   r  rp   r  rq   r   r  r9   )z127.0.0.1:8902rootr   cnosdbpublic)r   r"   r   r"   r   r"   r   r"   r   r"   r  r9   )r  r"   )r  zIterable[str])NF)r   r  r   r  r  r"   )rA   r   r  r"   )r   )
r   Union[str, Executable]r  Literal['all', 'one', 'cursor']r   Optional[Dict[str, Any]]r   r%  r  z'Union[Sequence[Dict[str, Any]], Result])r   F)r   r#  r  r$  r
  r  r   r%  r   r%  r  1Union[str, Sequence[Dict[str, Any]], Result[Any]])r   r  r  r"   )r   r"   r  zLiteral['all', 'one']r
  r  r   r%  r   r%  r  r&  )r  zDict[str, Any])__name__
__module____qualname____firstlineno____doc__rk   classmethodrs   r   r   r   propertyr   rT   rO   r   r   r   r   r  r  r  r  ry   __static_attributes__r   r&   r$   r9   r9   :   sy   /
 !%'+-1.2)*&+,0"!$&+NN N %	N
 +N ,N $'N  $N *N N N  $N`  '+J%J $J 	J
 
J J   ##'&*$(&*^Q^Q ^Q 	^Q
 !^Q $^Q "^Q $^Q ^Q 
^Q ^Q@  $ && & 	&
 & & 
& &P ) )> %=uM- N- % %
 QVY.YIMY	Yv6

B 27\
 046:\'\ /\
 -\ 4\ 
1\B 27 %	# 046:#'# /# 	# -# 4# 
;#J!& (- %	! 046:!! %! 	! -! 4! 
;!8Qr&   r9   )r#   z+sqlalchemy.engine.interfaces.ReflectedIndexr  r"   )r.   r   r/   rV   r'   r"   r  r"   )r6   r"   r  r"   ))r+  
__future__r   r2   typingr   r   r   r   r	   r
   r   r   
sqlalchemylangchain_core._apir   langchain_core.utilsr   r   r   r   r   r   r   sqlalchemy.enginer   r   r   sqlalchemy.excr   r   sqlalchemy.schemar   sqlalchemy.sql.expressionr   sqlalchemy.typesr   r%   r0   r7   r9   r   r&   r$   <module>r9     sb    + " 	 P P P  * -  2 1 < ) 0 % ?D FvQ vQr&   