B
    3¢\)"  ã               @   sŠ   d Z ddlZddlZyddlZW n  ek
r@   ddlmZ Y nX ddlmZm	Z	 ddl
mZ ddlmZ ddlmZ G dd	„ d	eƒZdS )
zA base class session manager.é    N)Údbapi2)ÚgenÚweb)ÚLoggingConfigurable)Úunicode_type)ÚInstancec               @   sÀ   e Zd ZedƒZedƒZdZdZdddddhZe	d	d
„ ƒZ
e	dd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zejd%dd„ƒZejdd„ ƒZd&dd„Zdd„ Zdd„ Zdd „ Zd!d"„ Zejd#d$„ ƒZdS )'ÚSessionManagerz<notebook.services.kernels.kernelmanager.MappingKernelManagerz2notebook.services.contents.manager.ContentsManagerNÚ
session_idÚpathÚnameÚtypeÚ	kernel_idc             C   s(   | j dkr"| j ¡ | _ | j  d¡ | j S )z5Start a cursor and create a database called 'session'NzOCREATE TABLE session 
                (session_id, path, name, type, kernel_id))Ú_cursorÚ
connectionÚcursorÚexecute)Úself© r   úHlib/python3.7/site-packages/notebook/services/sessions/sessionmanager.pyr       s
    
zSessionManager.cursorc             C   s&   | j dkr t d¡| _ tj| j _| j S )zStart a database connectionNz:memory:)Ú_connectionÚsqlite3ZconnectZRowZrow_factory)r   r   r   r   r   )   s    

zSessionManager.connectionc             C   s   | j dk	r| j  ¡  d| _ dS )zClose the sqlite connectionN)r   Úclose)r   r   r   r   r   1   s    

zSessionManager.closec             C   s   |   ¡  dS )z+Close connection once SessionManager closesN)r   )r   r   r   r   Ú__del__7   s    zSessionManager.__del__c             C   s.   | j  d|f¡ | j  ¡ }|dkr&dS dS dS )z2Check to see if the session of a given name existsz"SELECT * FROM session WHERE path=?NFT)r   r   Úfetchone)r   r
   Zreplyr   r   r   Úsession_exists;   s
    
zSessionManager.session_existsc             C   s   t t ¡ ƒS )zCreate a uuid for a new session)r   ÚuuidZuuid4)r   r   r   r   Únew_session_idD   s    zSessionManager.new_session_idc          	   c   sZ   |   ¡ }|dk	r|| jkrn|  |||||¡V }t | j|||||d¡V }t |¡‚dS )z'Creates a session and returns its modelN)r
   r   r   r   )r   Úkernel_managerÚstart_kernel_for_sessionr   Úmaybe_futureÚsave_sessionÚReturn)r   r
   r   r   Úkernel_namer   r	   Úresultr   r   r   Úcreate_sessionH   s    zSessionManager.create_sessionc             c   s4   | j j|d}t | jj||d¡V }t |¡‚dS )z'Start a new kernel for a given session.)r
   )r
   r"   N)Úcontents_managerZget_kernel_pathr   r   r   Zstart_kernelr!   )r   r	   r
   r   r   r"   Zkernel_pathr   r   r   r   r   V   s    z'SessionManager.start_kernel_for_sessionc             C   s$   | j  d|||||f¡ | j|dS )aü  Saves the items for the session with the given session_id
        
        Given a session_id (and any other of the arguments), this method
        creates a row in the sqlite session database that holds the information
        for a session.
        
        Parameters
        ----------
        session_id : str
            uuid for the session; this method must be given a session_id
        path : str
            the path for the given session
        name: str
            the name of the session
        type: string
            the type of the session
        kernel_id : str
            a uuid for the kernel associated with this session
        
        Returns
        -------
        model : dict
            a dictionary of the session model
        z&INSERT INTO session VALUES (?,?,?,?,?))r	   )r   r   Úget_session)r   r	   r
   r   r   r   r   r   r   r    a   s    zSessionManager.save_sessionc       	      K   sä   |st dƒ‚g }x2| ¡ D ]&}|| jkr2t d|ƒ‚| d| ¡ qW dd |¡ }| j |t| ¡ ƒ¡ y| j 	¡ }W n t
