o
    `^h[                     @   s   d dl Z d dlZd dlZd dlZd dlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ e de je jB ZG dd dZG d	d
 d
ZG dd deeZG dd dZG dd deeZG dd deZG dd deeZdS )    N)
WarningErrorInterfaceError	DataErrorDatabaseErrorOperationalErrorIntegrityErrorInternalErrorNotSupportedErrorProgrammingError   )logger)
FIELD_TYPEz|\s*((?:INSERT|REPLACE)\s.+\sVALUES?\s+)(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))(\s*(?:ON DUPLICATE.*)?);?\s*\Zc                   @   s  e Zd ZdZdZdLddZedd Zedd	 Zed
d Z	edd Z
edd Zejdd Zedd Zedd Zedd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& ZdMd(d)ZdMd*d+Zd,d- Zd.d/ ZdNd1d2Zd3d4 ZdMd5d6Zd7d8 ZdOd:d;Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$e%Z%e&Z&e'Z'e(Z(e)Z)e*Z*e+Z+e,Z,e-Z-e.Z.dDdE Z/dFdG Z0dHdI Z1dJdK Z2d'S )PCursorz-Cursor is used to interact with the database.i  Fc                 C   sJ   || _ | j j| _d| _d| _d| _d| _d| _d| _d| _	d| _
|| _dS )zfDo not create an instance of a Cursor yourself. Call
        connections.Connection.cursor().
        Nr   r   )_connectionloop_loop_description
_rownumber	_rowcount
_arraysize	_executed_result_rows
_lastrowid_echo)self
connectionecho r    N/home/air/shanriGPT/back/venv/lib/python3.10/site-packages/aiomysql/cursors.py__init__$   s   

zCursor.__init__c                 C      | j S )zmThis read-only attribute return a reference to the Connection
        object on which the cursor was created.r   r   r    r    r!   r   4   s   zCursor.connectionc                 C   r#   )a  This read-only attribute is a sequence of 7-item sequences.

        Each of these sequences is a collections.namedtuple containing
        information describing one result column:

        0.  name: the name of the column returned.
        1.  type_code: the type of the column.
        2.  display_size: the actual length of the column in bytes.
        3.  internal_size: the size in bytes of the column associated to
            this column on the server.
        4.  precision: total number of significant digits in columns of
            type NUMERIC. None for other types.
        5.  scale: count of decimal digits in the fractional part in
            columns of type NUMERIC. None for other types.
        6.  null_ok: always None as not easy to retrieve from the libpq.

        This attribute will be None for operations that do not
        return rows or if the cursor has not had an operation invoked
        via the execute() method yet.
        )r   r%   r    r    r!   description:   s   zCursor.descriptionc                 C   r#   )a  Returns the number of rows that has been produced of affected.

        This read-only attribute specifies the number of rows that the
        last :meth:`execute` produced (for Data Query Language
        statements like SELECT) or affected (for Data Manipulation
        Language statements like UPDATE or INSERT).

        The attribute is -1 in case no .execute() has been performed
        on the cursor or the row count of the last operation if it
        can't be determined by the interface.
        )r   r%   r    r    r!   rowcountR   s   zCursor.rowcountc                 C   r#   )zRow index.

        This read-only attribute provides the current 0-based index of the
        cursor in the result set or ``None`` if the index cannot be
        determined.
        )r   r%   r    r    r!   	rownumbera      	zCursor.rownumberc                 C   r#   )How many rows will be returned by fetchmany() call.

        This read/write attribute specifies the number of rows to
        fetch at a time with fetchmany(). It defaults to
        1 meaning to fetch a single row at a time.

        r   r%   r    r    r!   	arraysizel   r)   zCursor.arraysizec                 C   s
   || _ dS )r*   Nr+   )r   valr    r    r!   r,   w   s   
	c                 C   r#   )aj  This read-only property returns the value generated for an
        AUTO_INCREMENT column by the previous INSERT or UPDATE statement
        or None when there is no such value available. For example,
        if you perform an INSERT into a table that contains an AUTO_INCREMENT
        column, lastrowid returns the AUTO_INCREMENT value for the new row.
        )r   r%   r    r    r!   	lastrowid   s   zCursor.lastrowidc                 C   r#   )zReturn echo mode status.)r   r%   r    r    r!   r      s   zCursor.echoc                 C   s   | j sdS dS )zlThe readonly property that returns ``True`` if connections was
        detached from current cursor
        TFr$   r%   r    r    r!   closed   s   zCursor.closedc                    sT   | j }|du r
dS z|  I dH r 	 |  I dH sW d| _ dS W d| _ dS d| _ w )z2Closing a cursor just exhausts all remaining data.N)r   nextsetr   connr    r    r!   close   s   
zCursor.closec                 C   s   | j std| j S )NzCursor closed)r   r   r%   r    r    r!   _get_db   s   zCursor._get_dbc                 C   s   | j stdd S )Nzexecute() first)r   r   r%   r    r    r!   _check_executed   s   zCursor._check_executedc                 C   s   |S Nr    r   rowr    r    r!   	_conv_row      zCursor._conv_rowc                 G      dS z!Does nothing, required by DB API.Nr    r   argsr    r    r!   setinputsizes       zCursor.setinputsizesc                 G   r;   r<   r    r=   r    r    r!   setoutputsizes   r@   zCursor.setoutputsizesc                    s^   |   }| j}|du s||jurdS |jsdS d| _|   | I dH  |  I dH  dS )zGet the next query setNT)r4   r   has_next_clear_resultnext_result_do_get_result)r   r2   current_resultr    r    r!   r0      s   zCursor.nextsetc                    sN   t |ttfrt fdd|D S t |tr" fdd| D S  |S )Nc                 3   s    | ]}  |V  qd S r6   escape).0argr2   r    r!   	<genexpr>   s    z&Cursor._escape_args.<locals>.<genexpr>c                    s   i | ]
\}}|  |qS r    rG   )rI   keyr-   rK   r    r!   
<dictcomp>   s    z'Cursor._escape_args.<locals>.<dictcomp>)
isinstancetuplelistdictitemsrH   )r   r>   r2   r    rK   r!   _escape_args   s
   

zCursor._escape_argsNc                 C   s$   |   }|dur|| || }|S )a,   Returns the exact string that is sent to the database by calling
        the execute() method. This method follows the extension to the DB
        API 2.0 followed by Psycopg.

        :param query: ``str`` sql statement
        :param args: ``tuple`` or ``list`` of arguments for sql query
        N)r4   rT   r   queryr>   r2   r    r    r!   mogrify   s   zCursor.mogrifyc                    sx   |   }|  I dH r	 |  I dH s|dur || || }| |I dH  || _| jr9t| td| | jS )a  Executes the given operation

        Executes the given operation substituting any markers with
        the given parameters.

        For example, getting all rows where id is 5:
          cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))

        :param query: ``str`` sql statement
        :param args: ``tuple`` or ``list`` of arguments for sql query
        :returns: ``int``, number of rows that has been produced of affected
        N%r)	r4   r0   rT   _queryr   r   r   infor   rU   r    r    r!   execute   s   
zCursor.executec           	   	      s   |sdS | j rtd| td| t|}|rO|dd }|d }|dp/d}|d	 d
kr<|d dks>J | ||||| j| 	 j
I dH S d	}|D ]}| ||I dH  || j7 }qS|| _| jS )a  Execute the given operation multiple times

        The executemany() method will execute the operation iterating
        over the list of parameters in seq_params.

        Example: Inserting 3 new employees and their phone number

            data = [
                ('Jane','555-001'),
                ('Joe', '555-001'),
                ('John', '555-003')
                ]
            stmt = "INSERT INTO employees (name, phone) VALUES ('%s','%s')"
            await cursor.executemany(stmt, data)

        INSERT or REPLACE statements are optimized by batching the data,
        that is using the MySQL multiple rows syntax.

        :param query: `str`, sql statement
        :param args: ``tuple`` or ``list`` of arguments for sql query
        NCALL %srX   r   r           r   (r   ))r   r   rZ   RE_INSERT_VALUESmatchgrouprstrip_do_execute_manymax_stmt_lengthr4   encodingr[   r   )	r   rV   r>   mq_prefixq_values	q_postfixrowsrJ   r    r    r!   executemany   s,   

zCursor.executemanyc                    s&  |   }| j}t|tr||}t|tr||}t|}	t|}||t|| }
t|
tr8|
|d}
|	|
7 }	d}|D ]?}|||| }
t|
trT|
|d}
t|	t|
 t| d |krw| 	|	| I d H }||7 }t|}	n|	d7 }	|	|
7 }	q@| 	|	| I d H }||7 }|| _
|S )Nsurrogateescaper   r      ,)r4   rT   rO   strencode	bytearrayiternextlenr[   r   )r   prefixvaluespostfixr>   rg   rh   r2   rH   sqlvrm   rJ   rr    r    r!   rf   $  s8   





 

zCursor._do_execute_manyr    c                    s   |   }| jrtd  td| t|D ]\}}d |||f }| |I dH  |  I dH  qd fddt	t
|D }d  d	| d
}| |I dH  || _|S )a+  Execute stored procedure procname with args

        Compatibility warning: PEP-249 specifies that any modified
        parameters must be returned. This is currently impossible
        as they are only available by storing them in a server
        variable and then retrieved by a query. Since stored
        procedures return zero or more result sets, there is no
        reliable way to get at OUT or INOUT parameters via callproc.
        The server variables are named @_procname_n, where procname
        is the parameter above and n is the position of the parameter
        (from zero). Once all result sets generated by the procedure
        have been fetched, you can issue a SELECT @_procname_0, ...
        query using .execute() to get any OUT or INOUT values.

        Compatibility warning: The act of calling a stored procedure
        itself creates an empty result set. This appears after any
        result sets generated by the procedure. This is non-standard
        behavior with respect to the DB-API. Be sure to use nextset()
        to advance through all result sets; otherwise you may get
        disconnected.

        :param procname: ``str``, name of procedure to execute on server
        :param args: `sequence of parameters to use with procedure
        :returns: the original args.
        r\   rX   zSET @_%s_%d=%sN,c                 3   s    | ]	}d  |f V  qdS )z@_%s_%dNr    )rI   iprocnamer    r!   rL   g  s    z"Cursor.callproc.<locals>.<genexpr>zCALL r`   ra   )r4   r   r   rZ   	enumeraterH   rY   r0   joinrangerv   r   )r   r   r>   r2   indexrJ   q_argsr    r   r!   callprocC  s    zCursor.callprocc                 C   sl   |    | j }| jdu s| jt| jkr|d |S | j| j }|  jd7  _| j }|| |S )zFetch the next row Nr   )r5   r   create_futurer   r   rv   
