gpt4 book ai didi

arrays - 将数组从 node-postgres 传递到 plpgsql 函数

转载 作者:行者123 更新时间:2023-11-29 12:14:06 24 4
gpt4 key购买 nike

plpgsql函数:

CREATE OR REPLACE FUNCTION testarray (int[]) returns int as $$
DECLARE
len int;
BEGIN
len := array_upper($1);
return len;
END
$$ language plpgsql;

node-postgres 查询 + 测试数组:

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[]) 返回相同的错误。

我将函数参数更改为 (anyarray int) 并且输出错误更改为:

err: error: invalid input syntax for integer: "1,2,3,4,5"
result: undefined

以及其他一些变体。

我寻找不产生错误并返回 5 的变体。

我读到了 Postgres parse-array issue以及关于 node-postgres 中参数化数组的这个 stackoverflow 问题:

但似乎没有答案。

最佳答案

参数必须采用以下形式之一:

'{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

另外,你可以简化你的函数:

CREATE OR REPLACE FUNCTION testarray (int[])
RETURNS int AS
$func$
BEGIN
RETURN array_length($1, 1);
END
$func$ LANGUAGE plpgsql IMMUTABLE;

或者一个简单的 SQL 函数:

CREATE OR REPLACE FUNCTION testarray2 (int[])
RETURNS int AS 'SELECT array_length($1, 1)' LANGUAGE sql IMMUTABLE;

或者只使用 array_length($1, 1)直接。

关于arrays - 将数组从 node-postgres 传递到 plpgsql 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com