簡體   English   中英

如何為查詢執行設置語句超時

[英]How to set statement timeout for query execution

在我的網絡應用程序中,一些postgres sql查詢需要時間來執行。 我想只為其中一部分設置語句超時。

查詢的一部分必須通過超時取消,但其他部分必須無任何限制地工作。

在postgres中存在statement_timeout函數。

如何用statement_timeout函數包裝SqlAlchemy查詢?

像這樣:

SET statement_timeout TO 1000; -- timeout for one second
<sqlalchemy generated query>;
RESET statement_timeout; -- reset

對我來說完美的方式設置查詢超時,如下所示:

users = session.query(User).timeout(0.5).all()

SqlAlchemy必須:1)設置語句超時2)執行查詢並返回結果3)當前會話的重置語句超時

可能是為查詢執行設置超時的其他方法?

更新1.我的解決方案

我的解決方案是自定義連接代理(使用psycopg2 == 2.4和SQLAlchemy == 0.6.6測試):

from sqlalchemy.interfaces import ConnectionProxy

class TimeOutProxy(ConnectionProxy):
    def cursor_execute(self, execute, cursor, statement, parameters, context, executemany):

        timeout = context.execution_options.get('timeout', None)

        if timeout:
            c = cursor._parent.cursor()
            c.execute('SET statement_timeout TO %d;' % int(timeout * 1000))
            c.close()

        return execute(cursor, statement, parameters, context)


engine = create_engine(URL, proxy=TimeOutProxy(), pool_size=1, max_overflow=0)

此解決方案無需重置statement_timeout,因為每個SqlAlchemy查詢都在隔離事務中執行,而statement_timeout在當前事務中定義。

用法示例(以秒為單位的超時參數):

Session.query(Author).execution_options(timeout=0.001).all()

Session.bind.execute(text('select * from author;') \
      .execution_options(timeout=0.001)) \
      .fetchall()

您應該查看SQLAlchemy <= 0.6提供的擴展:

http://www.sqlalchemy.org/docs/06/orm/interfaces.html

有一些鈎子,你可以在你的代碼中堅持個人操作。

SQLAlchemy 0.7+現在有一個事件系統......可能有類似的東西。 看到

http://www.sqlalchemy.org/docs/core/events.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM