3
g`                 @   s   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	Z	d dl
mZ d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlm Z  dZ!G dd dZ"dS )    N)deque)contextmanager)settings)ImproperlyConfigured)DEFAULT_DB_ALIASDatabaseError)utils)BaseDatabaseValidation)connection_created)TransactionManagementError)DatabaseErrorWrapper)timezone)async_unsafe)cached_propertyZ	__no_db__c               @   s~  e Zd ZdZi Zi Zi ZdZdZdZ	dZ
dZdZdZdZdZeZdZefddZdd Ze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dZe dd Z!dd Z"e dd Z#dd  Z$d}d!d"Z%d#d$ Z&d%d& Z'd'd( Z(e d)d* Z)e d+d, Z*e d-d. Z+e d/d0 Z,d1d2 Z-d3d4 Z.d5d6 Z/d7d8 Z0e d9d: Z1e d;d< Z2e d=d> Z3e d?d@ Z4dAdB Z5dCdD Z6d~dFdGZ7dHdI Z8dJdK Z9dLdM Z:dNdO Z;e<dPdQ Z=dRdS Z>dTdU Z?ddVdWZ@dXdY ZAdZd[ ZBed\d] ZCd^d_ ZDd`da ZEdbdc ZFddde ZGedfdg ZHdhdi ZIdjdk ZJdldm ZKe<dndo ZLe<dpdq ZMdrds ZNdtdu ZOdvdw ZPe<dxdy ZQddzd{ZRdS )BaseDatabaseWrapperz Represent a database connection.Nunknowni(#  c             C   s   d | _ || _|| _t| jd| _d| _d| _d| _d| _	g | _
d| _d| _d | _d| _d| _tj | _d| _tj | _g | _d| _g | _| j| | _| j| | _| j| | _| j | | _!| j"| | _#| j$| | _%d S )N)maxlenFr   T)&
connectionsettings_dictaliasr   queries_limitqueries_logforce_debug_cursor
autocommitin_atomic_blocksavepoint_statesavepoint_idsZcommit_on_exitneeds_rollbackclose_atclosed_in_transactionerrors_occurred	threadingLock_thread_sharing_lock_thread_sharing_count_thread	get_ident_thread_identrun_on_commit%run_commit_hooks_on_set_autocommit_onexecute_wrappersclient_classclientcreation_classZcreationfeatures_classfeaturesintrospection_classZintrospection	ops_classopsvalidation_classZ
validation)selfr   r    r5   Z/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/db/backends/base/base.py__init__0   s4    

zBaseDatabaseWrapper.__init__c             C   s   dS )z
        Ensure the connection's timezone is set to `self.timezone_name` and
        return whether it changed or not.
        Fr5   )r4   r5   r5   r6   ensure_timezonen   s    z#BaseDatabaseWrapper.ensure_timezonec             C   s2   t js
dS | jd dkrtjS tj| jd S dS )a  
        Return a tzinfo of the database connection time zone.

        This is only used when time zone support is enabled. When a datetime is
        read from the database, it is always returned in this time zone.

        When the database backend supports time zones, it doesn't matter which
        time zone Django uses, as long as aware datetimes are used everywhere.
        Other users connecting to the database can choose their own time zone.

        When the database backend doesn't support time zones, the time zone
        Django uses may be constrained by the requirements of other users of
        the database.
        N	TIME_ZONE)r   USE_TZr   r   utcpytz)r4   r5   r5   r6   r   u   s
    zBaseDatabaseWrapper.timezonec             C   s,   t jst jS | jd dkrdS | jd S dS )zC
        Name of the time zone of the database connection.
        r9   NUTC)r   r:   r9   r   )r4   r5   r5   r6   timezone_name   s
    z!BaseDatabaseWrapper.timezone_namec             C   s   | j p
