【问题标题】:How do I use Returning and Commit in Postgres so I can get a committed recordset?如何在 Postgres 中使用 Returning 和 Commit,以便获得已提交的记录集?
【发布时间】:2013-01-31 21:17:04
【问题描述】:

我正在使用 postgres 构建一个 FIFO 队列,并根据 apinstein 对Job queue as SQL table with multiple consumers (PostgreSQL)的回答进行回答

问题是,如果我使用事务,那么语句看起来像:

    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;

然后我的返回值被丢弃。如果我在没有开始/提交的情况下运行相同的语句,则记录集返回正常。

显然我更喜欢交易;没有它,该语句甚至可能不安全。那么如何返回我提交的记录集呢?

编辑 我正在标记答案,因为它让我走上了正确的道路,但这是我最终得到的功能:

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')

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可以创建一个返回所需值的函数。每个函数都作为事务执行。 不要放置“开始;”和“承诺”;在函数体内。我相信下面的功能应该可以工作。

    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(); 返回一列,而 select * from set_in_progress(); 返回包含所有列的表。
    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 2011-03-24
    • 2021-04-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2012-10-15
    • 2021-11-11
    相关资源
    最近更新 更多