妙传节点的Postgres到PLPGSQL函数数组 [英] Pass array from node-postgres to plpgsql function

查看:404
本文介绍了妙传节点的Postgres到PLPGSQL函数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该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;

节点,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);
});

从节点服务器输出:

Output from node server:

错误:错误:数组值必须以{或维度信息搜索
  结果:未定义

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的解析阵列的问题这个计算器上的问题在节点的Postgres参数化数组:

I read about the Postgres parse-array issue and this stackoverflow question on parameterised arrays in node-postgres:

  • node-postgres: how to execute "WHERE col IN (<dynamic value list>)" query?

但答案似乎并不存在。

推荐答案

参数必须是下列形式之一:

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) 直接。


  • 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:

  • Normalize array subscripts for 1-dimensional array so they start with 1

两者 array_length() array_upper()需要的两个的参数。第二个是数组维 - 1 你的情况

Both array_length() and array_upper() require two parameters. The second is the array dimension - 1 in your case.

这篇关于妙传节点的Postgres到PLPGSQL函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