-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathtable_description.sql
50 lines (43 loc) · 1.35 KB
/
table_description.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
create or replace function public.table_description(
table_name regclass,
new_description text default null
)
returns text
volatile --COMMENT is not allowed in a non-volatile function
--returns null on null input
parallel safe -- Postgres 10 or later
language plpgsql
set search_path = ''
as
$$
declare
rec record;
query text not null default 'comment on table %I.%I is %L';
begin
if table_name is null then
return null;
elsif new_description is null then
return obj_description(table_name, 'pg_class');
end if;
SELECT ns.nspname as table_schema, c.relname as table_name
INTO rec
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS ns ON c.relnamespace = ns.oid
WHERE c.oid = table_name;
query := format(query, rec.table_schema, rec.table_name, new_description);
--raise notice '%', query;
execute query;
return new_description;
end;
$$;
comment on function public.table_description is 'Get or set table description, like COMMENT ON TABLE command, but it can set description dynamically';
--TEST
do $$
begin
create schema if not exists test;
create table test.d();
assert public.table_description('test.d'::regclass) is null; --GET
assert public.table_description('test.d'::regclass, 'table''d') = 'table''d'; --SET
drop table test.d;
end
$$;