
    #j6                       d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZ dZ G d d	e          Z G d
 de          Z G d de          Z G d de          Ze
 G d d                      Zd8dZd9dZd:dZddd;dZ G d  d!          Zd<d#Zd=d%Z	 	 	 	 	 d>d?d/Zd@dAd1ZdBdCd3Zd@dDd4Z dEdFd6Z!eZ"g d7Z#dS )Gz
pg0 - Embedded PostgreSQL for Python

Usage:
    from pg0 import Pg0

    # Start PostgreSQL
    pg = Pg0()
    pg.start()
    print(pg.uri)
    pg.stop()

    # Or use context manager
    with Pg0() as pg:
        print(pg.uri)
    )annotationsN)	dataclass)Path)Optionalz0.1.0c                      e Zd ZdZdS )Pg0ErrorzBase exception for pg0 errors.N__name__
__module____qualname____doc__     T/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/pg0/__init__.pyr   r   "   s        ((Dr   r   c                      e Zd ZdZdS )Pg0NotFoundErrorz0pg0 binary not found and could not be installed.Nr	   r   r   r   r   r   '   s        ::Dr   r   c                      e Zd ZdZdS )Pg0NotRunningErrorz#PostgreSQL instance is not running.Nr	   r   r   r   r   r   ,   s        --Dr   r   c                      e Zd ZdZdS )Pg0AlreadyRunningErrorz'PostgreSQL instance is already running.Nr	   r   r   r   r   r   1   s        11Dr   r   c                      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<   dZ	d
ed<   dZ
d
ed<   dZd
ed<   edd            ZdS )InstanceInfoz(Information about a PostgreSQL instance.strnameboolrunningNOptional[int]pidportOptional[str]versionusernamedatabasedata_diruridatadictreturn'InstanceInfo'c                    | |                     dd          |                     dd          |                     d          |                     d          |                     d          |                     d          |                     d	          |                     d
          |                     d          	  	        S )Nr   defaultr   Fr   r   r!   r"   r#   r$   r%   )	r   r   r   r   r!   r"   r#   r$   r%   )get)clsr&   s     r   	from_dictzInstanceInfo.from_dictC   s    s&),,HHY..&!!HHY''XXj))XXj))XXj))

 

 

 
	
