pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Joel Jacobson <joel@compiler.org>
To: pgsql-general@postgresql.org
Subject: Raise exception without using plpgsql?
Date: Thu, 17 Dec 2020 15:32:09 +0100
Message-ID: <7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com> (raw)

Hi,

Is there a way to raise an exception with a message,
without having to add your own plpgsql helper-function?

Currently this is what I have:

CREATE OR REPLACE FUNCTION raise(message text, debug json, dummy_return_value anyelement)
RETURNS anyelement
LANGUAGE plpgsql
AS $$
BEGIN
RAISE '% %', message, debug;
END;
$$;

The dummy value allows using the function in a context where a value of the given type is expected.

Here is a mockup example on the coding pattern where I typically would use this raise() helper-function:

SELECT
  CASE
    WHEN foo = 0 THEN f0(bar)::baz
    WHEN foo = 1 THEN f1(bar)::baz
    WHEN foo = 2 THEN f2(bar)::baz
    ELSE raise('Not implemented',json_build_object(
    'foo',foo,
    'bar',bar
    ),NULL::baz)
  END
FROM ...

The idea is to throw an exception when a case is not handled, instead of just letting the CASE produce a NULL value.

The dummy_return_value anyelement with the same type as the other CASEs is necessary, otherwise, if trying to just return anyelement without the dummy_return_value you would get error:

DETAIL:  A result of type anyelement requires at least one input of type anyelement, anyarray, anynonarray, anyenum, or anyrange.

Is there any idiomatic way of achieving the same, without having to rely on a plpgsql function in this way?

Best regards,

Joel

view thread (4+ messages)  latest in thread

Message-ID: <7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com>
Permalink:  ../7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com/
Also on:    postgresql.org/message-id/7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: joel@compiler.org
  Subject: Re: Raise exception without using plpgsql?
  In-Reply-To: <7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com>
  References: <7479ca12-af3c-44c3-9ddd-a2074eb82a12@www.fastmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox