【问题标题】:sqlalchemy core process remains 'idle in transaction'sqlalchemy 核心进程仍然“在事务中空闲”
【发布时间】:2015-04-17 01:44:31
【问题描述】:

我正在使用 sqlAlchemy 核心来访问 postgres 数据库。从中进行选择后,我在删除表时遇到问题。查看 CPU 进程 (ps -aux |grep postgres) 我可以看到 drop 命令正在等待。似乎它正在等待选择语句清除,这应该已经发生了。我进行了选择并处理了所有行,以便结束选择过程。我什至试图关闭光标,但没有做任何事情。我唯一能做的就是关闭连接,但我认为我应该为每个数据库查询重新创建连接,还是应该?

下面是关于水滴如何悬挂的基本概念。

engine = create_engine('postgresql://***:***@localhost:5432/Junk')
metadata = MetaData()
temp_table = Table('index_tmp', metadata,
                       Column('pid', Integer, primary_key = True),
                       Column('match_id', Integer),
                       Column('id', Integer)
                       )
people = Table('people', metadata, schema='public', autoload=True,          autoload_with=engine)

metadata.create_all(engine)
conn = engine.connect()

sel = select([func.min(people.c.id).label('match_id'), people.c.id])
ins = temp_table.insert().from_select(['match_id', 'id'], sel)
conn.execute(ins)

result = conn.execute(select([tmp_table]))
#Here the process shows "idle in transaction"

result.fetchall()
#This closes the cursor but the process is still "idle in transaction"

temp_table.drop(engine, checkfirst=True)
#The script will hang here since the select command is still "idle in  transaction" and blocking this drop.

【问题讨论】:

    标签: transactions sqlalchemy core


    【解决方案1】:

    很难从您的示例中看出问题所在,但我希望为变量分配了一个未收集垃圾的 sqlalchemy.engine.result.ResultProxy 对象。例如,这会创建两个挂起的事务:

    one = engine.execute("select 1");
    two = engine.execute("select 2");
    

    ...

    test=# select state,query from pg_stat_activity where application_name != 'psql';
            state        |  query
    ---------------------+----------
     idle in transaction | select 1
     idle in transaction | select 2
    (2 rows)
    

    在您的示例中,del(result)result.fetchall()result.close() 都会发出 ROLLBACK

    您也可以通过指示 SQLAlchemy/psycopg2 不要创建隐式事务来完全避免这种行为:

    engine = create_engine(uri, isolation_level="AUTOCOMMIT") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-23
      • 2013-08-28
      • 2016-12-22
      • 2012-02-20
      • 2013-10-11
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多