arrays - 如何将复合类型的数组从 nodejs 传递到 postgresql 函数?

标签 arrays node.js postgresql

我有一个 postgres 函数:

CREATE OR REPLACE FUNCTION add_new_views(VARIADIC all_view event_view[])
  RETURNS void AS
$BODY$
DECLARE
    view event_view;
BEGIN
    FOREACH view IN ARRAY all_view LOOP 
        INSERT INTO t_event_views VALUES (view.event_id, view.device_code);
    END LOOP;
END;
$BODY$

event_view - 这是我的复合类型:

CREATE TYPE event_view (event_id uuid, device_code text);

我可以像这样通过 pgAdmin 使用我的函数:

SELECT add_new_views(VARIADIC ARRAY [
    ('b9d78fc3-b55a-452e-b935-8ce4f1e79284', 'asd')::event_view,
    ('b9d78fc3-b55a-452e-b935-8ce4f1e79284', 'asd')::event_view
]);

但我需要从 nodejs 调用它。要连接 postgresql,我使用 node-postgres 'pg'模块。

我发送这个请求:

query = 'SELECT add_new_views(VARIADIC [$1])';
current_client.query(query, allViews, function(err ,res) {
    if(err) console.log(err);
    console.log(res)
})

allViews - 数组如下所示:

[ [ '(b9d78fc3-b55a-452e-b935-8ce4f1e79284)', '(CHUPERM)' ],
  [ '(b9d78fc3-b55a-452e-b935-8ce4f1e79284)', '(HUE)' ],
  [ '(b9d78fc3-b55a-452e-b935-8ce4f1e79284)', '(HU)' ],
  [ '(00ae9a6c-781f-48d1-ab42-bfa87d09bdbb)', '(HITE)' ],
  [ '(00ae9a6c-781f-48d1-ab42-bfa87d09bdbb)', '(HIJFIRM)' ],
  [ '(00ae9a6c-781f-48d1-ab42-bfa87d09bdbb)', '(DVERMNYEZAPILI)' ],
  [ '(00ae9a6c-781f-48d1-ab42-bfa87d09bdbb)', '(TICHTOMENYANEVIDISH)' ],
  [ '(00ae9a6c-781f-48d1-ab42-bfa87d09bdbb)', '(HITEBEAD)' ] ]

作为回应,我得到:

{ [error: malformed record literal: "(b9d78fc3-b55a-452e-b935-8ce4f1e79284)"]
  name: 'error',
  length: 133,
  severity: 'ERROR',
  code: '22P02',
  detail: 'Too few columns.',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'rowtypes.c',
  line: '183',
  routine: 'record_in' }

如果从元素 allView 数组中删除括号,我会收到错误“等待括号”。 当我尝试传递给 postgres 简单的一维数组时,一切正常(我更改了 postgre 函数中需要的所有内容)。但是对于这个复合类型数组我什么也做不了。请帮忙。抱歉我的英语不好。

最佳答案

答案可能晚了,但解决了这个问题。 node-postgres 的正确语法要求是:

[
   '(b9d78fc3-b55a-452e-b935-8ce4f1e79284, CHUPERM)',
   '(b9d78fc3-b55a-452e-b935-8ce4f1e79284, HUE)',
    ...
]

需要一维数组中行的字符串表示,而不是二维数组。

关于arrays - 如何将复合类型的数组从 nodejs 传递到 postgresql 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610059/

相关文章:

javascript - 如何将来自 2 个不同输入的值推送到像这样的数组集中 ["one", 2]

node.js - child_process.fork 和 cluster.fork 之间的有效区别是什么?

node.js - Node 使用 child_process 启动 VLC Player

c# - 设计多个表使用相同模型的 SQL 数据库

c - 程序先绕过fgets

javascript - 如何获得最长的相等字符序列,如果超过一个,则有多少个?

javascript - 在 Docker 容器内运行命令 'node filename.js'

postgresql - 试图从 postgresql\o -o 命令定位输出文件

bash - postgres 不允许 less 砍长线

java - 如何获取没有设定长度的数组的特定组成部分?