所以我正在一个项目中,该项目需要我的查询在一个事务中插入一个主表及其明细表(将作为列表发送到数据库中),以便在有一个主表及其明细表时回滚插入功能失败。
假设我有这些表格:
CREATE TABLE transaction(
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id BIGINT FOREIGN KEY NOT NULL,
total_item INT NOT NULL DEFAULT 0,
total_purchase BIGINT NOT NULL DEFAULT 0
)
CREATE TABLE transaction_detail(
id BIGSERIAL PRIMARY KEY NOT NULL,
transaction_id BIGINT FOREIGN KEY NOT NULL,
product_id BIGINT FOREIGN KEY NOT NULL,
product_price INT NOT NULL DEFAULT 0,
purchase_amount INT NOT NULL DEFAULT 0
)
我有这个功能:
CREATE OR REPLACE FUNCTION create_transaction(order JSONB, product_list JSONB)
功能参数:
order : An object which will be inserted into the transaction table
product_list : List of Product object which will be inserted into the transaction_detail table
我当前的查询看起来像这样:
CREATE OR REPLACE FUNCTION insert_order(tx JSONB, product_list JSONB)
RETURNS BIGINT
AS $$
WITH result AS (
INSERT INTO transaction(
user_id,
total_item,
total_purchase,
) VALUES (
(tx ->> 'user_id') :: BIGINT,
(tx ->> 'total_item') :: INT,
(tx ->> 'total_purchase') :: INT,
)
RETURNING id AS transaction_id
)
FOR row IN product_list LOOP
INSERT INTO transaction_detail(
transaction_id,
product_id,
product_price,
purchase_amount,
) VALUES (
transaction_id,
(row ->> 'product_id') :: BIGINT,
(row ->> 'product_price') :: INT,
(row ->> 'purchase_amount') :: INT,
)
END LOOP;
$$ LANGUAGE SQL SECURITY DEFINER;
JSON文件:
[
"user_id" : "1",
"total_item" : "2",
"total_purchase" : "2000",
]
[
{
"product_id" : "1",
"product_price" : "500",
"purchase_amount" : "2"
},
{
"product_id" : "2",
"product_price" : "1000",
"purchase_amount" : "1"
}
]
我知道我的查询出了点问题,尽管我对此没办法。 任何指针都将不胜感激。
答案 0 :(得分:0)
假设以product_list
传递的数据是一个数组,则可以执行以下操作:
CREATE OR REPLACE FUNCTION insert_order(p_order JSONB, p_product_list JSONB)
RETURNS BIGINT
AS $$
WITH result AS (
INSERT INTO "transaction"(
user_id,
total_item,
total_purchase
) VALUES (
(p_order ->> 'user_id') :: BIGINT,
(p_order ->> 'total_item') :: INT,
(p_order ->> 'total_purchase') :: INT
)
RETURNING id AS transaction_id
), details as (
INSERT INTO transaction_detail(
transaction_id,
product_id,
product_price,
purchase_amount
)
select r.transaction_id,
(pl.data ->> 'product_id')::bigint,
(pl.data ->> 'product_price')::int,
(pl.data ->> 'purchase_amount')::int
from result r,
jsonb_array_elements(p_product_list) as pl(data)
)
select transaction_id
from result;
$$
LANGUAGE SQL SECURITY DEFINER;
我重命名了参数,以避免名称与保留关键字冲突。通过为参数名称加上前缀,还可以避免名称与列或表名冲突。 order
是保留关键字,仅在引用时才可以使用,例如"order"
。 transaction
是关键字,但不是保留关键字,但最好还是用引号引起来。
在交易详细信息中插入的内容需要是INSERT...SELECT
中的result
,以获取生成的交易ID,并取消嵌套产品列表JSON值中的数组元素。
CTE的最终选择将返回生成的交易ID。
您可以这样调用函数:
select insert_order('{"user_id": 42, "total_item": 1, "total_purchase": 100}'::jsonb,
'[ {"product_id": 1, "product_price": 10, "purchase_amount": 1},
{"product_id": 2, "product_price": 20, "purchase_amount": 2},
{"product_id": 3, "product_price": 30, "purchase_amount": 3} ]'::jsonb);