@@ -178,7 +178,27 @@ data with the non-superuser. Only creating the views will leave out the most
178178important bits of data.
179179
180180``` sql
181- CREATE USER postgres_exporter PASSWORD ' password' ;
181+ -- To use IF statements, hence to be able to check if the user exists before
182+ -- attempting creation, we need to switch to procedural SQL (PL/pgSQL)
183+ -- instead of standard SQL.
184+ -- More: https://www.postgresql.org/docs/9.3/plpgsql-overview.html
185+ -- To preserve compatibility with <9.0, DO blocks are not used; instead,
186+ -- a function is created and dropped.
187+ CREATE OR REPLACE FUNCTION __tmp_create_user () returns void as $$
188+ BEGIN
189+ IF NOT EXISTS (
190+ SELECT -- SELECT list can stay empty for this
191+ FROM pg_catalog .pg_user
192+ WHERE usename = ' postgres_exporter' ) THEN
193+ CREATE USER postgres_exporter ;
194+ END IF;
195+ END;
196+ $$ language plpgsql;
197+
198+ SELECT __tmp_create_user();
199+ DROP FUNCTION __tmp_create_user();
200+
201+ ALTER USER postgres_exporter WITH PASSWORD ' password' ;
182202ALTER USER postgres_exporter SET SEARCH_PATH TO postgres_exporter,pg_catalog;
183203
184204-- If deploying as non-superuser (for example in AWS RDS), uncomment the GRANT
@@ -187,7 +207,7 @@ ALTER USER postgres_exporter SET SEARCH_PATH TO postgres_exporter,pg_catalog;
187207CREATE SCHEMA IF NOT EXISTS postgres_exporter;
188208GRANT USAGE ON SCHEMA postgres_exporter TO postgres_exporter;
189209
190- CREATE FUNCTION get_pg_stat_activity () RETURNS SETOF pg_stat_activity AS
210+ CREATE OR REPLACE FUNCTION get_pg_stat_activity () RETURNS SETOF pg_stat_activity AS
191211$$ SELECT * FROM pg_catalog .pg_stat_activity ; $$
192212LANGUAGE sql
193213VOLATILE
0 commit comments