Postgresql 如何在Postgres中使用Returning和Commit,以便获得提交的记录集?
我正在使用postgres和基于apinstein答案的答案构建一个FIFO队列 问题是,如果我使用一个事务,那么语句看起来像:Postgresql 如何在Postgres中使用Returning和Commit,以便获得提交的记录集?,postgresql,Postgresql,我正在使用postgres和基于apinstein答案的答案构建一个FIFO队列 问题是,如果我使用一个事务,那么语句看起来像: begin; lock table queued_message in exclusive mode; update queued_message set status='IN_PROGRESS' where id in ( select id from
begin;
lock table queued_message in exclusive mode;
update
queued_message
set
status='IN_PROGRESS'
where
id in (
select
id
from
queued_message
where
status='SUBMITTED' and queue='BACKFILL_REQUEST'
order by
id asc
limit 1
)
returning *;
commit;
然后我的返回值被丢弃。如果我在没有begin/commit的情况下运行相同的语句,记录集将返回罚款
显然,我更喜欢交易;没有它,这份声明甚至可能不安全。那么,如何返回已提交的记录集
编辑
我正在标记答案,因为它让我走上了正确的轨道,但以下是我最终得到的功能:
CREATE TYPE returned_message as (id bigint, body json, status character varying(50) , queue character varying(150), last_modified timestamp without time zone)
CREATE OR REPLACE FUNCTION get_next_message(desiredQueue character varying(150))
RETURNS returned_message AS $$
DECLARE result returned_message;
BEGIN
lock table queued_message in exclusive mode;
update queued_message
set
status='IN_PROGRESS'
where
id in (
select
id
from
queued_message
where
status='SUBMITTED' and queue=desiredQueue
order by
id asc
limit 1
)
returning * into result;
RETURN result;
END;$$LANGUAGE plpgsql;
select * from get_next_message('BACKFILL_REQUEST')
您可以创建一个返回所需值的函数。每个函数都作为事务执行。 不要在函数体中放置“开始”和“提交”。我相信下面的功能应该可以工作
create or replace function set_in_progress()
returns setof queued_message
language sql as $$
lock table queued_message in exclusive mode;
update
queued_message
set
status='IN_PROGRESS'
where
id in (
select
id
from
queued_message
where
status='SUBMITTED' and queue='BACKFILL_REQUEST'
order by
id asc
limit 1
)
returning *;
$$;
select * from set_in_progress();
根据我提供的脚本,您是否有一个如何执行此操作的示例?我并不是一个postgres专家,函数创建和返回类型对我来说似乎很重要。这仍然返回一个列,其中包含所有信息。我需要返回一个实际行,以便JDBC可以将其作为记录集进行解析。
select set_in_progress()
返回一列,而从set_in_progress()中选择*代码>返回包含所有列的表。