|
1 | 1 | --Inspired by https://hakibenita.com/future-proof-sql |
2 | 2 |
|
3 | 3 | --TODO: добавить ещё параметры, см. https://postgrespro.ru/docs/postgresql/14/plpgsql-errors-and-messages |
4 | | - |
5 | 4 | create or replace function raise_exception( |
6 | 5 | value anyelement, |
7 | 6 | message text default 'Unhandled value', |
8 | | - detail text default '', |
| 7 | + detail text default null, |
9 | 8 | hint text default 'See value in detail as JSON', |
10 | 9 | errcode text default 'raise_exception' |
11 | 10 | ) |
12 | 11 | returns boolean |
13 | 12 | immutable |
14 | | - returns null onnull input |
| 13 | + --strict -- returns null if any parameter is null |
15 | 14 | parallel safe |
16 | 15 | language plpgsql |
17 | 16 | set search_path = '' |
18 | 17 | as |
19 | 18 | $$ |
20 | 19 | begin |
21 | 20 | raise exception using |
22 | | - message = message, |
23 | | - detail = case when detail = '' |
24 | | - then to_json(value)::text |
25 | | - else detail |
26 | | - end, |
27 | | - hint = hint, |
28 | | - errcode = errcode; |
| 21 | + message = coalesce(message, 'Unhandled value'), |
| 22 | + detail = coalesce(detail, coalesce(to_json(value), 'null'::json)::text), |
| 23 | + hint = coalesce(hint, 'See value in detail as JSON'), |
| 24 | + errcode = coalesce(errcode, 'raise_exception'); |
29 | 25 | end; |
30 | 26 | $$; |
31 | 27 |
|
32 | 28 | --TEST |
33 | | - |
| 29 | +--select raise_exception(null::int); |
34 | 30 | --select raise_exception(1234567890); |
35 | 31 | --select raise_exception('ABCDE'::text); |
36 | 32 | --select raise_exception(json_build_object('id', 123)); |
37 | 33 | --select raise_exception('1d2h3m4s'::interval); |
| 34 | +--select raise_exception(now()); |
38 | 35 |
|
39 | 36 | /* |
40 | 37 | --explain |
|
0 commit comments