sql - 检查输入参数并引发异常

标签 sql postgresql plpgsql

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

 /*
 PLpgSQL function which behaves to aggregate the MIN(col)
 */
CREATE OR REPLACE FUNCTION searchMinimumValue (real,real) RETURNS real AS $$
DECLARE 
BEGIN
 IF $1 IS NULL OR $1 >= $2 THEN
    RETURN $2;
 ELSE
    RETURN $1;
 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) + $1;
  laplaceDistribution real;
BEGIN
  laplaceDistribution := sensivity / (epsilon);
  RETURN  $1 + laplaceDistribution;
END;
$$ LANGUAGE plpgsql;

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

正如我之前所说,我想输入如下内容: 如果 $1 不是数字,则引发异常“错误类型的输入参数”

最佳答案

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

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

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

CREATE OR REPLACE FUNCTION public.f1(numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return $1;
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

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

关于sql - 检查输入参数并引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881185/

相关文章:

php - 奇怪的 SQL 错误 - 无法打印

mysql - 为什么哪里条件不对?

postgresql - Tsquery返回完全匹配的关键字

sql - Postgresql:从存储过程返回临时表

sql - 使用另一个查询的输出动态执行查询

php - Symfony2/Doctrine2 : Don't drop fulltext index on schema:update

mysql - 第一个非假值

node.js - 使用 Bookshelf 补丁为未引用的列设置默认值

postgresql - 匿名和清理数据库表中字段的最快方法?

sql - postgresql 断言约束