如何在psql函数中包含隔离级别

时间:2019-04-20 11:02:01

标签: postgresql stored-procedures isolation-level

    CREATE OR REPLACE FUNCTION createNewOrder(userID text,currency text,orderAmount integer,price integer,isSell boolean,fast boolean) RETURNS integer AS $$
    DECLARE 
    asset record;
    newBalance integer;
    pairKey text;
    begin SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ write;
    --get user asset :
    select into asset getUserAssetEntity(userID);
    --check if asset not found :
    if not found then 
    rollback;
    return 101;
    end if;

    pairKey= asset.currency+"_payable" ;
    --check if asset is enoughf : 
    if pairKey >= orderAmount then 
    --create order  
    insert into public.order (pair,amount,price,remain,cdate,sell,cancel,fast,traderid,isactive,status)
    values (currency,orderAmount,price,orderAmount,NOW(),isSell,false,userID,true,"alive");

    --calculate new Balance :

    newBalance=asset.asset.pairKey - orderAmount;

    --update user asset :
    update public.asset set asset.pairKey = newBalance where id=asset.id;

    commit;
    return 103;

    else 
    rollback;
    return 102;
    end if;

    END; $$ 
    LANGUAGE 'plpgsql';

我尝试在函数中使用隔离级别,它返回此错误:

  

错误:任何查询之前都必须调用SET TRANSACTION ISOLATION LEVEL

1 个答案:

答案 0 :(得分:0)

首先,您不能在postgresql中的函数内包含commit或rollback命令,您可以在版本11中的过程中进行操作。

@a_horse_with_no_name的意思是,在事务中调用该函数之前必须指出隔离级别

例如:

 begin SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ write;
 select  your_function_createNewOrder(...);
 commit;--rollback

致谢