set_resultr   futresultr    r    r!   fetchonem  s   



zCursor.fetchonec                 C   sj   |    | j }| jdu r|g  |S | j|p| j }| j| j| }t|t| j| _|| |S )n  Returns the next set of rows of a query result, returning a
        list of tuples. When no more rows are available, it returns an
        empty list.

        The number of rows returned can be specified using the size argument,
        which defaults to one

        :param size: ``int`` number of rows to return
        :returns: ``list`` of fetched rows
        N)	r5   r   r   r   r   r   r   minrv   )r   sizer   endr   r    r    r!   	fetchmany|  s   



zCursor.fetchmanyc                 C   sb   |    | j }| jdu r|g  |S | jr!| j| jd }n| j}t| j| _|| |S )z[Returns all rows of a query result set

        :returns: ``list`` of fetched rows
        N)r5   r   r   r   r   r   rv   r   r    r    r!   fetchall  s   



zCursor.fetchallrelativec                 C   s~   |    |dkr| j| }n|dkr|}ntd| d|  kr+t| jk s0td td|| _| j }|d |S )a  Scroll the cursor in the result set to a new position according
         to mode.

        If mode is relative (default), value is taken as offset to the
        current position in the result set, if set to absolute, value
        states an absolute target position. An IndexError should be raised in
        case a scroll operation would leave the result set. In this case,
        the cursor position is left undefined (ideal would be to
        not move the cursor at all).

        :param int value: move cursor to next position according to mode.
        :param str mode: scroll mode, possible modes: `relative` and `absolute`
        r   absoluteunknown scroll mode %sr   zout of rangeN)	r5   r   r   rv   r   
