检查输入参数并引发异常

Check Input Parameter And Raise Exception

最近我一直在使用一些显然有效的功能。 我想添加一些功能,例如:“如果函数输入参数是一个字符串,它会引发异常,说些什么”。我该怎么做?

 /*
 PLpgSQL function which behaves to aggregate the MIN(col)
 */
CREATE OR REPLACE FUNCTION searchMinimumValue (real,real) RETURNS real AS $$
DECLARE 
BEGIN
 IF  IS NULL OR  >=  THEN
    RETURN ;
 ELSE
    RETURN ;
 END IF;
 END;
 $$ LANGUAGE plpgsql;

 /*
Function which given the minimum value returned from the previous function,
adds the Laplacian noise.
Our upper bound is computed by doubling the epsilon value and then adding our minimum value found by the previous function.
The returned value from the function below will be the Laplace distribution value added to the output from the previous function.
 */
CREATE OR REPLACE FUNCTION addLaplacianNoiseMinimum(real) RETURNS real AS $$
DECLARE
  epsilon real := 1.2;
  sensivity real := (epsilon * 2) + ;
  laplaceDistribution real;
BEGIN
  laplaceDistribution := sensivity / (epsilon);
  RETURN   + laplaceDistribution;
END;
$$ LANGUAGE plpgsql;

CREATE AGGREGATE minimumLaplaceValue (real)
(
  sfunc = searchMinimumValue,
  stype = real,
  finalfunc = addLaplacianNoiseMinimum
); 

正如我之前所说,我想输入如下内容: 如果 $1 不是数字,则引发异常 'WRONG TYPE INPUT PARAMETER'

我认为你不能用 Postgres 做到这一点——或者你不能在没有一些不必要的副作用的情况下做到这一点。

Postgres 是严格的类型系统 - 所以所有类型的工作都应该由 Postgres 完成。

但是您可以为某些类型的参数集重载函数:

CREATE OR REPLACE FUNCTION public.f1(numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return ;
end;
$function$

CREATE OR REPLACE FUNCTION public.f1(text)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
begin
  raise exception 'only numeric type is supported';
end;
$function$

postgres=# select f1(10);
+----+
| f1 |
+----+
| 10 |
+----+
(1 row)

postgres=# select f1('ahoj');
ERROR:  only numeric type is supported
CONTEXT:  PL/pgSQL function f1(text) line 3 at RAISE

但我强烈不建议使用这种模式。重载是狂野的枪 - 可以是好朋友也可以是坏朋友,并且应该只在需要时使用它并且可以做一些工作 - 它不应该仅仅用于引发异常。这是 postgres 类型系统的工作——它做得更好(尽管有不同的,也许在第一眼看来是奇怪的错误消息)。