亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 pg-promise 執行接受參數數組的 Postgresql 函數

使用 pg-promise 執行接受參數數組的 Postgresql 函數

絕地無雙 2022-05-22 11:30:35
我們有這個 postgresql 類型:create type order_input as (    item text,    quantity integer);而這個 postgresql 函數:create or replace function insert_into_orders(order_input[])returns void language plpgsql as $$declare     inserted_id integer;begin    insert into public.orders(orderdate)     values (now())     returning orderid into inserted_id;    insert into public.orderdetails(orderid, item, quantity)    select inserted_id, item, quantity    from unnest($1);end $$;要在 pgadmin-4 中執行,我們運行:select insert_into_orders(    array[        ('Red Widget', 10),         ('Blue Widget', 5)    ]::order_input[]);我試圖弄清楚如何使用 pg-promise javascript 庫執行 insert_into_orders 函數。我嘗試過執行以下操作:const pgp = require("pg-promise")();const db = pgp(connectionObj);await db.func("insert_into_orders", [{item:"Red Widget", quantity:10}, {item:"Blue Widget", quantity:5}]但收到以下消息:{  "error": {    "message": "malformed array literal: \"{\"item\":\"Red Widget\", \"quantity\":10}\""  }}如果有人知道我必須如何為 pg-promise 構建我的輸入,我將不勝感激
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

方法func需要一個值數組作為第二個參數。在您的情況下,它必須是一個參數 - 對象數組。但是您改為給它 2 個參數,每個參數都是一個對象,因此會出現錯誤。


正確的方法是:


const orderInput = [{item:"Red Widget", quantity:10}, {item:"Blue Widget", quantity:5}];


await db.func('insert_into_orders', [orderInput]);

無論如何,您應該使用事件查詢或pg-monitor來查看生成了什么 SQL。


另外,您insert_into_orders應該是一個存儲過程,然后至少通過proc執行。但是,它的實現看起來應該只是代碼中的一個事務。


執行此操作后,錯誤返回為"error": {"message": "function insert_into_orders(text[]) does not exist"}


那是因為類型不匹配,這需要類型轉換......


您可以通過常規查詢方法調用該函數,也可以使用自定義類型格式來修改數據格式:


const data = {

    toPostgres: () => `${pgp.as.array(orderInput)}::json[]::order_input[]`,

    rawType: true

};

然后將其傳入:


await db.func('insert_into_orders', [data]);


查看完整回答
反對 回復 2022-05-22
  • 1 回答
  • 0 關注
  • 80 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號