
    h+$                     (   S SK r S SKrS SK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  S SKJr  S SKJr  \R(                  " \R*                  S9  \R,                  " \5      r\" S\S	S
S9rS rSS jrS r\R:                  S 5       r\R?                  S5      S 5       r \R?                  SS/S9S 5       r!\R?                  SS/S9S 5       r"\R?                  SS/S9S 5       r#\R?                  SS/S9S 5       r$\R?                  SS/S9S 5       r%g)     N)wraps)	Blueprintrequestjsonifyrender_templatecurrent_appResponse)inspecttext)SQLAlchemyError)client)level
db_browserz../templatesz	../static)template_folderstatic_folderc                 r   ^ U R                  5       R                  5       m/ SQn[        U4S jU 5       5      $ )z6A simple check to see if a query is a write operation.)insertupdatedeletecreatedropaltertruncatec              3   F   >#    U  H  nTR                  U5      v   M     g 7f)N)
startswith).0keyword	sql_lowers     */root/zotify-API/Gonk/GonkUI/db_browser.py	<genexpr>!is_write_query.<locals>.<genexpr>   s     KNy##G,,Ns   !)striplowerany)sqlwrite_keywordsr   s     @r   is_write_queryr'      s-    		!!#IZNKNKKK    c                     [        5       XU=(       d    0 S.n[        R                  S[        R                  " U5       35        g)z3Placeholder for a more robust audit logging system.)	timestampactionuserdetailszAUDIT: N)_get_timestamploginfojsondumps)r+   r,   r-   	log_entrys       r   	audit_logr4      s5    +-ZaZgeghIHHwtzz),-./r(   c                  J    SSK J n   U R                  5       R                  5       $ )Nr   datetime)r7   utcnow	isoformatr6   s    r   r.   r.   #   s    !??&&((r(   c                  N   [        [        S5      (       d  [        SSS.5      S4$ [        R                  (       d  [        SSS.5      S4$  [        R
                  " 5       n U R                  SS	5      [        l        g! [         a  n[        SS
U 3S.5      S4s SnA$ SnAff = f)z{
Apply checks to all routes in this blueprint.
This function is executed before each request to a route in this blueprint.
	db_engineerrorzDatabase engine not configured.statusmessage  zPAuthentication required. Please log in via the JWT panel on the main page first.i  usernameunknownz9Unauthorized: Invalid token. Please log in again. Error: N)