r   )r&   r'   r(   r)   )r
   r   r   r   __annotations__r   r   r!   r"   r#   r$   r%   classmethodr.   r   r   r   r   r   6   s         22IIIMMMCD!G!!!!"H"""""H"""""H""""C
 
 
 [
 
 
r   r   r(   Optional[Path]c                     t          t                    j        } t          j        dk    rdnd}| dz  |z  }|                                r|S dS )z5Get the path to the bundled pg0 binary, if it exists.win32pg0.exepg0binN)r   __file__parentsysplatformexists)package_dirbinary_namebundled_paths      r   _get_bundled_binaryr?   R   sS    x..'K"|w66))EK&4L 4r   r   c                     t           j        dk    rLt          t          j                            dt          j                    dz  dz                      } | dz  dz  S t          j                    dz  dz  S )z7Get the directory where pg0 binary should be installed.r3   LOCALAPPDATAAppDataLocalr5   r6   z.local)r9   r:   r   osenvironr,   home)bases    r   _get_install_dirrH   \   sc     |wBJNN>49;;3JW3TUUVVe|e##y{{X%--r   r   c                 "   t                      } | rt          |           S t          j        d          }|r|S t	                      }t
          j        dk    rdnd}||z  }|                                rt          |          S t          d          )z3Find the pg0 binary or raise an error if not found.r5   r3   r4   zpg0 binary not found. Install it with:
  curl -fsSL https://raw.githubusercontent.com/vectorize-io/pg0/main/install.sh | bash
Or download from: https://github.com/vectorize-io/pg0/releases)	r?   r   shutilwhichrH   r9   r:   r;   r   )bundledpathinstall_dirr=   binary_paths        r   	_find_pg0rP   f   s     "##G 7|| <D  #$$K"|w66))EK+K  ; 	I  r   TcheckargsrR   r   subprocess.CompletedProcessc                   t                      }	 t          j        dk    rt          j                    5 }t          j                    5 }t          j        |g|||          }|                    d           |                    d           |                                	                    dd          }|                                	                    dd          }ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          j
        |g||||          }nt          j        |g|d	d	
          }| r|j        dk    r|j                                        }d|                                v rt!          |          d|                                v sd|                                v rt#          |          t%          |p	d|j                   |S # t&          $ r t)          d          w xY w)zRun a pg0 command.r3   )stdoutstderrr   zutf-8replace)errorsN)rS   
returncoderV   rW   T)capture_outputtextzalready runningzno running instanceznot runningzpg0 command failed with code zpg0 binary not found)rP   r9   r:   tempfileTemporaryFile
subprocesscallseekreaddecodeCompletedProcessrunrZ   rW   striplowerr   r   r   FileNotFoundErrorr   )	rR   rS   pg0_pathout_ferr_frcrV   rW   results	            r   _run_pg0rn      s   {{H(7<7"" ')) 	HUH4J4L4L 	HPU_%%    
 

1

1,,WY,GG,,WY,GG	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H  0&&	  FF  ^!D!#  F
  	^V&!++]((**F FLLNN22,V444&&,,..88MV\\^^<[<[(000v\)\IZ)\)\]]] 7 7 756667sT   $G$ DBC+D+C/	/D2C/	3D6G$ DG$ 	D
CG$ $G>c                      e Zd ZdZ	 	 	 	 	 	 	 d'd(dZd)dZd*dZd+d,dZd)dZe	d-d            Z
e	d.d            Zd/dZd0d!Zd1d2d#Zd3d%Zd*d&ZdS )4Pg0a  
    Embedded PostgreSQL instance.

    Args:
        name: Instance name (allows multiple instances)
        port: Port to listen on (None = auto-select available port)
        username: Database username
        password: Database password
        database: Database name
        data_dir: Custom data directory
        config: Dict of PostgreSQL configuration options

    Example:
        # Simple usage (auto-selects available port)
        pg = Pg0()
        pg.start()
        print(pg.uri)
        pg.stop()

        # Context manager with specific port
        with Pg0(port=5433, database="myapp") as pg:
            print(pg.uri)

        # Custom config
        pg = Pg0(config={"shared_buffers": "512MB"})
    r+   Npostgresr   r   r   r   r"   passwordr#   r$   r    configOptional[dict[str, str]]c                l    || _         || _        || _        || _        || _        || _        |pi | _        d S N)r   r   r"   rr   r#   r$   rs   )selfr   r   r"   rr   r#   r$   rs   s           r   __init__zPg0.__init__   s=     		    lr   r(   r   c           	        dd| j         d| j        d| j        d| j        g	}| j        )|                    dt          | j                  g           | j        r|                    d| j        g           | j        	                                D ]!\  }}|                    d	| d
| g           "t          |  |                                 S )z
        Start the PostgreSQL instance.

        Returns:
            InstanceInfo with connection details

        Raises:
            Pg0AlreadyRunningError: If instance is already running
            Pg0Error: If start fails
        start--namez
--usernamez
--passwordz
--databaseNz--portz
--data-dir-c=)r   r"   rr   r#   r   extendr   r$   rs   itemsrn   info)rw   rS   keyvalues       r   rz   z	Pg0.start   s     di$-$-$-
 9 KK3ty>>2333= 	7KKt}5666+++-- 	2 	2JCKK#////01111$yy{{r   Nonec                6    t          dd| j        d           dS )zv
        Stop the PostgreSQL instance.

        Note: Does not raise an error if the instance is not running.
        stopr{   FrQ   Nrn   r   rw   s    r   r   zPg0.stop   s#     	49E::::::r   Tforcer   c                `    dd| j         g}|r|                    d           t          |ddi dS )a  
        Drop the PostgreSQL instance (stop if running, delete all data).

        Args:
            force: Skip confirmation prompt (default True for programmatic use)

        Warning:
            This permanently deletes all data for this instance!
        dropr{   --forcerR   FN)r   appendrn   )rw   r   rS   s      r   r   zPg0.drop  sE     $), 	#KK	"""$$e$$$$$r   c                    t          dd| j        ddd          }t          j        |j                  }t
                              |          S )z
        Get information about the PostgreSQL instance.

        Returns:
            InstanceInfo with current status and connection details
        r   r{   -ojsonFrQ   )rn   r   r   loadsrV   r   r.   )rw   rm   r&   s      r   r   zPg0.info  sE     &(DItV5QQQz&-((%%d+++r   c                4    |                                  j        S )z"Get the connection URI if running.)r   r%   r   s    r   r%   zPg0.uri  s     yy{{r   c                4    |                                  j        S )z!Check if the instance is running.)r   r   r   s    r   r   zPg0.running$  s     yy{{""r   rS   rT   c                *    t          dd| j        g|R  S )a6  
        Run psql with the given arguments.

        Args:
            *args: Arguments to pass to psql (e.g., "-c", "SELECT 1")

        Returns:
            CompletedProcess with stdout/stderr

        Example:
            result = pg.psql("-c", "SELECT version();")
            print(result.stdout)
        psqlr{   r   )rw   rS   s     r   r   zPg0.psql)  s      $);d;;;;r   sqlc                <    |                      d|          }|j        S )z
        Execute a SQL command and return the output.

        Args:
            sql: SQL command to execute

        Returns:
            Command output as string

        Example:
            output = pg.execute("SELECT version();")
        r|   )r   rV   )rw   r   rm   s      r   executezPg0.execute9  s     4%%}r   linesc                    dd| j         g}|$|                    dt          |          g           t          |ddi}|j        S )z
        Get PostgreSQL logs for this instance.

        Args:
            lines: Number of lines to return (None = all logs)

        Returns:
            Log content as string

        Example:
            print(pg.logs(50))  # Last 50 lines
        logsr{   N-nrR   F)r   r~   r   rn   rV   )rw   r   rS   rm   s       r   r   zPg0.logsI  sO     $),KKs5zz*+++4-u--}r   'Pg0'c                .    |                                   | S )z*Context manager entry - starts PostgreSQL.)rz   r   s    r   	__enter__zPg0.__enter__\  s    

