o 3a`@sddlZddlZddlZddlZddlZddlmZddlmZddl Z ddl m Z ddl m Z ddlmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlm Z dZ!GdddZ"dS)N)deque)contextmanager)settings)ImproperlyConfigured)DEFAULT_DB_ALIAS DatabaseError)utils)BaseDatabaseValidation)connection_created)TransactionManagementErrorDatabaseErrorWrapper)timezone) async_unsafe)cached_property __no_db__c@s~eZdZdZiZiZiZdZdZdZ dZ dZ dZ dZ dZdZeZdZefddZddZed d Zed d Zed dZeddZddZddZddZd|ddZe ddZ!ddZ"e ddZ#dd 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/d0Z,d1d2Z-d3d4Z.d5d6Z/d7d8Z0e d9d:Z1e d;d<Z2e d=d>Z3e d?d@Z4dAdBZ5dCdDZ6d}dFdGZ7dHdIZ8dJdKZ9dLdMZ:dNdOZ;edTdUZ?d|dVdWZ@dXdYZAdZd[ZBed\d]ZCd^d_ZDd`daZEdbdcZFdddeZGedfdgZHdhdiZIdjdkZJdldmZKe/usr/lib/python3/dist-packages/django/db/backends/base/base.py__init__0s4       zBaseDatabaseWrapper.__init__cCdS)z Ensure the connection's timezone is set to `self.timezone_name` and return whether it changed or not. Fr;r:r;r;r<ensure_timezonenz#BaseDatabaseWrapper.ensure_timezonecCs.tjsdS|jddurtjSt|jdS)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)rUSE_TZrrutcpytzr?r;r;r<rus zBaseDatabaseWrapper.timezonecCs(tjstjS|jddurdS|jdS)zC Name of the time zone of the database connection. rBNUTC)rrCrBrr?r;r;r< timezone_names  z!BaseDatabaseWrapper.timezone_namecCs |jptjSN)rrDEBUGr?r;r;r<queries_logged z"BaseDatabaseWrapper.queries_loggedcCs0t|j|jjkrtd|jjt|jS)NzLLimit for query logging exceeded, only the last {} queries will be returned.)lenrrwarningswarnformatlistr?r;r;r<queriess   zBaseDatabaseWrapper.queriescCtd)zConnect to the database. Assume that the connection is closed.F CONN_MAX_AGEN AUTOCOMMIT)senderr)check_settingsrrr rtime monotonicr!r"r#rUrXrset_autocommitrYr send __class__r+)r:max_agerWr;r;r<connects   zBaseDatabaseWrapper.connectcCs*|jddurtjstd|jdSdS)NrBz=Connection '%s' cannot set TIME_ZONE because USE_TZ is False.)rrrCrrr?r;r;r<r`sz"BaseDatabaseWrapper.check_settingscCsB|jdur|j |WddS1swYdSdS)z;Guarantee that a connection to the database is established.N)rwrap_database_errorsrgr?r;r;r<ensure_connections  "z%BaseDatabaseWrapper.ensure_connectioncCs*||jr||}|S||}|S)zY Validate the connection is usable and perform database cursor wrapping. )validate_thread_sharingrJmake_debug_cursor make_cursor)r:cursorwrapped_cursorr;r;r<_prepare_cursors   z#BaseDatabaseWrapper._prepare_cursorcCsB||j|||WdS1swYdSrH)rirhror\rZr;r;r<_cursors$zBaseDatabaseWrapper._cursorcCB|jdur|j |jWdS1swYdSdSrH)rrhcommitr?r;r;r<_commit $zBaseDatabaseWrapper._commitcCrqrH)rrhrollbackr?r;r;r< _rollbackrtzBaseDatabaseWrapper._rollbackcCrqrH)rrhcloser?r;r;r<_closertzBaseDatabaseWrapper._closecC|S)z3Create a cursor, opening a connection if necessary.)rpr?r;r;r<rmszBaseDatabaseWrapper.cursorcCs(|||d|_d|_dS)z.Commit a transaction and reset the dirty flag.FTN)rjvalidate_no_atomic_blockrsr#r,r?r;r;r<rrs  zBaseDatabaseWrapper.commitcCs.|||d|_d|_g|_dS)z1Roll back a transaction and reset the dirty flag.FN)rjrzrvr#r r+r?r;r;r<rus  zBaseDatabaseWrapper.rollbackcCsj|g|_|js|jdurdSz|W|jr"d|_d|_dSd|_dS|jr1d|_d|_wd|_w)z%Close the connection to the database.NT)rjr+r"rrxrr r?r;r;r<rws    zBaseDatabaseWrapper.closecC@|}||j|WddS1swYdSrH)rmexecuter7savepoint_create_sqlr:sidrmr;r;r< _savepoint0 "zBaseDatabaseWrapper._savepointcCr{rH)rmr|r7savepoint_rollback_sqlr~r;r;r<_savepoint_rollback4rz'BaseDatabaseWrapper._savepoint_rollbackcCr{rH)rmr|r7savepoint_commit_sqlr~r;r;r<_savepoint_commit8rz%BaseDatabaseWrapper._savepoint_commitcCs|jjo| SrH)r3uses_savepointsget_autocommitr?r;r;r<_savepoint_allowed<sz&BaseDatabaseWrapper._savepoint_allowedcCsV|sdSt}t|dd}|jd7_d||jf}||||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-zs%s_x%d)rr(r)strreplacerrjr)r: thread_identtidrr;r;r< savepointBs zBaseDatabaseWrapper.savepointcs8|sdS||fdd|jD|_dS)zW Roll back to a savepoint. Do nothing if savepoints are not supported. Ncs g|] \}}|vr||fqSr;r;).0sidsfuncrr;r< csz:BaseDatabaseWrapper.savepoint_rollback..)rrjrr+r:rr;rr<savepoint_rollbackWs   z&BaseDatabaseWrapper.savepoint_rollbackcCs"|sdS|||dS)zR Release a savepoint. Do nothing if savepoints are not supported. N)rrjrrr;r;r<savepoint_commitgsz$BaseDatabaseWrapper.savepoint_commitcCs d|_dS)zY Reset the counter used to generate unique savepoint ids in this thread. rN)rr?r;r;r<clean_savepointsrs z$BaseDatabaseWrapper.clean_savepointscCrR)zR Backend-specific implementation to enable or disable autocommit. zHsubclasses of BaseDatabaseWrapper may require a _set_autocommit() methodrS)r:rr;r;r<_set_autocommit{sz#BaseDatabaseWrapper._set_autocommitcCs||jS)zGet the autocommit state.)rirr?r;r;r<rsz"BaseDatabaseWrapper.get_autocommitFcCsf|||o| ot|d}|r|n||||_|r/|jr1|d|_dSdSdS)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)rzrihasattrrrrr,run_and_clear_commit_hooks)r:r.force_begin_transaction_with_broken_autocommit"start_transaction_under_autocommitr;r;r<rcs      z"BaseDatabaseWrapper.set_autocommitcCs|jstd|jS)z9Get the "needs rollback" flag -- for *advanced use* only.)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. Fr;r?r;r;r<rz/BaseDatabaseWrapper.disable_constraint_checkingcCr>)zh Backends can implement as needed to re-enable foreign key constraint checking. Nr;r?r;r;r<rrAz.BaseDatabaseWrapper.enable_constraint_checkingcCr>)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. Nr;)r: table_namesr;r;r<check_constraintsrz%BaseDatabaseWrapper.check_constraintscCrR)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() methodrSr?r;r;r< is_usables zBaseDatabaseWrapper.is_usablecCsz|jdur7||jdkr|dS|jr%|rd|_n|dS|jdur9t|jkr;|dSdSdSdS)z Close the current connection if unrecoverable errors have occurred or if it outlived its maximum age. Nr^F) rrrrwr#rr!rarbr?r;r;r<close_if_unusable_or_obsoletes z1BaseDatabaseWrapper.close_if_unusable_or_obsoletecCs4|j |jdkWdS1swYdSNrr&r'r?r;r;r<allow_thread_sharings$z(BaseDatabaseWrapper.allow_thread_sharingcCs:|j|jd7_WddS1swYdS)Nrrr?r;r;r<inc_thread_sharings"z&BaseDatabaseWrapper.inc_thread_sharingcCsL|j|jdkr td|jd8_WddS1swYdS)Nrz5Cannot decrement the thread sharing count below zero.r)r&r' RuntimeErrorr?r;r;r<dec_thread_sharings  "z&BaseDatabaseWrapper.dec_thread_sharingcCs6|js|jtkstd|j|jtfdSdS)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)rr*r(r)rrr?r;r;r<rj sz+BaseDatabaseWrapper.validate_thread_sharingcCr>)z~ Hook to do any database check or preparation, generally called before migrating a project or an app. Nr;r?r;r;r<prepare_database2rAz$BaseDatabaseWrapper.prepare_databasecCst|S)z Context manager and decorator that re-throws backend-specific database exceptions using Django's common wrappers. r r?r;r;r<rh9sz(BaseDatabaseWrapper.wrap_database_errorscCry)z Return a cursor that tries to avoid caching in the database (if supported by the database), otherwise return a regular cursor. )rmr?r;r;r<chunked_cursorAsz"BaseDatabaseWrapper.chunked_cursorcC t||S)z:Create a cursor that logs all queries in self.queries_log.)rCursorDebugWrapperr:rmr;r;r<rkHrKz%BaseDatabaseWrapper.make_debug_cursorcCr)z&Create a cursor without debug logging.)r CursorWrapperrr;r;r<rlLrKzBaseDatabaseWrapper.make_cursorccsb|jdu}z"| }|VWdn1swYW|r'|dSdS|r0|ww)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)rrmrw)r: must_closermr;r;r<temporary_connectionPs    z(BaseDatabaseWrapper.temporary_connectionccst|ji|jdditd}z%| }|VWdn1s"wYW|dSW|dS|w)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)rer NO_DB_ALIASrmrw)r:connrmr;r;r< _nodb_cursoras   z BaseDatabaseWrapper._nodb_cursorcOs*|jdur td|j|g|Ri|S)zG Return a new instance of this backend's SchemaEditor. NzFThe SchemaEditorClass attribute of this database wrapper is still None)SchemaEditorClassrT)r:argskwargsr;r;r< schema_editorqs z!BaseDatabaseWrapper.schema_editorcCsJt|std|jr|jt|j|fdS|s td|dS)Nz*on_commit()'s callback must be a callable.z;on_commit() cannot be used in manual transaction management) callable TypeErrorrr+appendsetrrr )r:rr;r;r< on_commitzs zBaseDatabaseWrapper.on_commitcCs8||j}g|_|r|d\}}||s dSdSr)rzr+pop)r:current_run_on_commitrrr;r;r<rs z.BaseDatabaseWrapper.run_and_clear_commit_hooksccs2|j|z dVW|jdS|jw)z| Return a context manager under which the wrapper is applied to suitable database query executions. N)r-rr)r:wrapperr;r;r<execute_wrappers  z#BaseDatabaseWrapper.execute_wrappercCs(t|j}|dur |j}t|||S)zy Return a copy of this connection. For tests that require two connections to the same database. N)copydeepcopyrrtype)r:rrr;r;r<rs zBaseDatabaseWrapper.copyrH)F)S__name__ __module__ __qualname____doc__ data_typesdata_types_suffixdata_type_check_constraintsr7vendor display_namerr.r0r2r4r6r r8rrr=r@rrrGpropertyrJrQrUrXrYr\rrgr`rirorprsrvrxrmrrrurwrrrrrrrrrrrcrrrzrrrrrrrrrrrrjrrhrrkrlrrrrrrrr;r;r;r<rs >                                r)#r(rr$rarM collectionsr contextlibrrE django.confrdjango.core.exceptionsr django.dbrrdjango.db.backendsr"django.db.backends.base.validationr django.db.backends.signalsr django.db.transactionr django.db.utilsr django.utilsrdjango.utils.asynciordjango.utils.functionalrrrr;r;r;r<s*