处理PostgreSQL异常的优雅方法? [英] Elegant way of handling PostgreSQL exceptions?

查看:138
本文介绍了处理PostgreSQL异常的优雅方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PostgreSQL中,我想创建一个安全包装机制,如果发生异常,该机制将返回空结果.请考虑以下内容:

In PostgreSQL, I would like to create a safe-wrapping mechanism which returns empty result if an exception occurs. Consider the following:

SELECT * FROM myschema.mytable;

我可以在客户端应用程序中进行安全包装:

I could do the safe-wrapping in the client application:

try {
    result = execute_query('SELECT value FROM myschema.mytable').fetchall();
}
catch(pg_exception) {
    result = []
}

但是我可以直接在SQL中做这样的事情吗?我想使以下代码正常工作,但似乎应该将其放入DO $$ ... $$块中,在这里我迷路了.

But could I do such a thing in SQL directly? I would like to make the following code work, but it seems like it should by put into DO $$ ... $$ block and here I'm getting lost.

BEGIN
    SELECT * FROM myschema.mytable;
EXCEPTION WHEN others THEN
    SELECT unnest(ARRAY[]::TEXT[])
END

推荐答案

PL/pgSQL中的异常处理

通常,plpgsql代码总是包装在BEGIN .. END块中.那可以在DO语句或函数的主体内.块可以嵌套在内部-但它们不能在外部存在,请不要将其与普通SQL混淆.

Exception handling in PL/pgSQL

Generally, plpgsql code is always wrapped into a BEGIN .. END block. That can be inside the body of a DO statement or a function. Blocks can be nested inside - but they cannot exist outside, don't confuse this with plain SQL.

每个BEGIN块都可以选择包含EXCEPTION子句来处理异常,但是需要捕获异常的函数的开销要大得多,因此最好避免先验的异常.

Each BEGIN block can optionally include an EXCEPTION clause for handling exceptions, but functions that need to trap exceptions are considerably more expensive, so it's best to avoid exceptions a priori.

更多信息:

示例: 在SO上搜索相关答案

DO 语句无法返回任何内容. 创建一个带表的功能 和模式名称作为参数,并返回您想要的任何内容:

A DO statement can't return anything. Create a function that takes table and schema name as parameters and returns whatever you want:

CREATE OR REPLACE FUNCTION f_tbl_value(_tbl text, _schema text = 'public')
  RETURNS TABLE (value text) AS
$func$
DECLARE
   _t regclass := to_regclass(_schema || '.' || _tbl);
BEGIN
   IF _t IS NULL THEN
      value := ''; RETURN NEXT;    -- return single empty string
   ELSE
      RETURN QUERY EXECUTE
      'SELECT value FROM ' || _t;  -- return set of values
   END
$func$ LANGUAGE plpgsql;

致电:

SELECT * FROM f_tbl_value('my_table');

或者:

SELECT * FROM f_tbl_value('my_table', 'my_schema');

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