如何将 PostgreSQL 警告提升为 psycopg2 中的异常?

How do I promote PostgreSQL warnings to exceptions in psycopg2?

来自 BEGIN 上的 PostgreSQL docs

Issuing BEGIN when already inside a transaction block will provoke a warning message. The state of the transaction is not affected.

如何让 psycopg2 对任何此类警告引发异常?

我远不是 psycopg2Postgres 专家,而且,我确信有更好的解决方案来提高警告级别,但这里有一些对我有用的东西 - a custom cursor which looks into connection notices 并且,如果那里有东西 - 它会抛出异常。实施本身主要用于教育目的——我确信它需要进行调整以适应您的用例:

import psycopg2

# this "cursor" class needs to be used as a base for custom cursor classes
from psycopg2.extensions import cursor  

class ErrorThrowingCursor(cursor):
    def __init__(self, conn, *args, **kwargs):
        self.conn = conn
        super(ErrorThrowingCursor, self).__init__(*args, **kwargs)

    def execute(self, query, vars=None):
        result = super(ErrorThrowingCursor, self).execute(query, vars)

        for notice in self.conn.notices:
            level, message = notice.split(": ")
            if level == "WARNING":
                raise psycopg2.Warning(message.strip())

        return result

用法示例:

conn = psycopg2.connect(user="user", password="secret")
cursor = conn.cursor(conn, cursor_factory=ErrorThrowingCursor)

如果在查询执行后发出警告,这将引发异常(psycopg2.Warning 类型)。示例:

psycopg2.Warning: there is already a transaction in progress