我试图在 postgres 12 DB 中调用一个存储函数,它接受 1 个 json 类型的参数并返回 json 类型的结果。
函数是这样的:
CREATE OR REPLACE FUNCTION public.get_users(
data json,
OUT result json)
RETURNS json
LANGUAGE 'plv8'
COST 100
VOLATILE
AS $BODY$const dataJson = JSON.parse(data);
const arg_id = dataJson.id;
const arg_token = dataJson.token;
const arg_ids = dataJson.ids.join(",");
result = {};
const getAuthUserResult = plv8.execute( 'SELECT id, token, deleted FROM public.users WHERE id = $1', [arg_id]);
const authUser = getAuthUserResult[0];
switch (true) {
case getAuthUserResult.length === 0: {
result.code = "ERR_SENDER_NOTFOUND";
break;
}
case authUser.token !== arg_token: {
result.code = "ERR_SENDER_INVALIDTOKEN";
break;
}
case authUser.deleted !== 0: {
result.code = "ERR_SENDER_DELETED";
break;
}
default: {
result.code = "OK"
}
}
if (result.code === "OK") {
result.users = plv8.execute( 'SELECT $1 FROM public.users WHERE id IN ($2)', ["name", arg_id]);
}
$BODY$;
ALTER FUNCTION public.get_users(json)
OWNER TO postgres;
该函数必须采用带有键的json:“id” - 用于请求发送者的ID,“token” - 用于它的秘密和“targets” - 用于目标用户的ID,如下所示:
{
"id": 448,
"token": "someToken",
"targets": [449, 450, 451]
}
但是当我尝试通过 SQL 查询调用该函数时:
SELECT * FROM get_users('{"id":448,"token":"someToken","targets":[449,450,451]}');
我收到一个错误:
ERROR: SyntaxError: Unexpected token o in JSON at position 1
CONTEXT: undefined() LINE 0: [object Object]
SQL state: XX000
我已经仔细检查了 json,它似乎是有效的。还有很多资源提供了这种使用 json 类型参数调用函数的方式。我这样做的方式有什么问题?