定义一个 psql C 函数给出一个列定义列表,函数返回 "record" 是必需的

Defining a psql C function gives a column definition list is required for functions returning "record"

我正在尝试为 Postgres 9.6 编写一个函数来访问一些用 C 编写的代码。

我的函数定义为:

CREATE OR REPLACE FUNCTION graph_cluster_graph (sql text, has_rcost boolean)
  RETURNS SETOF RECORD AS
    '$libdir/libpgrouting-2.4', 'dir_graph_cluster_desc'
    LANGUAGE c STABLE STRICT;

尝试调用它时:

select * from   graph_cluster_graph('select * from case3_cab_dist_table',true);

我收到错误

definition list is required for functions returning "record"


如果我写就可以了

select graph_cluster_graph('select * from case3_cab_dist_table',true);

在这种情况下,它调用请求的 C 函数,然后在 returns 时退出。

我确实更改了 C 函数的名称只是为了了解会发生什么(您可能会遇到无法找到该函数的错误)。所以我知道它可以找到我的 C 例程。再次使用 select 语句的第二种形式并获得响应意味着已正确调用 C 函数。

有人知道我做错了什么吗?

使用 RETURNS SETOF RECORD 查询解析器不知道结果行将包含哪些列的函数,您必须在查询中提供该信息。

the documentation所说,

In some cases it is useful to define table functions that can return different column sets depending on how they are invoked. To support this, the table function can be declared as returning the pseudotype record. When such a function is used in a query, the expected row structure must be specified in the query itself, so that the system can know how to parse and plan the query. This syntax looks like:

<em>function_call</em> [AS] <em>alias</em> (<em>column_definition</em> [, ... ]) <em>function_call</em> AS [<em>alias</em>] (<em>column_definition</em> [, ... ]) ROWS FROM( ... <em>function_call</em> AS (<em>column_definition</em> [, ... ]) [, ... ] )

如果事先知道记录会有哪些列,最好将函数定义为

RETURNS SETOF <em>数据类型</em>

RETURNS TABLE ( <em>column_name</em> <em>column_type</em> [ ...] )

后者是旧语法的 shorthand:

<em>funcname</em>(..., OUT <em>column_name</em> <em>column_type</em>, ...) RETURNS SETOF 记录