首页 > 解决方案 > Postgresql v12 函数在 Json 中返回函数名称

问题描述

这是函数所需的查询结果:

[{"id":1,"task":"Finish Task ONE"},{"id":2,"task":"Finish Task TWO"}]

它在 pgAdmin4 中通过以下方式正确生成:SELECT api.add_them(1,2) in 4。

但是,当使用 Windows Curl 或 Android Studio 应用程序调用该函数时,它会生成:

[{"add_them":[{"id":1,"task":"Finish Task ONE"},{"id":2,"task":"Finish Task TWO"}]}]

因此,函数名称被包含在主体周围的包装中。

Windows curl 脚本是:

curl http://localhost:3000/rpc/add_them -X POST ^
     -H "Authorization: Bearer <My JWT Token>"   ^
     -H "Content-Type: application/json" ^
     -H "Prefer: return=representation" ^
     -d "{\"a\": 1, \"b\": 2}"

功能是:

CREATE OR REPLACE FUNCTION api.add_them(
a integer,
b integer)
RETURNS setof json
LANGUAGE 'plpgsql'

COST 100
VOLATILE 
ROWS 1000

AS $$

BEGIN
RETURN QUERY 
SELECT array_to_json(array_agg(row_to_json(t)))
FROM ( select id, task from api.todos
       where id >= a and id <= b) t;
END;  $$;

ALTER FUNCTION api.add_them(a integer, b integer)
OWNER TO postgres;

标签: curlrpcpostgresql-jsonpostgrest

解决方案


PostgREST 使用模式缓存,如果您添加新功能并且不刷新它,它可能会变得陈旧。

要刷新模式缓存,请重新启动 PostgREST 或使用 SIGUSR1( killall -SIGUSR1 postgrest) 重新加载它。

您可以在以下位置查看更多详细信息: https ://postgrest.org/en/v6.0/admin.html#schema-reloading 。

还要检查本节末尾的重要说明(绿色): https ://postgrest.org/en/v6.0/api.html#stored-procedures


推荐阅读