如何使用twisted.enterprise.adbapi在没有显式事务的情况下运行查询?

时间:2018-07-23 07:18:31

标签: postgresql twisted psycopg2

我使用Python + Twisted为PostgreSQL编写了迁移工具。当我尝试在PostgreSQL中同时创建索引时,收到psycopg2.InternalError,请参见一段代码:

from twisted.enterprise import adbapi
from twisted.internet import reactor

cp = adbapi.ConnectionPool("psycopg2", host="localhost", port=5432, database="test", user="test", password="test")
reactor.callWhenRunning(cp.runOperation, "CREATE TABLE IF NOT EXISTS test (id INTEGER NOT NULL, name TEXT)") 
reactor.callWhenRunning(cp.runOperation, "CREATE INDEX CONCURRENTLY test_idx  ON test (name TEXT)") 
reactor.run()

运行结果:

$ venv/bin/python test.py

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/_threads/_threadworker.py", line 46, in work
    task()
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/_threads/_team.py", line 190, in doWork
    task()
--- <exception caught here> ---
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/python/threadpool.py", line 241, in inContext
    result = inContext.theWork()
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/python/threadpool.py", line 257, in <lambda>
    inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
    return func(*args,**kw)
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/enterprise/adbapi.py", line 445, in _runInteraction
    result = interaction(trans, *args, **kw)
  File "/home/test/venv/local/lib/python2.7/site-packages/twisted/enterprise/adbapi.py", line 463, in _runOperation
    trans.execute(*args, **kw)
psycopg2.InternalError: CREATE INDEX CONCURRENTLY cannot run inside a transaction block

是否有任何方法可以使用twisted.enterprise.adbapi在没有显式事务块的情况下运行查询?

我尝试了runWithConnection,runOperation并分析了源代码。不知道。

我的环境是在Ubuntu 14.04.5 LTS中使用virtualenv工具创建的:

python==2.7.6
psycopg2==2.7.4
Twisted==15.4.0

0 个答案:

没有答案