PostgreSQL中函数参数的约束条件
问题描述:
对函数参数进行约束的最佳做法是什么?
类似于一个检查对数函数内部的检查负数: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
答
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"