2017-10-12 102 views
1

對函數參數進行約束的最佳做法是什麼?
類似於一個檢查對數函數內部的檢查負數:PostgreSQL中函數參數的約束條件

SELECT log(-1, 1) 

拋出錯誤:

[2201E] ERROR: cannot take logarithm of a negative number 

到目前爲止,我發現了一個辦法做到這一點使用PL/pgSQL的函數體內部,但它對我來說不是一個好的解決方案。
有沒有辦法在函數聲明中進行約束?
我希望看到這樣的事情:(此代碼不起作用)

CREATE OR REPLACE FUNCTION public.logloss(y_true BOOL NOTNULL, y_pred FLOAT NOTNULL) 

或者,也許(這不工作,以及)

CASE WHEN __condition__ RAISE EXCEPTION 
    ELSE __function__body 
END 

回答

2

So far I found a way to do it using PL/pgSQL inside a function body but it doesn't look like a good solution for me.

我個人不知道這種方法可能會出錯。它非常簡單明瞭,例如

create or replace function test_1(arg integer) 
returns integer language plpgsql as $$ 
begin 
    if arg < 0 then 
     raise exception 'The argument cannot be negative.'; 
    end if; 
    return arg; 
end $$; 

select test_1(-1); 

ERROR: The argument cannot be negative. 

沒有內置的功能來自動檢查函數的參數。但是,你有另一種選擇。您可以爲參數定義domains,例如:

create domain non_negative_integer as integer 
check (value >= 0); 

create or replace function test_2(arg non_negative_integer) 
returns integer language plpgsql as $$ 
begin 
    return arg; 
end $$; 

select test_2(-1); 

ERROR: value for domain non_negative_integer violates check constraint "non_negative_integer_check"