首页 > 解决方案 > PSQLException:错误:大型查询超出堆栈深度限制

问题描述

我正在使用 postgres java jdbc 驱动程序。SELECT * FROM mytable where (pk1, pk2, pk3) in ((?,?,?),(?,?,?).....)当我使用 ~20k 复合 ID(即 ~60k 占位符)进行大批量查询时,会弹出此错误。

异常的调用堆栈:

org.postgresql.util.PSQLException: ERROR: stack depth limit exceeded
  Hint: Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2552)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2284)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:322)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:114)
        at io.agroal.pool.wrapper.PreparedStatementWrapper.executeQuery(PreparedStatementWrapper.java:78)
...

这看起来像是服务器端错误。这很棘手,因为:

  1. 我很难配置服务器端的东西......
  2. 即使我可以配置它,但很难知道“会炸毁服务器端堆栈的查询有多大”

对此有什么想法吗?或者进行如此大的 id 查询的最佳做法是什么。

标签: sqlpostgresqljdbc

解决方案


我不确定一个IN子句的最大条目数(1000?),但它远小于 20K。处理这么多的常用方法是创建一个临时表,在这种情况下包含变量。然后调用 v1、v2、v3。现在从文件 (CSV) 加载临时表,然后使用:

select * 
  from mytable 
 where (pk1, pk2, pk3) in
       (select v1,v2,v3 
          from staging_table
       ); 

使用这种格式,暂存表中的项目没有限制。流程完成后truncate,暂存表为下一个周期做准备。


推荐阅读