首页 > 解决方案 > jOOQ - 使用 refcursor 执行 postgres 用户定义的函数

问题描述

我在执行refcursor在 jooq 中获取和返回 postgres 的函数时遇到了一些问题。我不知道如何通过实例化来处理refResult<Record>以及如何遍历我应该从我想要执行的函数中获得的记录。

假设我在 postgres (postgres 9.5) 中有以下功能:

create or replace function foo_cursor(name character varying, ref refcursor)
returns refcursor
as $func$
begin
  open ref for
    select id, first_name, last_name
    from students
    where first_name = name;
  return ref;
end
$func$ 
language plpgsql;

在 postgres 中,我是这样执行的:

begin;
select foo_cursor('Konrad', 'my_cursor');
fetch all in "my_cursor";
commit;

该函数必须保持不变 - 它返回refcursor并获取refcursor.

我想在 jOOQ 中执行它:

Routines.fooCursor(configuration, "Konrad", ____);

但我不知道在里面放什么____,这需要Result<Record>。我试过类似的东西:

Result<Record> records = DSL.using(configuration).newResult();

但它也没有用。

标签: javapostgresqljooq

解决方案


jOOQ 支持 PostgreSQL 中的refcursor结果类型(或OUT参数),但不支持IN参数类型,这确实有点怪癖,因为它伪装成标识符的伪类型。如果你可以重载你的函数到这个:

create or replace function foo_cursor(name character varying)
returns refcursor
as $func$
declare
  ref refcursor;
begin
  open ref for
    select id, first_name, last_name
    from students
    where first_name = name;
  return ref;
end
$func$ 
language plpgsql;

然后,jOOQ 将能够调用该函数。jOOQ(或者您,在使用 jOOQ 时)不需要定义生成的游标名称。

但是,您可能需要在事务内部运行函数调用。


推荐阅读