import django
from django.db import DatabaseError, connection, transaction
from django.conf import settings

settings.configure(
    DATABASES={"default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": "/tmp/dangle.sqlite3",
    }},
    INSTALLED_APPS=[],
)
django.setup()

try:
    with connection.schema_editor(atomic=True) as editor:
        # The schema editor's __exit__ runs this and raises before it gets to
        # self.atomic.__exit__, so the transaction it opened is never closed.
        editor.deferred_sql.append("sql nonsense that will raise an error")
except DatabaseError as e:
    print("deferred sql raised:", e)

# The with block is over. This should be False.
print("in_atomic_block:", connection.in_atomic_block)

# We shouldn't be in an atomic block, so durable=True is fine.
try:
    with transaction.atomic(durable=True):
        pass
except RuntimeError as e:
    print("atomic(durable=True):", e)

# A connection should work after .close().
connection.close()
try:
    connection.cursor().execute("SELECT 1")
except Exception as e:
    print("query after close():", e)
