postgresql database delete all comments

**

postgresql database delete all comments

**

I often encounter special situations in my work. This time I met the requirement to delete all the comments in the database (table comments and column comments)
. It is too troublesome to delete one by one. We can delete comments
in batches. In the Oracle database, you can use user_col_comments Delete comments

select 'comment on column '||t.table_name||'.'||t.column_name||' is '''';' from user_col_comments t; 

But there is no similar table in postgresql database, but we can also achieve this function through statements.
Postgresql database has pg_class and pg_namespace tables

pg_class records tables and almost everything that has columns or looks like tables. This includes indexes (but also see pg_index), sequences (pg_sequence
), views, materialized views, composite types and TOAST tables, see relkind.

pg_namespace stores the name space. Namespace is a structure under SQL mode: each namespace has an
independent collection of tables, types, etc., and there is no name conflict in it

For details, please refer to pg_class https://blog.csdn.net/pg_hgdb/article/details/79455123?utm_source=copy
pg_namespace

Through these two tables we can realize the function of the user_col_comments table in Oracle
**

1. Delete the comment of the table

**
First we need to determine our needs: schema name, table name, comment and then spliced ​​into a statement

SELECT
	n.nspname,
	relname AS tabname,
	obj_description ( relfilenode, 'pg_class' ) AS COMMENT,
	concat_ws ( '', 'COMMENT ON TABLE "', nspname, '"."', relname, '" is '''';' ) 
FROM
	pg_class
	C LEFT JOIN pg_catalog.pg_namespace n ON n.oid = C.relnamespace 
WHERE
	relkind = 'r' 
	AND obj_description ( relfilenode, 'pg_class' ) IS NOT NULL;

Blurred due to company secretsBlurred due to company secrets

nspname  --表所在的模式
tabname --表名
comment  --表注释
concat_ws --要执行的语句

**

2. Delete the comment of the column

**The
idea is the same as the table, so I won’t talk about it here

SELECT
	nspname,
	b.TABLE_NAME,
	A.attname,
	col_description ( A.attrelid, A.attnum ) AS COMMENT,
	concat_ws ( '', 'COMMENT ON COLUMN ', nspname, '.', b.TABLE_NAME, '.', A.attname, ' is '''';' ) 
FROM
	pg_catalog.pg_attribute A,
	(
	SELECT C
		.oid,
		C.relname AS TABLE_NAME,
		n.nspname 
	FROM
		pg_catalog.pg_class
		C LEFT JOIN pg_catalog.pg_namespace n ON n.oid = C.relnamespace 
	WHERE
		C.relkind = 'r' 
	) b 
WHERE
	A.attrelid = b.oid 
	AND A.attnum > 0 
	AND NOT A.attisdropped 
	AND col_description ( A.attrelid, A.attnum ) IS NOT NULL 
ORDER BY
	b.TABLE_NAME,
	A.attnum;

Insert picture description here
3. Execute the statement.
With the delete statement, you can copy, paste and execute the statement. If there are too many tables, you can write a function to execute automatically...

Guess you like

Origin blog.csdn.net/yang_z_1/article/details/111358111