You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

特定场景下SQLAlchemy执行PostgreSQL查询挂起问题求助

PostgreSQL查询偶发挂起问题排查

问题现象

  • 仅在Manjaro XFCE笔记本上出现查询挂起,Windows PC执行无异常
  • 挂起多发生在特定时间戳(主要为4:05),出现概率不固定
  • 临时解决方法:在目标查询前添加SELECT 1;可恢复正常,但暂不清楚问题成因及该方案的原理

涉及的SQL查询

用于按5分钟时间步长计算测量数据的平均值(含插值):

SELECT datetime, AVG(wc) as wc
FROM (
    SELECT public.time_bucket_gapfill('5 minutes', m.datetime)
    AS datetime, public.interpolate(AVG(m.wc)) as wc
    FROM growficient.measurement AS m
    INNER JOIN growficient.placement AS p ON m.placement_id = p.id
    WHERE m.datetime >= '2022-09-30T22:00:00+00:00'
    AND m.datetime < '2022-10-01T04:05:00+00:00'
    AND p.section_id = 'bd5114b8-4aab-11eb-af66-32bd66d4e25c'
    GROUP BY public.time_bucket_gapfill('5 minutes', m.datetime), p.id
) AS placement_averages
GROUP BY datetime
ORDER BY datetime;

Python执行逻辑

通过SQLAlchemy会话执行上述查询,出现挂起时无法执行到fetchall()步骤:

execute_result = session.execute(query)
readings = execute_result.fetchall()

会话管理代码

参考SQLAlchemy官方文档实现,调试用会话无提交逻辑:

sessionMaker = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=create_engine(
        config.get_settings().main_db,
        echo=False,
        connect_args=connect_options,
        pool_pre_ping=True,
    ),
)

@contextlib.contextmanager
def managed_session() -> Session:
    session = sessionMaker()
    try:
        yield session
    except Exception as e:
        session.rollback()
        logger.error("Session error: %s", e)
        raise
    finally:
        session.close()

观察结果

  1. 执行select * from pg_catalog.pg_stat_activity psa可看到对应事务处于挂起状态
  2. 直接在DBeaver等数据库工具中执行相同查询,可正常返回结果
  3. 尝试PostgreSQL官方文档中提及的客户端超时设置,无法终止挂起的事务
  4. 添加SELECT 1;可解决问题,但已配置pool_pre_ping=True却无效,对此存在困惑

内容的提问来源于stack exchange,提问作者M.verdegaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:45:32