tjS )N)r   r   DEBUG)r4   r5   r5   r6   queries_logged   s    z"BaseDatabaseWrapper.queries_loggedc             C   s0   t | j| jjkr&tjdj| jj t| jS )NzLLimit for query logging exceeded, only the last {} queries will be returned.)lenr   r   warningswarnformatlist)r4   r5   r5   r6   queries   s
    zBaseDatabaseWrapper.queriesc             C   s   t ddS )z<Return a dict of parameters suitable for get_new_connection.zNsubclasses of BaseDatabaseWrapper may require a get_connection_params() methodN)NotImplementedError)r4   r5   r5   r6   get_connection_params   s    z)BaseDatabaseWrapper.get_connection_paramsc             C   s   t ddS )z"Open a connection to the database.zKsubclasses of BaseDatabaseWrapper may require a get_new_connection() methodN)rG   )r4   conn_paramsr5   r5   r6   get_new_connection   s    z&BaseDatabaseWrapper.get_new_connectionc             C   s   t ddS )z,Initialize the database connection settings.zOsubclasses of BaseDatabaseWrapper may require an init_connection_state() methodN)rG   )r4   r5   r5   r6   init_connection_state   s    z)BaseDatabaseWrapper.init_connection_statec             C   s   t ddS )z9Create a cursor. Assume that a connection is established.zFsubclasses of BaseDatabaseWrapper may require a create_cursor() methodN)rG   )r4   namer5   r5   r6   create_cursor   s    z!BaseDatabaseWrapper.create_cursorc             C   s   | j   d| _g | _d| _| jd }|dkr0dn
tj | | _d| _d| _	| j
 }| j|| _| j| jd  | j  tj| j| d g | _dS )z>Connect to the database. Assume that the connection is closed.FZCONN_MAX_AGEN
AUTOCOMMIT)Zsenderr   )check_settingsr   r   r   r   time	monotonicr   r   r    rH   rJ   r   set_autocommitrK   r
   send	__class__r(   )r4   Zmax_agerI   r5   r5   r6   connect   s    
zBaseDatabaseWrapper.connectc             C   s(   | j d d k	r$tj r$td| j d S )Nr9   z=Connection '%s' cannot set TIME_ZONE because USE_TZ is False.)r   r   r:   r   r   )r4   r5   r5   r6   rO      s    z"BaseDatabaseWrapper.check_settingsc          	   C   s(   | j dkr$| j | j  W dQ R X dS )z;Guarantee that a connection to the database is established.N)r   wrap_database_errorsrU   )r4   r5   r5   r6   ensure_connection   s    
z%BaseDatabaseWrapper.ensure_connectionc             C   s(   | j   | jr| j|}n
| j|}|S )zY
        Validate the connection is usable and perform database cursor wrapping.
        )validate_thread_sharingr@   make_debug_cursormake_cursor)r4   cursorZwrapped_cursorr5   r5   r6   _prepare_cursor   s
    
z#BaseDatabaseWrapper._prepare_cursorc          
   C   s*   | j   | j | j| j|S Q R X d S )N)rW   rV   r\   rM   )r4   rL   r5   r5   r6   _cursor   s    zBaseDatabaseWrapper._cursorc          	   C   s&   | j d k	r"| j | j j S Q R X d S )N)r   rV   commit)r4   r5   r5   r6   _commit   s    
zBaseDatabaseWrapper._commitc          	   C   s&   | j d k	r"| j | j j S Q R X d S )N)r   rV   rollback)r4   r5   r5   r6   	_rollback   s    
zBaseDatabaseWrapper._rollbackc          	   C   s&   | j d k	r"| j | j j S Q R X d S )N)r   rV   close)r4   r5   r5   r6   _close   s    
zBaseDatabaseWrapper._closec             C   s   | j  S )z3Create a cursor, opening a connection if necessary.)r]   )r4   r5   r5   r6   r[      s    zBaseDatabaseWrapper.cursorc             C   s(   | j   | j  | j  d| _d| _dS )z.Commit a transaction and reset the dirty flag.FTN)rX   validate_no_atomic_blockr_   r    r)   )r4   r5   r5   r6   r^     s
    zBaseDatabaseWrapper.commitc             C   s.   | j   | j  | j  d| _d| _g | _dS )z1Roll back a transaction and reset the dirty flag.FN)rX   rd   ra   r    r   r(   )r4   r5   r5   r6   r`     s    zBaseDatabaseWrapper.rollbackc             C   sP   | j   g | _| js| jdkr"dS z| j  W d| jrDd| _d| _nd| _X dS )z%Close the connection to the database.NT)rX   r(   r   r   rc   r   r   )r4   r5   r5   r6   rb     s    zBaseDatabaseWrapper.closec          
   C   s*   | j  }|j| jj| W d Q R X d S )N)r[   executer2   Zsavepoint_create_sql)r4   sidr[   r5   r5   r6   
_savepoint0  s    
zBaseDatabaseWrapper._savepointc          
   C   s*   | j  }|j| jj| W d Q R X d S )N)r[   re   r2   Zsavepoint_rollback_sql)r4   rf   r[   r5   r5   r6   _savepoint_rollback4  s    
z'BaseDatabaseWrapper._savepoint_rollbackc          
   C   s*   | j  }|j| jj| W d Q R X d S )N)r[   re   r2   Zsavepoint_commit_sql)r4   rf   r[   r5   r5   r6   _savepoint_commit8  s    
z%BaseDatabaseWrapper._savepoint_commitc             C   s   | j jo| j  S )N)r/   Zuses_savepointsget_autocommit)r4   r5   r5   r6   _savepoint_allowed<  s    z&BaseDatabaseWrapper._savepoint_allowedc             C   sV   | j  sdS tj }t|jdd}|  jd7  _d|| jf }| j  | j| |S )z
        Create a savepoint inside the current transaction. Return an
        identifier for the savepoint that will be used for the subsequent
        rollback or commit. Do nothing if savepoints are not supported.
        N-    zs%s_x%d)rk   r%   r&   strreplacer   rX   rg   )r4   Zthread_identtidrf   r5   r5   r6   	savepointB  s    
zBaseDatabaseWrapper.savepointc                s8   | j  sdS | j  | j   fdd| jD | _dS )zW
        Roll back to a savepoint. Do nothing if savepoints are not supported.
        Nc                s    g | ]\}} |kr||fqS r5   r5   ).0sidsfunc)rf   r5   r6   
<listcomp>d  s    z:BaseDatabaseWrapper.savepoint_rollback.<locals>.<listcomp>)rk   rX   rh   r(   )r4   rf   r5   )rf   r6   savepoint_rollbackW  s
    
z&BaseDatabaseWrapper.savepoint_rollbackc             C   s"   | j  sdS | j  | j| dS )zR
        Release a savepoint. Do nothing if savepoints are not supported.
        N)rk   rX   ri   )r4   rf   r5   r5   r6   savepoint_commitg  s    z$BaseDatabaseWrapper.savepoint_commitc             C   s
   d| _ dS )zY
        Reset the counter used to generate unique savepoint ids in this thread.
        r   N)r   )r4   r5   r5   r6   clean_savepointsr  s    z$BaseDatabaseWrapper.clean_savepointsc             C   s   t ddS )zR
        Backend-specific implementation to enable or disable autocommit.
        zHsubclasses of BaseDatabaseWrapper may require a _set_autocommit() methodN)rG   )r4   r   r5   r5   r6   _set_autocommit{  s    z#BaseDatabaseWrapper._set_autocommitc             C   s   | j   | jS )zGet the autocommit state.)rW   r   )r4   r5   r5   r6   rj     s    z"BaseDatabaseWrapper.get_autocommitFc             C   s^   | j   | j  |o"| o"t| d}|r2| j  n
| j| || _|rZ| jrZ| j  d| _dS )a  
        Enable or disable autocommit.

        The usual way to start a transaction is to turn autocommit off.
        SQLite does not properly start a transaction when disabling
        autocommit. To avoid this buggy behavior and to actually enter a new
        transaction, an explicit BEGIN is required. Using
        force_begin_transaction_with_broken_autocommit=True will issue an
        explicit BEGIN with SQLite. This option will be ignored for other
        backends.
        #_start_transaction_under_autocommitFN)rd   rW   hasattrr{   rz   r   r)   run_and_clear_commit_hooks)r4   r   Z.force_begin_transaction_with_broken_autocommitZ"start_transaction_under_autocommitr5   r5   r6   rR     s    




z"BaseDatabaseWrapper.set_autocommitc             C   s   | j std| jS )z9Get the "needs rollback" flag -- for *advanced use* only.z<The rollback flag doesn't work outside of an 'atomic' block.)r   r   r   )r4   r5   r5   r6   get_rollback  s    z BaseDatabaseWrapper.get_rollbackc             C   s   | j std|| _dS )zT
        Set or unset the "needs rollback" flag -- for *advanced use* only.
        z<The rollback flag doesn't work outside of an 'atomic' block.N)r   r   r   )r4   r`   r5   r5   r6   set_rollback  s    z BaseDatabaseWrapper.set_rollbackc             C   s   | j rtddS )z,Raise an error if an atomic block is active.z3This is forbidden when an 'atomic' block is active.N)r   r   )r4   r5   r5   r6   rd     s    z,BaseDatabaseWrapper.validate_no_atomic_blockc             C   s   | j rtdd S )NzlAn error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.)r   r   )r4   r5   r5   r6   validate_no_broken_transaction  s    z2BaseDatabaseWrapper.validate_no_broken_transactionc          
   c   s&   | j  }z