IndexErrorr   r   r   )r   valuemoder|   r   r    r    r!   scroll  s   

zCursor.scrollc                    s:   |   }|| _|   ||I d H  |  I d H  d S r6   )r4   _last_executedrC   rV   rE   r   r   r2   r    r    r!   rY     s   zCursor._queryc                 C   s(   d| _ d | _d| _d | _d | _d | _d S Nr   )r   r   r   r   r   r   r%   r    r    r!   rC     s   
zCursor._clear_resultc                    s^   |   }d| _|j | _}|j| _|j| _|j| _|j	| _
|jdkr-| |I d H  d S d S r   )r4   r   r   affected_rowsr   r&   r   	insert_idr   rm   r   warning_count_show_warnings)r   r2   r   r    r    r!   rE     s   
zCursor._do_get_resultc                    sV   | j r
| j jr
d S | I d H }|d u rd S |D ]}|d }tt|td qd S )Nr      )r   rB   show_warningswarningswarnrq   r   )r   r2   wswmsgr    r    r!   r     s   zCursor._show_warningsc                 C   s   | S r6   r    r%   r    r    r!   	__aiter__  r:   zCursor.__aiter__c                    s    |   I d H }|d ur|S tr6   )r   StopAsyncIteration)r   retr    r    r!   	__anext__  s
   zCursor.__anext__c                    s   | S r6   r    r%   r    r    r!   
