represent a database connection mapping of field objects to their column types datatypes mapping of field objects to their sql suffix such as autoincrement datatypessuffix mapping of field objects to their sql for check constraints datatypecheckconstraints ops none vendor unknown displayname unknown schemaeditorclass none classes instantiated in init clientclass none creationclass none featuresclass none introspectionclass none opsclass none validationclass basedatabasevalidation querieslimit 9000 def initself settingsdict aliasdefaultdbalias connection related attributes the underlying database connection self connection none settingsdict should be a dictionary containing keys such as name user etc it s called settingsdict instead of settings to disambiguate it from django settings modules self settingsdict settingsdict self alias alias query logging in debug mode or when explicitly enabled self querieslog dequemaxlenself querieslimit self forcedebugcursor false transaction related attributes tracks if the connection is in autocommit mode per pep 249 by default it isn t self autocommit false tracks if the connection is in a transaction managed by atomic self inatomicblock false increment to generate unique savepoint ids self savepointstate 0 list of savepoints atomic self savepointids stack of active atomic blocks self atomicblocks tracks if the outermost atomic block should commit on exit ie if autocommit was active on entry self commitonexit true tracks if the transaction should be rolled back to the next available savepoint because of an exception in an inner block self needsrollback false self rollbackexc none connection termination related attributes self closeat none self closedintransaction false self errorsoccurred false self healthcheckenabled false self healthcheckdone false threadsafety related attributes self threadsharinglock threading lock self threadsharingcount 0 self threadident thread getident a list of noargument functions to run when the transaction commits each entry is an sids func robust tuple where sids is a set of the active savepoint ids when this function was registered and robust specifies whether it s allowed for the function to fail self runoncommit should we run the oncommit hooks the next time setautocommittrue is called self runcommithooksonsetautocommiton false a stack of wrappers to be invoked around executeexecutemany calls each entry is a function taking five arguments execute sql params many and context it s the function s responsibility to call executesql params many context self executewrappers self client self clientclassself self creation self creationclassself self features self featuresclassself self introspection self introspectionclassself self ops self opsclassself self validation self validationclassself def reprself return fself class qualname fvendorself vendor r aliasself alias r def ensuretimezoneself return false cachedproperty def timezoneself if not settings usetz return none elif self settingsdicttimezone is none return datetime timezone utc else return zoneinfo zoneinfoself settingsdicttimezone cachedproperty def timezonenameself if not settings usetz return settings timezone elif self settingsdicttimezone is none return utc else return self settingsdicttimezone property def queriesloggedself return self forcedebugcursor or settings debug property def queriesself if lenself querieslog self querieslog maxlen warnings warn limit for query logging exceeded only the last queries will be returned formatself querieslog maxlen return listself querieslog def getdatabaseversionself raise an error if the database version isn t supported by this version of django backendspecific methods for creating connections and cursors return a dict of parameters suitable for getnewconnection raise notimplementederror subclasses of basedatabasewrapper may require a getconnectionparams method def getnewconnectionself connparams initialize the database connection settings global randbversioncheck if self alias not in randbversioncheck self checkdatabaseversionsupported randbversioncheck addself alias def createcursorself namenone backendspecific methods for creating connections connect to the database assume that the connection is closed check for invalid configurations self checksettings in case the previous connection was closed while in an atomic block self inatomicblock false self savepointids self atomicblocks self needsrollback false reset parameters defining when to closehealthcheck the connection self healthcheckenabled self settingsdictconnhealthchecks maxage self settingsdictconnmaxage self closeat none if maxage is none else time monotonic maxage self closedintransaction false self errorsoccurred false new connections are healthy self healthcheckdone true establish the connection connparams self getconnectionparams self connection self getnewconnectionconnparams self setautocommitself settingsdictautocommit self initconnectionstate connectioncreated sendsenderself class connectionself self runoncommit def checksettingsself if self settingsdicttimezone is not none and not settings usetz raise improperlyconfigured connection s cannot set timezone because usetz is false self alias asyncunsafe def ensureconnectionself backendspecific wrappers for pep249 connection methods validate the connection is usable and perform database cursor wrapping generic wrappers for pep249 connection methods create a cursor opening a connection if necessary return self cursor asyncunsafe def commitself a successful commit means that the database connection works roll back a transaction and reset the dirty flag self validatethreadsharing self validatenoatomicblock self rollback a successful rollback means that the database connection works self errorsoccurred false self needsrollback false self runoncommit asyncunsafe def closeself don t call validatenoatomicblock to avoid making it difficult to get rid of a connection in an invalid state the next connect will reset the transaction state anyway backendspecific savepoint management methods savepoints cannot be created outside a transaction generic savepoint management methods 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 roll back to a savepoint do nothing if savepoints are not supported remove any callbacks registered while this savepoint was active release a savepoint do nothing if savepoints are not supported reset the counter used to generate unique savepoint ids in this thread backendspecific transaction management methods backendspecific implementation to enable or disable autocommit generic transaction management methods get the autocommit state self ensureconnection return self autocommit def setautocommit self autocommit forcebegintransactionwithbrokenautocommitfalse self validatenoatomicblock self closeifhealthcheckfailed self ensureconnection starttransactionunderautocommit forcebegintransactionwithbrokenautocommit and not autocommit and hasattrself starttransactionunderautocommit if starttransactionunderautocommit self starttransactionunderautocommit elif autocommit self setautocommitautocommit else with debugtransactionself begin self setautocommitautocommit self autocommit autocommit if autocommit and self runcommithooksonsetautocommiton self runandclearcommithooks self runcommithooksonsetautocommiton false def getrollbackself set or unset the needs rollback flag for advanced use only raise an error if an atomic block is active if self inatomicblock raise transactionmanagementerror this is forbidden when an atomic block is active def validatenobrokentransactionself if self needsrollback raise transactionmanagementerror an error occurred in the current transaction you can t execute queries until the end of the atomic block from self rollbackexc foreign key constraints checks handling contextmanager def constraintchecksdisabledself disabled self disableconstraintchecking try yield finally if disabled self enableconstraintchecking def disableconstraintcheckingself return false def enableconstraintcheckingself pass def checkconstraintsself tablenamesnone pass connection termination handling def isusableself raise notimplementederror subclasses of basedatabasewrapper may require an isusable method def closeifhealthcheckfailedself close the current connection if unrecoverable errors have occurred or if it outlived its maximum age if the application didn t restore the original autocommit setting don t take chances drop the connection if an exception other than dataerror or integrityerror occurred since the last commit rollback check if the connection works thread safety handling validate that the connection isn t accessed by another thread than the one which originally created it unless the connection was explicitly ized to be shared between threads via the incthreadsharing method raise an exception if the validation fails miscellaneous hook to do any database check or preparation generally called before migrating a project or an app context manager and decorator that rethrows backendspecific database exceptions using django s common wrappers return a cursor that tries to avoid caching in the database if supported by the database otherwise return a regular cursor create a cursor that logs all queries in self querieslog return utils cursordebugwrappercursor self def makecursorself cursor 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 requestresponse cycle provide a cursor with self temporaryconnection as cursor return a cursor from an alternative connection to be used when there is no need to access the main database specifically for test db creationdeletion 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 return a new instance of this backend s schemaeditor transaction in progress save for execution on commit no transaction in progress and in autocommit mode execute immediately return a context manager under which the wrapper is applied to suitable database query executions return a copy of this connection for tests that require two connections to the same database represent a database connection mapping of field objects to their column types mapping of field objects to their sql suffix such as autoincrement mapping of field objects to their sql for check constraints classes instantiated in __init__ connection related attributes the underlying database connection settings_dict should be a dictionary containing keys such as name user etc it s called settings_dict instead of settings to disambiguate it from django settings modules query logging in debug mode or when explicitly enabled transaction related attributes tracks if the connection is in autocommit mode per pep 249 by default it isn t tracks if the connection is in a transaction managed by atomic increment to generate unique savepoint ids list of savepoints atomic stack of active atomic blocks tracks if the outermost atomic block should commit on exit ie if autocommit was active on entry tracks if the transaction should be rolled back to the next available savepoint because of an exception in an inner block connection termination related attributes thread safety related attributes a list of no argument functions to run when the transaction commits each entry is an sids func robust tuple where sids is a set of the active savepoint ids when this function was registered and robust specifies whether it s allowed for the function to fail should we run the on commit hooks the next time set_autocommit true is called a stack of wrappers to be invoked around execute executemany calls each entry is a function taking five arguments execute sql params many and context it s the function s responsibility to call execute sql params many context ensure the connection s timezone is set to self timezone_name and return whether it changed or not 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 name of the time zone of the database connection return a tuple of the database s version raise an error if the database version isn t supported by this version of django backend specific methods for creating connections and cursors return a dict of parameters suitable for get_new_connection open a connection to the database initialize the database connection settings create a cursor assume that a connection is established backend specific methods for creating connections connect to the database assume that the connection is closed check for invalid configurations in case the previous connection was closed while in an atomic block reset parameters defining when to close health check the connection new connections are healthy establish the connection guarantee that a connection to the database is established backend specific wrappers for pep 249 connection methods validate the connection is usable and perform database cursor wrapping generic wrappers for pep 249 connection methods create a cursor opening a connection if necessary commit a transaction and reset the dirty flag a successful commit means that the database connection works roll back a transaction and reset the dirty flag a successful rollback means that the database connection works close the connection to the database don t call validate_no_atomic_block to avoid making it difficult to get rid of a connection in an invalid state the next connect will reset the transaction state anyway backend specific savepoint management methods savepoints cannot be created outside a transaction generic savepoint management methods 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 roll back to a savepoint do nothing if savepoints are not supported remove any callbacks registered while this savepoint was active release a savepoint do nothing if savepoints are not supported reset the counter used to generate unique savepoint ids in this thread backend specific transaction management methods backend specific implementation to enable or disable autocommit generic transaction management methods get the autocommit state 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 get the needs rollback flag for advanced use only set or unset the needs rollback flag for advanced use only raise an error if an atomic block is active foreign key constraints checks handling disable foreign key constraint checking 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 backends can implement as needed to re enable foreign key constraint checking 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 connection termination handling 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 close existing connection if it fails a health check close the current connection if unrecoverable errors have occurred or if it outlived its maximum age if the application didn t restore the original autocommit setting don t take chances drop the connection if an exception other than dataerror or integrityerror occurred since the last commit rollback check if the connection works thread safety handling validate that the connection isn t accessed by another thread than the one which originally created it unless the connection was explicitly ized to be shared between threads via the inc_thread_sharing method raise an exception if the validation fails miscellaneous hook to do any database check or preparation generally called before migrating a project or an app context manager and decorator that re throws backend specific database exceptions using django s common wrappers return a cursor that tries to avoid caching in the database if supported by the database otherwise return a regular cursor create a cursor that logs all queries in self queries_log create a cursor without debug logging 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 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 return a new instance of this backend s schemaeditor transaction in progress save for execution on commit no transaction in progress and in autocommit mode execute immediately return a context manager under which the wrapper is applied to suitable database query executions return a copy of this connection for tests that require two connections to the same database
import _thread
import copy
import datetime
import logging
import threading
import time
import warnings
import zoneinfo
from collections import deque
from contextlib import contextmanager

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError
from django.db.backends import utils
from django.db.backends.base.validation import BaseDatabaseValidation
from django.db.backends.signals import connection_created
from django.db.backends.utils import debug_transaction
from django.db.transaction import TransactionManagementError
from django.db.utils import DatabaseErrorWrapper
from django.utils.asyncio import async_unsafe
from django.utils.functional import cached_property

