From 1c14eb964a23c83ab5538196e024bc1ee355031e Mon Sep 17 00:00:00 2001 From: Sakis Date: Thu, 11 Jul 2019 15:50:03 +0200 Subject: [PATCH] README: SQL that supports re-execution Make the SQL work in automated deployments where it will be repeated many times. --- README.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2488fc1..666b638 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,27 @@ data with the non-superuser. Only creating the views will leave out the most important bits of data. ```sql -CREATE USER postgres_exporter PASSWORD 'password'; +-- To use IF statements, hence to be able to check if the user exists before +-- attempting creation, we need to switch to procedural SQL (PL/pgSQL) +-- instead of standard SQL. +-- More: https://www.postgresql.org/docs/9.3/plpgsql-overview.html +-- To preserve compatibility with <9.0, DO blocks are not used; instead, +-- a function is created and dropped. +CREATE OR REPLACE FUNCTION __tmp_create_user() returns void as $$ +BEGIN + IF NOT EXISTS ( + SELECT -- SELECT list can stay empty for this + FROM pg_catalog.pg_user + WHERE usename = 'postgres_exporter') THEN + CREATE USER postgres_exporter; + END IF; +END; +$$ language plpgsql; + +SELECT __tmp_create_user(); +DROP FUNCTION __tmp_create_user(); + +ALTER USER postgres_exporter WITH PASSWORD 'password'; ALTER USER postgres_exporter SET SEARCH_PATH TO postgres_exporter,pg_catalog; -- 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; CREATE SCHEMA IF NOT EXISTS postgres_exporter; GRANT USAGE ON SCHEMA postgres_exporter TO postgres_exporter; -CREATE FUNCTION get_pg_stat_activity() RETURNS SETOF pg_stat_activity AS +CREATE OR REPLACE FUNCTION get_pg_stat_activity() RETURNS SETOF pg_stat_activity AS $$ SELECT * FROM pg_catalog.pg_stat_activity; $$ LANGUAGE sql VOLATILE