2015-04-17 21 views
1

我正在使用sqlAlchemy核心訪問postgres數據庫。在我從中選擇一個表格後,我遇到了一個問題。看着CPU進程(ps -aux | grep postgres)我可以看到drop命令正在等待。看來它正在等待select語句清除,應該發生。我做了選擇並處理了所有行,以便結束選擇過程。我甚至試圖關閉光標,但沒有做任何事情。關於我能做的唯一的事情是關閉連接,但我不認爲我應該重新創建每個數據庫查詢的連接,或者我應該?sqlalchemy核心進程仍然是'閒置交易'

下面是拖放懸掛的基本思路。

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. 

回答

0

這是很難看到的問題是從你的例子是什麼,但我希望這一個變量被分配未garbate收集的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") 
相關問題