Postgres user is lack of superuser privilege

Sometimes, you can loose a superuser privilege and when you try to grant it, you receive an error of lack of privileges.

If you have access to other user which has the role, then you may just grant the role using the credentials, but what if you lost it or accidentaly removed.

The workaround is as following:

Connect to the server and switch to postgres OS user.

su - postgres

Export env variable for your postgres instance

export PGHOME=<PATH_TO_PG_HOME_DIR>
export PGDATA=<PATH_TO_DATA_DIRECTORY>

Stop the instance

$PGHOME/bin/pg_ctl -D $PGDATA stop

Open backend session to the cluster

$PGHOME/bin/postgres --single -D $PGDATA

Add superuser role to the postgres or any other user you need

ALTER USER postgres SUPERUSER;

Exit backend session

Ctrl+D -- to exit

Start the cluster

$PGHOME/bin/pg_ctl -D $PGDATA start

Check the user has the superuser role

$PGHOME/bin/psql -U postgres
\du;