dV  W d|r | j  X dS )z:
        Disable foreign key constraint checking.
        N)disable_constraint_checkingenable_constraint_checking)r4   disabledr5   r5   r6   constraint_checks_disabled  s
    
z.BaseDatabaseWrapper.constraint_checks_disabledc             C   s   dS )z
        Backends can implement as needed to temporarily disable foreign key
        constraint checking. Should return True if the constraints were
        disabled and will need to be reenabled.
        Fr5   )r4   r5   r5   r6   r     s    z/BaseDatabaseWrapper.disable_constraint_checkingc             C   s   dS )zh
        Backends can implement as needed to re-enable foreign key constraint
        checking.
        Nr5   )r4   r5   r5   r6   r     s    z.BaseDatabaseWrapper.enable_constraint_checkingc             C   s   dS )z
        Backends can override this method if they can apply constraint
        checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
        IntegrityError if any invalid foreign key references are encountered.
        Nr5   )r4   Ztable_namesr5   r5   r6   check_constraints  s    z%BaseDatabaseWrapper.check_constraintsc             C   s   t ddS )a  
        Test if the database connection is usable.

        This method may assume that self.connection is not None.

        Actual implementations should take care not to raise exceptions
        as that may prevent Django from recycling unusable connections.
        zCsubclasses of BaseDatabaseWrapper may require an is_usable() methodN)rG   )r4   r5   r5   r6   	is_usable  s    	zBaseDatabaseWrapper.is_usablec             C   sr   | j dk	rn| j | jd kr(| j  dS | jrJ| j r>d| _n| j  dS | jdk	rntj | jkrn| j  dS dS )z
        Close the current connection if unrecoverable errors have occurred
        or if it outlived its maximum age.
        NrN   F)	r   rj   r   rb   r    r   r   rP   rQ   )r4   r5   r5   r6   close_if_unusable_or_obsolete  s    
z1BaseDatabaseWrapper.close_if_unusable_or_obsoletec          	   C   s   | j  | jdkS Q R X d S )Nr   )r#   r$   )r4   r5   r5   r6   allow_thread_sharing  s    z(BaseDatabaseWrapper.allow_thread_sharingc          
   C   s$   | j  |  jd7  _W d Q R X d S )Nrn   )r#   r$   )r4   r5   r5   r6   inc_thread_sharing  s    z&BaseDatabaseWrapper.inc_thread_sharingc          
   C   s6   | j & | jdkrtd|  jd8  _W d Q R X d S )Nr   z5Cannot decrement the thread sharing count below zero.rn   )r#   r$   RuntimeError)r4   r5   r5   r6   dec_thread_sharing  s    
z&BaseDatabaseWrapper.dec_thread_sharingc             C   s2   | j p| jtj ks.td| j| jtj f dS )a3  
        Validate that the connection isn't accessed by another thread than the
        one which originally created it, unless the connection was explicitly
        authorized to be shared between threads (via the `inc_thread_sharing()`
        method). Raise an exception if the validation fails.
        zDatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias '%s' was created in thread id %s and this is thread id %s.N)r   r'   r%   r&   r   r   )r4   r5   r5   r6   rX      s    z+BaseDatabaseWrapper.validate_thread_sharingc             C   s   dS )z~
        Hook to do any database check or preparation, generally called before
        migrating a project or an app.
        Nr5   )r4   r5   r5   r6   prepare_database2  s    z$BaseDatabaseWrapper.prepare_databasec             C   s   t | S )z
        Context manager and decorator that re-throws backend-specific database
        exceptions using Django's common wrappers.
        )r   )r4   r5   r5   r6   rV   9  s    z(BaseDatabaseWrapper.wrap_database_errorsc             C   s   | j  S )z
        Return a cursor that tries to avoid caching in the database (if
        supported by the database), otherwise return a regular cursor.
        )r[   )r4   r5   r5   r6   chunked_cursorA  s    z"BaseDatabaseWrapper.chunked_cursorc             C   s   t j|| S )z:Create a cursor that logs all queries in self.queries_log.)r   ZCursorDebugWrapper)r4   r[   r5   r5   r6   rY   H  s    z%BaseDatabaseWrapper.make_debug_cursorc             C   s   t j|| S )z&Create a cursor without debug logging.)r   ZCursorWrapper)r4   r[   r5   r5   r6   rZ   L  s    zBaseDatabaseWrapper.make_cursorc             c   s<   | j dk}z| j }|V  W dQ R X W d|r6| j  X dS )a8  
        Context manager that ensures that a connection is established, and
        if it opened one, closes it to avoid leaving a dangling connection.
        This is useful for operations outside of the request-response cycle.

        Provide a cursor: with self.temporary_connection() as cursor: ...
        N)r   r[   rb   )r4   Z