NO_DB_ALIAS = "__no_db__"
RAN_DB_VERSION_CHECK = set()

logger = logging.getLogger("django.db.backends.base")


class BaseDatabaseWrapper:
    

    
    data_types = {}
    
    data_types_suffix = {}
    
    data_type_check_constraints = {}
    ops = None
    vendor = "unknown"
    display_name = "unknown"
    SchemaEditorClass = None
    
    client_class = None
    creation_class = None
    features_class = None
    introspection_class = None
    ops_class = None
    validation_class = BaseDatabaseValidation

    queries_limit = 9000

    def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
        
        
        self.connection = None
        
        
        
        self.settings_dict = settings_dict
        self.alias = alias
        
        self.queries_log = deque(maxlen=self.queries_limit)
        self.force_debug_cursor = False

        
        
        
        self.autocommit = False
        
        self.in_atomic_block = False
        
        self.savepoint_state = 0
        
        self.savepoint_ids = []
        
        self.atomic_blocks = []
        
        
        self.commit_on_exit = True
        
        
        self.needs_rollback = False
        self.rollback_exc = None

        
        self.close_at = None
        self.closed_in_transaction = False
        self.errors_occurred = False
        self.health_check_enabled = False
        self.health_check_done = False

        
        self._thread_sharing_lock = threading.Lock()
        self._thread_sharing_count = 0
        self._thread_ident = _thread.get_ident()

        
        
        
        
        self.run_on_commit = []

        
        
        self.run_commit_hooks_on_set_autocommit_on = False

        
        
        
        
        self.execute_wrappers = []

        self.client = self.client_class(self)
        self.creation = self.creation_class(self)
        self.features = self.features_class(self)
        self.introspection = self.introspection_class(self)
        self.ops = self.ops_class(self)
        self.validation = self.validation_class(self)

    def __repr__(self):
        return (
            f"<{self.__class__.__qualname__} "
            f"vendor={self.vendor!r} alias={self.alias!r}>"
        )

    def ensure_timezone(self):
        
        return False

    @cached_property
    def timezone(self):
        
        if not settings.USE_TZ:
            return None
        elif self.settings_dict["TIME_ZONE"] is None:
            return datetime.timezone.utc
        else:
            return zoneinfo.ZoneInfo(self.settings_dict["TIME_ZONE"])

    @cached_property
    def timezone_name(self):
        
        if not settings.USE_TZ:
            return settings.TIME_ZONE
        elif self.settings_dict["TIME_ZONE"] is None:
            return "UTC"
        else:
            return self.settings_dict["TIME_ZONE"]

    @property
    def queries_logged(self):
        return self.force_debug_cursor or settings.DEBUG

    @property
    def queries(self):
        if len(self.queries_log) == self.queries_log.maxlen:
            warnings.warn(
                "Limit for query logging exceeded, only the last {} queries "
                "will be returned.".format(self.queries_log.maxlen)
            )
        return list(self.queries_log)

    def get_database_version(self):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require a get_database_version() "
            "method."
        )

    def check_database_version_supported(self):
        
        if (
            self.features.minimum_database_version is not None
            and self.get_database_version() < self.features.minimum_database_version
        ):
            db_version = ".".join(map(str, self.get_database_version()))
            min_db_version = ".".join(map(str, self.features.minimum_database_version))
            raise NotSupportedError(
                f"{self.display_name} {min_db_version} or later is required "
                f"(found {db_version})."
            )

    

    def get_connection_params(self):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require a get_connection_params() "
            "method"
        )

    def get_new_connection(self, conn_params):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require a get_new_connection() "
            "method"
        )

    def init_connection_state(self):
        
        global RAN_DB_VERSION_CHECK
        if self.alias not in RAN_DB_VERSION_CHECK:
            self.check_database_version_supported()
            RAN_DB_VERSION_CHECK.add(self.alias)

    def create_cursor(self, name=None):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require a create_cursor() method"
        )

    

    @async_unsafe
    def connect(self):
        
        
        self.check_settings()
        
        self.in_atomic_block = False
        self.savepoint_ids = []
        self.atomic_blocks = []
        self.needs_rollback = False
        
        self.health_check_enabled = self.settings_dict["CONN_HEALTH_CHECKS"]
        max_age = self.settings_dict["CONN_MAX_AGE"]
        self.close_at = None if max_age is None else time.monotonic() + max_age
        self.closed_in_transaction = False
        self.errors_occurred = False
        
        self.health_check_done = True
        
        conn_params = self.get_connection_params()
        self.connection = self.get_new_connection(conn_params)
        self.set_autocommit(self.settings_dict["AUTOCOMMIT"])
        self.init_connection_state()
        connection_created.send(sender=self.__class__, connection=self)

        self.run_on_commit = []

    def check_settings(self):
        if self.settings_dict["TIME_ZONE"] is not None and not settings.USE_TZ:
            raise ImproperlyConfigured(
                "Connection '%s' cannot set TIME_ZONE because USE_TZ is False."
                % self.alias
            )

    @async_unsafe
    def ensure_connection(self):
        
        if self.connection is None:
            with self.wrap_database_errors:
                self.connect()

    

    def _prepare_cursor(self, cursor):
        
        self.validate_thread_sharing()
        if self.queries_logged:
            wrapped_cursor = self.make_debug_cursor(cursor)
        else:
            wrapped_cursor = self.make_cursor(cursor)
        return wrapped_cursor

    def _cursor(self, name=None):
        self.close_if_health_check_failed()
        self.ensure_connection()
        with self.wrap_database_errors:
            return self._prepare_cursor(self.create_cursor(name))

    def _commit(self):
        if self.connection is not None:
            with debug_transaction(self, "COMMIT"), self.wrap_database_errors:
                return self.connection.commit()

    def _rollback(self):
        if self.connection is not None:
            with debug_transaction(self, "ROLLBACK"), self.wrap_database_errors:
                return self.connection.rollback()

    def _close(self):
        if self.connection is not None:
            with self.wrap_database_errors:
                return self.connection.close()

    

    @async_unsafe
    def cursor(self):
        
        return self._cursor()

    @async_unsafe
    def commit(self):
        
        self.validate_thread_sharing()
        self.validate_no_atomic_block()
        self._commit()
        
        self.errors_occurred = False
        self.run_commit_hooks_on_set_autocommit_on = True

    @async_unsafe
    def rollback(self):
        
        self.validate_thread_sharing()
        self.validate_no_atomic_block()
        self._rollback()
        
        self.errors_occurred = False
        self.needs_rollback = False
        self.run_on_commit = []

    @async_unsafe
    def close(self):
        
        self.validate_thread_sharing()
        self.run_on_commit = []

        
        
        
        if self.closed_in_transaction or self.connection is None:
            return
        try:
            self._close()
        finally:
            if self.in_atomic_block:
                self.closed_in_transaction = True
                self.needs_rollback = True
            else:
                self.connection = None

    

    def _savepoint(self, sid):
        with self.cursor() as cursor:
            cursor.execute(self.ops.savepoint_create_sql(sid))

    def _savepoint_rollback(self, sid):
        with self.cursor() as cursor:
            cursor.execute(self.ops.savepoint_rollback_sql(sid))

    def _savepoint_commit(self, sid):
        with self.cursor() as cursor:
            cursor.execute(self.ops.savepoint_commit_sql(sid))

    def _savepoint_allowed(self):
        
        return self.features.uses_savepoints and not self.get_autocommit()

    

    @async_unsafe
    def savepoint(self):
        
        if not self._savepoint_allowed():
            return

        thread_ident = _thread.get_ident()
        tid = str(thread_ident).replace("-", "")

        self.savepoint_state += 1
        sid = "s%s_x%d" % (tid, self.savepoint_state)

        self.validate_thread_sharing()
        self._savepoint(sid)

        return sid

    @async_unsafe
    def savepoint_rollback(self, sid):
        
        if not self._savepoint_allowed():
            return

        self.validate_thread_sharing()
        self._savepoint_rollback(sid)

        
        self.run_on_commit = [
            (sids, func, robust)
            for (sids, func, robust) in self.run_on_commit
            if sid not in sids
        ]

    @async_unsafe
    def savepoint_commit(self, sid):
        
        if not self._savepoint_allowed():
            return

        self.validate_thread_sharing()
        self._savepoint_commit(sid)

    @async_unsafe
    def clean_savepoints(self):
        
        self.savepoint_state = 0

    

    def _set_autocommit(self, autocommit):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require a _set_autocommit() method"
        )

    

    def get_autocommit(self):
        
        self.ensure_connection()
        return self.autocommit

    def set_autocommit(
        self, autocommit, force_begin_transaction_with_broken_autocommit=False
    ):
        
        self.validate_no_atomic_block()
        self.close_if_health_check_failed()
        self.ensure_connection()

        start_transaction_under_autocommit = (
            force_begin_transaction_with_broken_autocommit
            and not autocommit
            and hasattr(self, "_start_transaction_under_autocommit")
        )

        if start_transaction_under_autocommit:
            self._start_transaction_under_autocommit()
        elif autocommit:
            self._set_autocommit(autocommit)
        else:
            with debug_transaction(self, "BEGIN"):
                self._set_autocommit(autocommit)
        self.autocommit = autocommit

        if autocommit and self.run_commit_hooks_on_set_autocommit_on:
            self.run_and_clear_commit_hooks()
            self.run_commit_hooks_on_set_autocommit_on = False

    def get_rollback(self):
        
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block."
            )
        return self.needs_rollback

    def set_rollback(self, rollback):
        
        if not self.in_atomic_block:
            raise TransactionManagementError(
                "The rollback flag doesn't work outside of an 'atomic' block."
            )
        self.needs_rollback = rollback

    def validate_no_atomic_block(self):
        
        if self.in_atomic_block:
            raise TransactionManagementError(
                "This is forbidden when an 'atomic' block is active."
            )

    def validate_no_broken_transaction(self):
        if self.needs_rollback:
            raise TransactionManagementError(
                "An error occurred in the current transaction. You can't "
                "execute queries until the end of the 'atomic' block."
            ) from self.rollback_exc

    

    @contextmanager
    def constraint_checks_disabled(self):
        
        disabled = self.disable_constraint_checking()
        try:
            yield
        finally:
            if disabled:
                self.enable_constraint_checking()

    def disable_constraint_checking(self):
        
        return False

    def enable_constraint_checking(self):
        
        pass

    def check_constraints(self, table_names=None):
        
        pass

    

    def is_usable(self):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseWrapper may require an is_usable() method"
        )

    def close_if_health_check_failed(self):
        
        if (
            self.connection is None
            or not self.health_check_enabled
            or self.health_check_done
        ):
            return

        if not self.is_usable():
            self.close()
        self.health_check_done = True

    def close_if_unusable_or_obsolete(self):
        
        if self.connection is not None:
            self.health_check_done = False
            
            
            if self.get_autocommit() != self.settings_dict["AUTOCOMMIT"]:
                self.close()
                return

            
            
            if self.errors_occurred:
                if self.is_usable():
                    self.errors_occurred = False
                    self.health_check_done = True
                else:
                    self.close()
                    return

            if self.close_at is not None and time.monotonic() >= self.close_at:
                self.close()
                return

    

    @property
    def allow_thread_sharing(self):
        with self._thread_sharing_lock:
            return self._thread_sharing_count > 0

    def inc_thread_sharing(self):
        with self._thread_sharing_lock:
            self._thread_sharing_count += 1

    def dec_thread_sharing(self):
        with self._thread_sharing_lock:
            if self._thread_sharing_count <= 0:
                raise RuntimeError(
                    "Cannot decrement the thread sharing count below zero."
                )
            self._thread_sharing_count -= 1

    def validate_thread_sharing(self):
        
        if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()):
            raise DatabaseError(
                "DatabaseWrapper 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." % (self.alias, self._thread_ident, _thread.get_ident())
            )

    

    def prepare_database(self):
        
        pass

    @cached_property
    def wrap_database_errors(self):
        
        return DatabaseErrorWrapper(self)

    def chunked_cursor(self):
        
        return self.cursor()

    def make_debug_cursor(self, cursor):
        
        return utils.CursorDebugWrapper(cursor, self)

    def make_cursor(self, cursor):
        
        return utils.CursorWrapper(cursor, self)

    @contextmanager
    def temporary_connection(self):
        
        must_close = self.connection is None
        try:
            with self.cursor() as cursor:
                yield cursor
        finally:
            if must_close:
                self.close()

    @contextmanager
    def _nodb_cursor(self):
        
        conn = self.__class__({**self.settings_dict, "NAME": None}, alias=NO_DB_ALIAS)
        try:
            with conn.cursor() as cursor:
                yield cursor
        finally:
            conn.close()

    def schema_editor(self, *args, **kwargs):
        
        if self.SchemaEditorClass is None:
            raise NotImplementedError(
                "The SchemaEditorClass attribute of this database wrapper is still None"
            )
        return self.SchemaEditorClass(self, *args, **kwargs)

    def on_commit(self, func, robust=False):
        if not callable(func):
            raise TypeError("on_commit()'s callback must be a callable.")
        if self.in_atomic_block:
            
            self.run_on_commit.append((set(self.savepoint_ids), func, robust))
        elif not self.get_autocommit():
            raise TransactionManagementError(
                "on_commit() cannot be used in manual transaction management"
            )
        else:
            
            
            if robust:
                try:
                    func()
                except Exception as e:
                    logger.error(
                        f"Error calling {func.__qualname__} in on_commit() (%s).",
                        e,
                        exc_info=True,
                    )
            else:
                func()

    def run_and_clear_commit_hooks(self):
        self.validate_no_atomic_block()
        current_run_on_commit = self.run_on_commit
        self.run_on_commit = []
        while current_run_on_commit:
            _, func, robust = current_run_on_commit.pop(0)
            if robust:
                try:
                    func()
                except Exception as e:
                    logger.error(
                        f"Error calling {func.__qualname__} in on_commit() during "
                        f"transaction (%s).",
                        e,
                        exc_info=True,
                    )
            else:
                func()

    @contextmanager
    def execute_wrapper(self, wrapper):
        
        self.execute_wrappers.append(wrapper)
        try:
            yield
        finally:
            self.execute_wrappers.pop()

    def copy(self, alias=None):
        
        settings_dict = copy.deepcopy(self.settings_dict)
        if alias is None:
            alias = self.alias
        return type(self)(settings_dict, alias)