Transactions sqlalchemy核心进程在事务中保持“空闲”

Transactions sqlalchemy核心进程在事务中保持“空闲”,transactions,sqlalchemy,core,Transactions,Sqlalchemy,Core,我正在使用sqlAlchemy core访问postgres数据库。我在从表中进行选择后,在删除表时遇到问题。查看CPU进程ps-aux | grep postgres,我可以看到drop命令正在等待。它似乎正在等待select语句被清除,这应该已经发生了。我进行了选择并处理了所有行,因此应该结束选择过程。我甚至尝试过关闭光标,但没有任何效果。我能做的唯一一件事就是关闭连接,但我不认为我应该为每个db查询重新创建一个连接,还是应该 下面是水滴如何悬挂的基本概念 engine = create_e

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

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

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.

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

one = engine.execute("select 1");
two = engine.execute("select 2");
engine = create_engine(uri, isolation_level="AUTOCOMMIT") 

在您的示例中,delresult、result.fetchall和result.close都将发出回滚

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

one = engine.execute("select 1");
two = engine.execute("select 2");
engine = create_engine(uri, isolation_level="AUTOCOMMIT")