1

動作するが恐ろしく遅いストアド プロシージャがあります。

基本的に私がやりたいことは、単一の更新コマンドでサブクエリから取得した一連の行を更新することです。もう 1 つの注意点は、ステートメントで更新した行を返したいということです。

現在、ループを使用して単一の行を取得して更新し、returning を使用して結果を保存していますが、これは機能しますが、非常に遅いです。

提案?

以下は、現在の作業バージョンとスキーマ作成ステートメントです。

CREATE TABLE "queued_message"
(
  id bigserial NOT NULL,
  body json NOT NULL,
  status character varying(50) NOT NULL,
  queue character varying(150) NOT NULL,
  last_modified timestamp without time zone NOT NULL,
  CONSTRAINT id_pkey PRIMARY KEY (id)
);

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_notification_message_batch(desiredQueue character varying(150), numberOfItems integer) 
    RETURNS SETOF returned_message AS $$ 
    DECLARE result returned_message; messageCount integer := 1;
    BEGIN
    lock table queued_notification_message in exclusive mode;
    LOOP 
        update queued_notification_message
        set 
            status='IN_PROGRESS', last_modified=now()
        where
            id in (
            select
                id
            from
                queued_notification_message
            where
                status='SUBMITTED' and queue=desiredQueue
            limit 1
            )
        returning * into result;
        RETURN NEXT result; 
        messageCount := messageCount+1;
        EXIT WHEN messageCount > numberOfItems;
    END LOOP;   
END;$$LANGUAGE plpgsql;
4

1 に答える 1

0

UPDATE ステートメントの LIMIT 句がサポートされていないため、コードを高速化するのは困難です。おそらく次の例で十分です。

関数の作成または置換 public.fx2(n integer)
 SETOF oo を返します
 言語plpgsql
AS $関数$
始める
  戻りクエリ更新 oo セット a = b
                 どこで b in (選択 b
                                から
                               bで並べる
                               n) を制限する
                 *を返します。
  戻る;
終わり;
$関数$

postgres=# insert into oo select 1, i from generate_series(1,100) g(i);
挿入 0 100
postgres=# select * from fx2(1);
 | | b
---+---
 1 | 1
(1行)

postgres=# select * from fx2(4);
 | | b
---+---
 1 | 1
 2 | 2
 3 | 3
 4 | 4
(4行)

postgres=# select * from oo limit 10;
 | | b  
---+----
 1 | 5
 1 | 6
 1 | 7
 1 | 8
 1 | 9
 1 | 10
 1 | 11
 1 | 12
 1 | 13
 1 | 14
(10行)
于 2013-07-02T06:10:35.050 に答える