__aenter__   s   zCursor.__aenter__c                    s   |   I d H  d S r6   )r3   )r   exc_typeexc_valexc_tbr    r    r!   	__aexit__  s   zCursor.__aexit__)Fr6   )r    r   )3__name__
__module____qualname____doc__rg   r"   propertyr   r&   r'   r(   r,   setterr.   r   r/   r3   r4   r5   r9   r?   rA   r0   rT   rW   r[   rn   rf   r   r   r   r   r   rY   rC   rE   r   r   r   r   r   r   r   r   r	   r   r
   r   r   r   r   r    r    r    r!   r      sr    










	




.
*

	
r   c                       s0   e Zd Z fddZdd Z fddZ  ZS )_DeserializationCursorMixinc                    s6   t   I d H   jr fdd jD  _d S d S )Nc                       g | ]}  |qS r    )_deserialization_rowrI   r|   r%   r    r!   
<listcomp>      z>_DeserializationCursorMixin._do_get_result.<locals>.<listcomp>)superrE   r   r%   	__class__r%   r!   rE   	  s
   z*_DeserializationCursorMixin._do_get_resultc              	   C   s   |d u rd S t |trd}nt|}d}t| jD ]1\}^}}}|tjkrJ|r)|n|}tt	t
 t|| ||< W d    n1 sEw   Y  q|rO|S t|S )NTF)rO   rR   rQ   r   r   r   JSON
contextlibsuppress
ValueError	TypeErrorjsonloadsrP   )r   r8   	dict_flagr   name
field_typenpointr    r    r!   r     s    

