Is it possible to issue a “VACUUM ANALYZE <tablename>” from psycopg2 or sqlalchemy for PostgreSQL?

ⅰ亾dé卋堺 提交于 2019-12-07 00:53:55

问题


Well, the question pretty much summarises it. My db activity is very update intensive, and I want to programmatically issue a Vacuum Analyze. However I get an error that says that the query cannot be executed within a transaction. Is there some other way to do it?


回答1:


This is a flaw in the Python DB-API: it starts a transaction for you. It shouldn't do that; whether and when to start a transaction should be up to the programmer. Low-level, core APIs like this shouldn't babysit the developer and do things like starting transactions behind our backs. We're big boys--we can start transactions ourself, thanks.

With psycopg2, you can disable this unfortunate behavior with an API extension: run connection.autocommit = True. There's no standard API for this, unfortunately, so you have to depend on nonstandard extensions to issue commands that must be executed outside of a transaction.

No language is without its warts, and this is one of Python's. I've been bitten by this before too.




回答2:


You can turn on Postgres autocommit mode using SQLAlchemy's raw_connection (which will give you a "raw" psycopg2 connection):

import sqlalchemy
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT


engine = sqlalchemy.create_engine(url)
connection = engine.raw_connection()
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor = connection.cursor()
cursor.execute("VACUUM ANALYSE table_name")


来源:https://stackoverflow.com/questions/3931951/is-it-possible-to-issue-a-vacuum-analyze-tablename-from-psycopg2-or-sqlalche

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!