hasattrr   r   
jwt_clienttokenget_profilegetr   current_user	Exception)profilees     r   before_request_hookrL   )   s     ;,,'6WXY[^^^ i
   		} ((*  '{{:yA }'8qrsqt6uvwy|||}s   0A= =
B$BB$B$/c                      [        S5      $ )z)Render the main database browser UI page.zdb/index.html)r    r(   r   indexrP   J   s     ?++r(   z/tablesGET)methodsc                      [        [        R                  5      n U R                  5       n[	        S[
        R                  S[        U5      0S9  [        SUS.5      $ ! [         a  n[        SSU 3S.5      S	4s S
nA$ S
nAff = f)z,Return a list of all tables in the database.
get_tablestable_countr,   r-   success)r>   tablesr<   zFailed to retrieve tables: r=   r@   N)
r
   r   r;   get_table_namesr4   r   rH   lenr   r   )	inspectorrX   rK   s      r   rT   rT   O   s    _K112	**,,W%9%9MSVW]S^C_`)v>?? _'8STUSV6WXY[^^^_s   AA 
B'A?9B?Bz/schema/<table>c                 P    [        [        R                  5      nUR                  U 5      nU Vs0 s H  o3S   [	        US   5      _M     nn[        S[        R                  SU 0S9  [        SX@S.5      $ s  snf ! [         a   n[        SS	U  S
U 3S.5      S4s SnA$ SnAff = f)z$Return the schema for a given table.nametype
get_schematablerV   rW   )r>   schemar`   r<   z%Failed to retrieve schema for table '': r=   r@   N)
r
   r   r;   get_columnsstrr4   r   rH   r   r   )r`   r[   columnscolra   rK   s         r   r_   r_   Z   s    sK112	''.;BC7Cf+s3v;//7C,W%9%9GUCST)vNOO D  s'8]^c]ddghigj6klmorrrss.   .A; A6*A; 6A; ;
B%B B% B%z/table/<table>c           
      h   [         R                  R                  SS[        S9n[        R
                  R                  SS5      nUS-
  U-  n [        R                  R                  5        n[        SU  S35      nUR                  XRUS.5      nU Vs/ s H  n[        UR                  5      PM     nn[        S	[         R                  X[        U5      S
.S9  [        SXUS.5      sSSS5        $ s  snf ! , (       d  f       g= f! [          a   n	[        SSU  SU	 3S.5      S4s Sn	A	$ Sn	A	ff = f)z)Return rows from a table with pagination.page   )r^   DB_BROWSER_MAX_ROWSd   zSELECT * FROM "z" LIMIT :limit OFFSET :offset)limitoffsetget_table_rows)r`   rh   	row_countrV   rW   )r>   r`   rh   rowsNr<   z!Failed to fetch rows from table 'rb   r=   r@   )r   argsrG   intr   configr;   connectr   executedict_mappingr4   rH   rZ   r   r   )
r`   rh   max_rowsrm   
connectionqueryresultrowrp   rK   s
             r   rn   rn   f   s3    <<FAC0D!!%%&;SAHQh("Fo""**,
?5'1NOPE''V/TUF289&3D&&D9&W-A-AUZwz{  xA  LB  Ci%W[\] -, : -,  o'8YZ_Y``cdecf6ghiknnnosN   D +(C6C125C6'	D 1C66
D D D 
D1D,&D1,D1z/queryPOSTc            	      *   [         R                  n U R                  SS5      R                  5       nU R                  SS5      nU(       d  [	        SSS.5      S4$ [        U5      (       Ga1  U(       d  [	        S	S
S.5      S4$ Sn [        [        S5      (       aO  [        R                  (       a:  [        R                  R                  5       n[        S[         R                  SU0S9  O[        S[         R                  SS0S9  [        R                  R                  5        nUR                  5       nUR                  [!        U5      5      nUR#                  5         SSS5        [        S[         R                  XS.S9  [	        SSWR$                   3US.5      $  [        R                  R                  5        n[        R*                  R                  SS5      nSUR-                  5       ;  a  UR/                  S5       SU 3n	OUn	UR                  [!        U	5      5      nU V
s/ s H  n
[1        U
R2                  5      PM     nn
[        S [         R                  U[5        U5      S!.S9  [	        SUS"[5        U5       S#3S$.5      sSSS5        $ ! , (       d  f       GN<= f! [&        [(        4 a  n[	        SSU 3US.5      S4s SnA$ SnAff = fs  sn
f ! , (       d  f       g= f! [&         a  n[	        SSU 3S.5      S4s SnA$ SnAff = f)%z)Execute a SQL query against the database.r%    confirmFr<   zSQL query cannot be empty.r=     confirmation_requiredzLThis appears to be a write operation. Please confirm you want to execute it.zN/Adb_snapshot_providercreate_snapshotpathrV   create_snapshot_skippedreasonzNo provider configuredNexecute_write_query)r%   snapshot_pathrW   z2Write query executed successfully. Rows affected: )r>   r?   r   zQuery failed: r@   rj   rk   rl   ;z LIMIT execute_read_query)r%   ro   zQuery returned z rows.)r>   rp   r?   )r   r1   rG   r"   r   r'   rC   r   r   r   r4   rH   r;   rt   beginru   r   commitrowcountr   RuntimeErrorrs   r#   rstriprv   rw   rZ   )datar%   r   r   ry   transactionr{   rK   rx   sql_limitedr|   rp   s               r   	run_queryr   w   s    <<D
((5"

#
#
%Chhy%(G'6RSTVYYYc1i   
 	v{$:;;@`@` + @ @ P P R+'2F2FQWYfPgh3':N:NYac{X|}&&..0J(..0#++DI6""$ 1
 +'2F2FX[P|}#OPVP_P_O`a!.  	V&&..0J&--112GM#))+-%(ZZ_$5WXJ"GK"%K#++D,=>6<=fsS\\*f=.W5I5I[^mpqumvSwx)TP_`cdh`i_jjpNqrs 10! 10  . 	vgN1#:Nanopruuu	v > 10  	VgN1#:NOPRUUU	Vs   BJ$ ";J>J$ K+ ;A,K'KAK	K+ 
J!J$ $K4KKKK
K($K+ (K+ +
L5LLLz/exportc            	         [         R                  R                  S5      n [         R                  R                  SS5      nU (       d  [        SSS.5      S4$ [	        U 5      (       a  [        SSS.5      S4$  [
        R                  R                  5        nUR                  [        U 5      5      nU Vs/ s H  n[        UR                  5      PM     nnS	S	S	5        [        S
[         R                  X[        W5      S.S9  US:X  a~  SS	KnSSKJn  U(       d
  [%        SSS9$ U" 5       nUR'                  XS   R)                  5       S9n	U	R+                  5         U	R-                  U5        [%        UR/                  5       SSS0S9$ [%        [0        R2                  " USS9SSS0S9$ s  snf ! , (       d  f       N= f! [4         a  n
[        SSU
 3S.5      S4s S	n
A
$ S	n
A
ff = f)z$Export query results to CSV or JSON.r%   formatr1   r<   z SQL query parameter is required.r=   r   z&Cannot export data from a write query.Nexport_data)r%   r   ro   rV   csvr   )StringIOr   ztext/csv)mimetype)
fieldnameszContent-Dispositionzattachment;filename=export.csv)r   headers   )indentzapplication/jsonzattachment;filename=export.jsonzExport failed: r@   )r   rq   rG   r   r'   r   r;   rt   ru   r   rv   rw   r4   rH   rZ   r   ior   r	   
DictWriterkeyswriteheader	writerowsgetvaluer1   r2   r   )r%   fmtry   r{   r|   rp   r   r   outputwriterrK   s              r   r   r      s    ,,

5
!C
,,

8V
,C'6XYZ\___c'6^_`beeeS""**,
''S	2F289&3D&&D9 - 	-g&:&:CmpqumvDwx%<#Z88ZF^^FAw||~^FF T"!#.0PQ  

4*+.0QR - : -,:  S's6KLMsRRSsV   8F= F,5F'F,AF= $A"F= F= 'F,,
F:6F= =
G$GG$G$)rB   N)&osr1   logging	functoolsr   flaskr   r   r   r   r   r	   
sqlalchemyr
   r   sqlalchemy.excr   GonkUI.views.jwt_uir   rD   basicConfigINFO	getLogger__name__r/   db_browser_bpr'   r4   r.   before_requestrL   routerP   rT   r_   rn   r   r   rO   r(   r   <module>r      sr   	    U U $ * 5   ',, '! (N+L0
) } }@ S, , Y0_ 1_ &8	s 9	s %w7o 8o  Xx04V 14Vl Y0*S 1*Sr(   