Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep comments inside a view definition with PostgreSQL?

I need to keep the comments I add inside a SQL query when I create views from complex queries, in order to come back to views definition more easily. Within pgAdminIII, when I create a view and then consult the view definition, the comments are deleted and indentation completely revised... Is there a way to change this behaviour?

View creation:

CREATE OR REPLACE VIEW public.v_test AS 

-- Count number of null lines within table 'test'
(SELECT * FROM public.test WHERE client IS NULL);

View definition after creation, as displayed in pgAdminIII:

-- View: v_test

-- DROP VIEW v_test;

CREATE OR REPLACE VIEW v_test AS 
 SELECT test.gid,
    test.client
   FROM test
  WHERE test.client IS NULL;

ALTER TABLE v_test
  OWNER TO postgres;

Thanks for help!

like image 870
wiltomap Avatar asked Jun 06 '17 14:06

wiltomap


2 Answers

No, Postgres saves views as parse trees, so it does not remember whitespace or comments.

However, if you really need it, functions can remember comments.

like image 126
Joseph Lee Avatar answered Oct 20 '22 23:10

Joseph Lee


Postgres doesn't store a view definition as is, hence you cannot store comments this way. Use the comment command:

create view my_view as select 1;
comment on view my_view is 'It is my view';

select obj_description('my_view'::regclass);

 obj_description 
-----------------
 It is my view
(1 row)

You can see the comment in PgAdmin3:

-- View: public.my_view

-- DROP VIEW public.my_view;

CREATE OR REPLACE VIEW public.my_view AS 
 SELECT 1;

ALTER TABLE public.my_view
  OWNER TO postgres;
COMMENT ON VIEW public.my_view
  IS 'it is my view';
like image 27
klin Avatar answered Oct 21 '22 00:10

klin