【问题标题】:SQLAlchemy + postgres : (InternalError) current transaction is aborted, commands ignored until end of transaction blockSQLAlchemy + postgres:(InternalError)当前事务被中止,命令被忽略直到事务块结束
【发布时间】:2012-06-05 11:06:27
【问题描述】:

我正在尝试保存一组父/子记录,并且我想将插入包装在事务中。我正在使用带有 postgresql 8.4 的 SQLAlchemy。

这是我的代码的 sn-p:

def insert_data(parent, child_rows):
    # Start a transaction
    conn = _get_connection()
    tran = conn.begin()

    try:
        sql = get_sql_from_parent(parent)
        res = conn.execute(sql)  # <- Code barfs at this line
        item = res.fetchone() if res else None
        parent_id = item['id'] if ((item) and ('id' in item)) else -1

        if parent_id == -1:
            raise Exception('Parent could not be saved in database')

        # Import children
        for child in child_rows:
            child_sql = get_child_sql(parent_id, child)                        
            conn.execute(child_sql)

        tran.commit()

    except IntegrityError:
        pass  # rollback?

    except Exception as e:
        tran.rollback()
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60

当我调用该函数时,我得到以下堆栈跟踪:

Traceback (most recent call last):
  File "import_data.py", line 125, in <module>
    res = conn.execute(sql)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1405, in execute
    params)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1582, in _execute_text
    statement, parameters
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1646, in _execute_context
    context)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1639, in _execute_context
    context)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/default.py", line 330, in do_execute
    cursor.execute(statement, parameters)
InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block
...

有谁知道我为什么会收到这个神秘的错误 - 我该如何解决?

【问题讨论】:

  • (我没读过python,但是)你的前端程序不需要回滚;发生错误后,当前语句由后端自动回滚(并且所有游标都已关闭)“事务”不再存在,但-为方便起见-设置为无效状态,只是为了提醒你重新开始一个新的事务。没有其他办法,因为此时 DBMS 无法保证其内部状态。

标签: python postgresql sqlalchemy


【解决方案1】:

你能在 postgresql 上激活日志查询吗? (在 postgresql.conf 中将 min_duration 设置为 0 然后重新启动)。

然后查看你的 postgresql 日志进行调试。

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 2011-04-05
    • 2011-12-06
    • 1970-01-01
    • 2013-08-04
    • 2012-05-11
    • 2016-12-11
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多