r   c                R    	 |                                   dS # t          $ r Y dS w xY w)z(Context manager exit - stops PostgreSQL.N)r   r   )rw   exc_typeexc_valexc_tbs       r   __exit__zPg0.__exit__a  s:    	IIKKKKK! 	 	 	DD	s    
&&)r+   Nrq   rq   rq   NN)r   r   r   r   r"   r   rr   r   r#   r   r$   r    rs   rt   )r(   r   )r(   r   )T)r   r   r(   r   )r(   r    )r(   r   )rS   r   r(   rT   )r   r   r(   r   rv   )r   r   r(   r   )r(   r   )r
   r   r   r   rx   rz   r   r   r   propertyr%   r   r   r   r   r   r   r   r   r   rp   rp      sL        : """""&+/# # # # #$   >; ; ; ;% % % % %	, 	, 	, 	,    X # # # X#< < < <         &   
     r   rp   list[InstanceInfo]c                 r    t          dddd          } t          j        | j                  }d |D             S )zd
    List all pg0 instances.

    Returns:
        List of InstanceInfo for all known instances
    listr   r   FrQ   c                B    g | ]}t                               |          S r   )r   r.   ).0items     r   
<listcomp>z"list_instances.<locals>.<listcomp>r  s&    :::TL""4((:::r   )rn   r   r   rV   )rm   r&   s     r   list_instancesr   i  s?     fdF%888F:fm$$D::T::::r   	list[str]c                     t          dd          } | j                                                            d          }d |D             S )z
    List available PostgreSQL extensions.

    Returns:
        List of available extension names

    Example:
        extensions = pg0.list_extensions()
        print(extensions)  # ['vector', 'postgis', ...]
    zlist-extensionsFrQ   
c                ^    g | ]*}|                                 |                                 +S r   )rf   )r   lines     r   r   z#list_extensions.<locals>.<listcomp>  s-    ;;;Tdjjll;DJJLL;;;r   )rn   rV   rf   split)rm   r   s     r   list_extensionsr   u  sL     'u555FM!!''--E;;U;;;;r   r+   rq   r   r   r   r"   rr   r#   rs   c                T    t          | |||||          }|                                S )a  
    Start a PostgreSQL instance (convenience function).

    Args:
        name: Instance name
        port: Port to listen on (None = auto-select available port)
        username: Database username
        password: Database password
        database: Database name
        **config: PostgreSQL configuration options

    Returns:
        InstanceInfo with connection details

    Example:
        info = pg0.start(shared_buffers="512MB")  # auto-selects port
        print(info.uri)
    )r   r   r"   rr   r#   rs   )rp   rz   )r   r   r"   rr   r#   rs   pgs          r   rz   rz     s:    4 

 
 
B 88::r   r   c                ,    t          dd| d           dS )zk
    Stop a PostgreSQL instance (convenience function).

    Args:
        name: Instance name to stop
    r   r{   FrQ   N)rn   )r   s    r   r   r     s!     VXt5111111r   r   c                V    dd| g}|r|                     d           t          |ddi dS )a;  
    Drop a PostgreSQL instance (convenience function).

    Stops the instance if running and deletes all data.

    Args:
        name: Instance name to drop
        force: Skip confirmation prompt (default True for programmatic use)

    Warning:
        This permanently deletes all data for this instance!
    r   r{   r   rR   FN)r   rn   )r   r   rS   s      r   r   r     sC     Hd#D Id %     r   c                    t          dd| ddd          }t          j        |j                  }t                              |          S )z
    Get information about a PostgreSQL instance (convenience function).

    Args:
        name: Instance name

    Returns:
        InstanceInfo with current status
    r   r{   r   r   FrQ   )rn   r   r   rV   r   r.   )r   rm   r&   s      r   r   r     sC     fhdF%HHHF:fm$$D!!$'''r   r   c                ~    dd| g}|$|                     dt          |          g           t          |ddi}|j        S )z
    Get PostgreSQL logs for an instance (convenience function).

    Args:
        name: Instance name
        lines: Number of lines to return (None = all logs)

    Returns:
        Log content as string
    r   r{   Nr   rR   F)r~   r   rn   rV   )r   r   rS   rm   s       r   r   r     sM     Hd#DT3u::&'''t)5))F=r   )rp   
PostgreSQLr   r   r   r   r   r   r   rz   r   r   r   r   r?   )r(   r1   )r(   r   )r(   r   )rS   r   rR   r   r(   rT   )r(   r   )r(   r   )r+   Nrq   rq   rq   )r   r   r   r   r"   r   rr   r   r#   r   rs   r   r(   r   )r+   )r   r   r(   r   )r+   T)r   r   r   r   r(   r   )r   r   r(   r   )r+   N)r   r   r   r   r(   r   )$r   
__future__r   r   rD   rJ   r_   r]   r9   dataclassesr   pathlibr   typingr   __version__	Exceptionr   r   r   r   r   r?   rH   rP   rn   rp   r   r   rz   r   r   r   r   r   __all__r   r   r   <module>r      s   " # " " " " "  				       



 ! ! ! ! ! !             	 	 	 	 	y 	 	 	
	 	 	 	 	x 	 	 	
	 	 	 	 	 	 	 	
	 	 	 	 	X 	 	 	
 
 
 
 
 
 
 
 
6   . . . .   8 (, +7 +7 +7 +7 +7 +7\v v v v v v v vr	; 	; 	; 	;< < < <" " " " " "J2 2 2 2 2! ! ! ! !&( ( ( ( (    & 
  r   