k
rŽ   d}Y nX |dkrÚg }x&| ¡ D ]\}}| d||f ¡ q¦W t dd	d
 |¡ ¡‚|  |¡S )aO  Returns the model for a particular session.
        
        Takes a keyword argument and searches for the value in the session
        database, then returns the rest of the session's info.

        Parameters
        ----------
        **kwargs : keyword argument
            must be given one of the keywords and values from the session database
            (i.e. session_id, path, name, type, kernel_id)

        Returns
        -------
        model : dict
            returns a dictionary that includes all the information from the 
            session described by the kwarg.
        zmust specify a column to queryzNo such column: %rz%s=?zSELECT * FROM session WHERE %sz AND Nz%s=%ri”  zSession not found: %sz, )Ú	TypeErrorÚkeysÚ_columnsÚappendÚjoinr   r   ÚlistÚvaluesr   ÚKeyErrorÚitemsr   Z	HTTPErrorÚrow_to_model)	r   ÚkwargsZ
conditionsÚcolumnÚqueryÚrowÚqÚkeyÚvaluer   r   r   r&      s&    


zSessionManager.get_sessionc             K   s|   | j |d |sdS g }x4| ¡ D ](}|| jkr<td| ƒ‚| d| ¡ q"W dd |¡ }| j |t| 	¡ ƒ|g ¡ dS )a  Updates the values in the session database.
        
        Changes the values of the session with the given session_id
        with the values from the keyword arguments. 
        
        Parameters
        ----------
        session_id : str
            a uuid that identifies a session in the sqlite3 database
        **kwargs : str
            the key must correspond to a column title in session database,
            and the value replaces the current value in the session 
            with session_id.
        )r	   NzNo such column: %rz%s=?z(UPDATE session SET %s WHERE session_id=?z, )
r&   r(   r)   r'   r*   r+   r   r   r,   r-   )r   r	   r1   Zsetsr2   r3   r   r   r   Úupdate_session¬   s    
zSessionManager.update_sessionc             C   sx   |d | j kr&| j d|d f¡ t‚|d |d |d |d | j  |d ¡dœ}|d dkrt|d |d d	œ|d< |S )
z@Takes sqlite database session row and turns it into a dictionaryr   z&DELETE FROM session WHERE session_id=?r	   r
   r   r   )Úidr
   r   r   ÚkernelZnotebook)r
   r   )r   r   r   r.   Zkernel_model)r   r4   Zmodelr   r   r   r0   É   s    zSessionManager.row_to_modelc          	   C   sP   | j  d¡}g }x:| ¡ D ].}y| |  |¡¡ W q tk
rF   Y qX qW |S )z_Returns a list of dictionaries containing all the information from
        the session databasezSELECT * FROM session)r   r   Zfetchallr*   r0   r.   )r   Úcr#   r4   r   r   r   Úlist_sessionsß   s    
zSessionManager.list_sessionsc             c   s<   | j |d}t | j |d d ¡¡V  | j d|f¡ dS )z=Deletes the row in the session database with given session_id)r	   r:   r9   z&DELETE FROM session WHERE session_id=?N)r&   r   r   r   Zshutdown_kernelr   r   )r   r	   Zsessionr   r   r   Údelete_sessioní   s    zSessionManager.delete_session)NNNNN)NNNN)Ú__name__Ú
__module__Ú__qualname__r   r   r%   r   r   r)   Úpropertyr   r   r   r   r   r   r   Ú	coroutiner$   r   r    r&   r8   r0   r<   r=   r   r   r   r   r      s(   		
-r   )Ú__doc__Úosr   r   ÚImportErrorZ	pysqlite2r   Ztornador   r   Ztraitlets.config.configurabler   Zipython_genutils.py3compatr   Z	traitletsr   r   r   r   r   r   Ú<module>   s   