IT박스

Django + Postgres : "현재 트랜잭션이 중단되고 트랜잭션 블록이 끝날 때까지 명령이 무시됩니다."

itboxs 2020. 10. 29. 07:55
반응형

Django + Postgres : "현재 트랜잭션이 중단되고 트랜잭션 블록이 끝날 때까지 명령이 무시됩니다."


저는 Django / Postgres 사이트에서 작업을 시작했습니다. 가끔에서 작업 manage.py shell하고 실수로 오류가 발생하는 일부 DB 작업을 수행합니다. 그럼 내가 할 수없는 나는 모든 데이터베이스 작업을 위해 내가 수행하려고하기 때문에, 나는 오류가 발생, 모두에서 데이터베이스 작업을 :

current transaction is aborted, commands ignored until end of transaction block

현재 해결 방법은 셸을 다시 시작하는 것이지만 셸 세션을 중단하지 않고이 문제를 해결할 수있는 방법을 찾아야합니다.

(내가 읽은 ,하지만 그들은 쉘에서 무엇을해야하는지에 대한 실질적인 지침을 제공하지 않습니다.)


이것을 시도 할 수 있습니다.

from django.db import connection
connection._rollback()

이 문제에 대한 자세한 내용은 여기에서 확인할 수 있습니다.


때때로 나에게 이런 일이 발생합니다.

manage.py migrate 

또는

manage.py syncdb

여기에서도 언급했듯이

models.py에서 스키마 마이그레이션이 보류중인 경우 다른 방식으로 발생할 수도 있습니다. 남쪽에서는 스키마를 업데이트해야합니다.

manage.py schemamigration mymodel --auto

이것을 확인하십시오

빠른 대답은 일반적으로 다음을 추가하여 데이터베이스 수준 자동 커밋을 설정하는 것입니다.

'OPTIONS': {'autocommit': True,}

데이터베이스 설정에.


완전히 빈 DB에 백업을 복원 한 후이 오류가 발생했습니다. 실행 후 사라졌습니다.

./manage syncdb 

덤프에서 누락 된 내부 모델이있을 수 있습니다.


경고 : 아래 패치로 인해 트랜잭션이 db에서 열린 상태로 남을 수 있습니다 (적어도 postgres 사용시). 100 % 확실하지는 않지만 (그리고 수정 방법) 프로덕션 데이터베이스에서 아래 패치를 수행하지 않는 것이 좋습니다.

받아 들인 대답으로 문제가 해결되지 않기 때문에 DB 오류가 발생하면 수동 롤백으로도 새로운 DB 작업을 수행 할 수 없습니다. 자신의 해결책을 찾았습니다.

Django-shell을 실행할 때 오류가 발생하는 즉시 Django를 패치하여 DB 연결을 닫습니다. 이렇게하면 트랜잭션 롤백이나 연결 처리에 대해 생각할 필요가 없습니다.

이것은 Django-shell-session의 시작 부분에로드하는 코드입니다.

from django import db
from django.db.backends.util import CursorDebugWrapper
old_execute = CursorDebugWrapper.execute
old_execute_many = CursorDebugWrapper.executemany

def execute_wrapper(*args, **kwargs):
    try:
        old_execute(*args, **kwargs)
    except Exception, ex:
        logger.error("Database error:\n%s" % ex)
        db.close_connection

def execute_many_wrapper(*args, **kwargs):
    try:
        old_execute_many(*args, **kwargs)
    except Exception, ex:
        logger.error("Database error:\n%s" % ex)
        db.close_connection

CursorDebugWrapper.execute = execute_wrapper
CursorDebugWrapper.executemany = execute_many_wrapper

migrate(South)를 실행할 때 이러한 오류가 발생하면 데이터베이스 스키마에 많은 변경 사항이 있으며 모두 한 번에 처리하고 싶을 수 있습니다. Postgres는 그것에 대해 약간 불쾌합니다. 항상 작동하는 것은 하나의 큰 마이그레이션을 더 작은 단계로 나누는 것입니다. 대부분 버전 제어 시스템을 사용하고 있습니다.

  • 현재 버전
  • n1 커밋
  • n2 커밋
  • n3 커밋
  • n4 # db 변경 사항 커밋
  • n5 커밋
  • n6 커밋
  • 커밋 n7 # db changse
  • n8 커밋
  • n9 # db 변경 사항 커밋
  • n10 커밋

따라서 위에서 설명한 상황에서 다음과 같이하십시오.

  • Checkout repository to "n4", then syncdb and migrate.
  • Checkout repository to "n7", then syncdb and migrate.
  • Checkout repository to "n10", then syncdb and migrate.

And you're done. :)

It should run flawlessly.


If you are using a django version before 1.6 then you should use Christophe's excellent xact module.

xact is a recipe for handling transactions sensibly in Django applications on PostgreSQL.

Note: As of Django 1.6, the functionality of xact will be merged into the Django core as the atomic decorator. Code that uses xact should be able to be migrated to atomic with just a search-and-replace. atomic works on databases other than PostgreSQL, is thread-safe, and has other nice features; switch to it when you can!


I add the following to my settings file, because I like the autocommit feature when I'm "playing around" but dont want it active when my site is running otherwise.

So to get autocommit just in shell, I do this little hack:

import sys
if 'shell' in sys.argv or sys.argv[0].endswith('pydevconsole.py'):
    DATABASES['default']['OPTIONS']['autocommit'] = True

NOTE: That second part is just because I work in PyCharm, which doesnt directly run manage.py


I got this error in Django 1.7. When I read in the documentation that

This problem cannot occur in Django’s default mode and atomic() handles it automatically.

I got a bit suspicious. The errors happened, when I tried running migrations. It turned out that some of my models had my_field = MyField(default=some_function). Having this function as a default for a field worked alright with sqlite and mysql (I had some import errors, but I managed to make it work), though it seems to not work for postgresql, and it broke the migrations to the point that I didn't event get a helpful error message, but instead the one from the questions title.

참고URL : https://stackoverflow.com/questions/7753016/djangopostgres-current-transaction-is-aborted-commands-ignored-until-end-of

반응형