将数组从 node-postgres 传递给 plpgsql 函数 [英] Pass array from node-postgres to plpgsql function
问题描述
plpgsql 函数:
The plpgsql function:
CREATE OR REPLACE FUNCTION testarray (int[]) returns int as $$
DECLARE
len int;
BEGIN
len := array_upper($1);
return len;
END
$$ language plpgsql;
node-postgres 查询 + 测试数组:
The node-postgres query + test array:
var ta = [1,2,3,4,5];
client.query('SELECT testarray($1)', [ta], function(err, result) {
console.log('err: ' + err);
console.log('result: ' + result);
});
节点服务器的输出:
错误:错误:数组值必须以{"或维度信息开头
结果:未定义
err: error: array value must start with "{" or dimension information
result: undefined
我还尝试在客户端查询中转换参数,如 testarray($1::int[])
返回相同的错误.
I also tried cast the parameter in the client query like testarray($1::int[])
which returned the same error.
我将函数参数更改为 (anyarray int)
并且输出错误发生了变化:
I changed the function argument to (anyarray int)
and the output error changed:
错误:错误:整数的无效输入语法:1,2,3,4,5"
结果:未定义
err: error: invalid input syntax for integer: "1,2,3,4,5"
result: undefined
以及其他几个变体.
我寻找不会产生错误并返回 5 的变体.
I seek the variation that produces no error and returns 5.
我阅读了 Postgres 解析数组问题 和这个 stackoverflow 问题在 node-postgres 中的参数化数组上:
I read about the Postgres parse-array issue and this stackoverflow question on parameterised arrays in node-postgres:
但答案似乎并不存在.
推荐答案
参数必须是以下形式之一:
The parameter has to be in one of these forms:
'{1,2,3,4,5}' -- array literal
'{1,2,3,4,5}'::int[] -- array literal with explicit cast
ARRAY[1,2,3,4,5] -- array constructor
此外,您还可以简化您的功能:
Also, you can simplify your function:
CREATE OR REPLACE FUNCTION testarray (int[])
RETURNS int AS
$func$
BEGIN
RETURN array_length($1, 1);
END
$func$ LANGUAGE plpgsql IMMUTABLE;
或者一个简单的SQL函数:
Or a simple SQL function:
CREATE OR REPLACE FUNCTION testarray2 (int[])
RETURNS int AS 'SELECT array_length($1, 1)' LANGUAGE sql IMMUTABLE;
或者只是使用 array_length($1, 1)
直接.
Or just use array_length($1, 1)
directly.
array_upper()
是错误的函数.数组可以有任意的下标.array_length()
可以满足您的需求.相关问题:
array_upper()
is the wrong function. Arrays can have arbitrary subscripts.array_length()
does what you are looking for. Related question:
array_length()
和 array_upper()
都需要 两个 参数.第二个是数组维度 - 1
在你的情况下.
Both array_length()
and array_upper()
require two parameters. The second is the array dimension - 1
in your case.
这篇关于将数组从 node-postgres 传递给 plpgsql 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!