z0_DeserializationCursorMixin._deserialization_rowc                    s"   |d u rd S t  |}| |S r6   )r   r9   r   r7   r   r    r!   r9      s   
z%_DeserializationCursorMixin._conv_row)r   r   r   rE   r   r9   __classcell__r    r    r   r!   r     s    r   c                   @      e Zd ZdZdS )DeserializationCursorz6A cursor automatic deserialization of json type fieldsNr   r   r   r   r    r    r    r!   r   '      r   c                       s,   e Zd ZeZ fddZ fddZ  ZS )_DictCursorMixinc                    s   t   I d H  g } jr+ jjD ]}|j}||v r"|jd | }|| q| _|r= j	r? fdd j	D  _	d S d S d S )N.c                    r   r    )r9   r   r%   r    r!   r   ;  r   z3_DictCursorMixin._do_get_result.<locals>.<listcomp>)
r   rE   r   r   fieldsr   
table_nameappend_fieldsr   )r   r   fr   r   r%   r!   rE   /  s   
z_DictCursorMixin._do_get_resultc                    s*   |d u rd S t  |}| t| j|S r6   )r   r9   	dict_typezipr   r7   r   r    r!   r9   =  s   z_DictCursorMixin._conv_row)r   r   r   rR   r   rE   r9   r   r    r    r   r!   r   +  s    r   c                   @   r   )
DictCursorz.A cursor which returns results as a dictionaryNr   r    r    r    r!   r   D  r   r   c                   @   sL   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdddZ	dddZ
dS )SSCursora  Unbuffered Cursor, mainly useful for queries that return a lot of
    data, or for connections to remote servers over a slow network.

    Instead of copying every row of data into a buffer, this will fetch
    rows as needed. The upside of this, is the client uses much less memory,
    and rows are returned much faster when traveling over a slow network,
    or if the result set is very big.

    There are limitations, though. The MySQL protocol doesn't support
    returning the total number of rows, so the only way to tell how many rows
    there are is to iterate over every row returned. Also, it currently isn't
    possible to scroll backwards, as only the current row is held in memory.
    c                    sz   | j }|d u r
d S | jd ur| j|ju r| j I d H  z|  I d H r3	 |  I d H s%W d | _ d S W d | _ d S d | _ w r6   )r   r   _finish_unbuffered_queryr0   r1   r    r    r!   r3   W  s   
zSSCursor.closec                    s8   |   }|| _|j|ddI d H  |  I d H  | jS )NT)
unbuffered)r4   r   rV   rE   r   r   r    r    r!   rY   e  s   zSSCursor._queryc                    s    | j  I dH }| |}|S )zRead next row N)r   _read_rowdata_packet_unbufferedr9   r7   r    r    r!   
_read_nextl  s   
zSSCursor._read_nextc                    s6   |    |  I dH }|du rdS |  jd7  _|S )z Fetch next row Nr   )r5   r   r   r7   r    r    r!   r   r  s   zSSCursor.fetchonec                    s0   g }	 |   I dH }|du r	 |S || q)z`Fetch all, as per MySQLdb. Pretty useless for large queries, as
        it is buffered.
        TN)r   r   )r   rm   r8   r    r    r!   r   {  s   
zSSCursor.fetchallNc                    sb   |    |du r| j}g }t|D ]}|  I dH }|du r" |S || |  jd7  _q|S )r   Nr   )r5   r   r   r   r   r   )r   r   rm   r~   r8   r    r    r!   r     s   
zSSCursor.fetchmanyr   c                    s   |    |dkr(|dk rtdt|D ]	}|  I dH  q|  j|7  _dS |dkrM|| jk r5td|| j }t|D ]	}|  I dH  q>|| _dS td| )a  Scroll the cursor in the result set to a new position
        according to mode . Same as :meth:`Cursor.scroll`, but move cursor
        on server side one by one row. If you want to move 20 rows forward
        scroll will make 20 queries to move cursor. Currently only forward
        scrolling is supported.

        :param int value: move cursor to next position according to mode.
        :param str mode: scroll mode, possible modes: `relative` and `absolute`
        r   r   z0Backwards scrolling not supported by this cursorNr   r   )r5   r
   r   r   r   r   )r   r   r   _r   r    r    r!   r     s$   


zSSCursor.scrollr6   r   )r   r   r   r   r3   rY   r   r   r   r   r   r    r    r    r!   r   H  s    	
r   c                   @   r   )SSDictCursorz<An unbuffered cursor, which returns results as a dictionary Nr   r    r    r    r!   r     r   r   )rer   r   r   pymysql.errr   r   r   r   r   r   r   r	   r
   r   logr   r   r   compile
IGNORECASEDOTALLrb   r   r   r   r   r   r   r   r    r    r    r!   <module>   s*    0
   qy