must_closer[   r5   r5   r6   temporary_connectionP  s    	

z(BaseDatabaseWrapper.temporary_connectionc             c   sF   | j | jdditd}z|j }|V  W dQ R X W d|j  X dS )aq  
        Return a cursor from an alternative connection to be used when there is
        no need to access the main database, specifically for test db
        creation/deletion. This also prevents the production database from
        being exposed to potential child threads while (or after) the test
        database is destroyed. Refs #10868, #17786, #16969.
        NAMEN)r   )rT   r   NO_DB_ALIASr[   rb   )r4   connr[   r5   r5   r6   _nodb_cursora  s
    	
z BaseDatabaseWrapper._nodb_cursorc             O   s$   | j dkrtd| j | f||S )zG
        Return a new instance of this backend's SchemaEditor.
        NzFThe SchemaEditorClass attribute of this database wrapper is still None)SchemaEditorClassrG   )r4   argskwargsr5   r5   r6   schema_editorq  s    
z!BaseDatabaseWrapper.schema_editorc             C   sJ   t |std| jr.| jjt| j|f n| j s@tdn|  d S )Nz*on_commit()'s callback must be a callable.z;on_commit() cannot be used in manual transaction management)	callable	TypeErrorr   r(   appendsetr   rj   r   )r4   ru   r5   r5   r6   	on_commitz  s    
zBaseDatabaseWrapper.on_commitc             C   s6   | j   | j}g | _x|r0|jd\}}|  qW d S )Nr   )rd   r(   pop)r4   Zcurrent_run_on_commitrt   ru   r5   r5   r6   r}     s    z.BaseDatabaseWrapper.run_and_clear_commit_hooksc          
   c   s(   | j j| z
dV  W d| j j  X dS )z|
        Return a context manager under which the wrapper is applied to suitable
        database query executions.
        N)r*   r   r   )r4   wrapperr5   r5   r6   execute_wrapper  s    
z#BaseDatabaseWrapper.execute_wrapperc             C   s(   t j| j}|dkr| j}t| ||S )zy
        Return a copy of this connection.

        For tests that require two connections to the same database.
        N)copydeepcopyr   r   type)r4   r   r   r5   r5   r6   r     s    zBaseDatabaseWrapper.copy)N)N)F)N)N)S__name__
__module____qualname____doc__Z
data_typesZdata_types_suffixZdata_type_check_constraintsr2   vendorZdisplay_namer   r+   r-   r.   r0   r1   r	   r3   r   r   r7   r8   r   r   r>   propertyr@   rF   rH   rJ   rK   rM   r   rU   rO   rW   r\   r]   r_   ra   rc   r[   r^   r`   rb   rg   rh   ri   rk   rr   rw   rx   ry   rz   rj   rR   r~   r   rd   r   r   r   r   r   r   r   r   r   r   r   rX   r   rV   r   rY   rZ   r   r   r   r   r}   r   r   r5   r5   r5   r6   r      s   >

	

	
	

	r   )#r%   r   r!   rP   rB   collectionsr   
contextlibr   r<   Zdjango.confr   Zdjango.core.exceptionsr   Z	django.dbr   r   Zdjango.db.backendsr   Z"django.db.backends.base.validationr	   Zdjango.db.backends.signalsr
   Zdjango.db.transactionr   Zdjango.db.utilsr   Zdjango.utilsr   Zdjango.utils.asyncior   Zdjango.utils.functionalr   r   r   r5   r5   r5   r6   <module>   s(   