How to solve connection error on postgresql database however postgresql seems started

On my favourite database client it’s opening a pop notification saying “could not connect to server: Connection refused Is the server running on host “localhost” (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host “localhost” (127.0.0.1) and accepting TCP/IP connections on port 5432?”

At the beginning of all check the postgresql log file with command below;

tail -f /opt/homebrew/var/log/postgres.log

If output contains something like below;

FATAL: database "port=5432" does not exist

Firstly check if the service is running properly with command below;

brew services list

If the output of command contains something like below

postgresql@14 stopped ~/Library/LaunchAgents/homebrew.mxcl.postgresq1@14.plist

This problem generally occurs in these situations below;

1. If cause of an unexpected interruption such power failure etc. happened and postgresql so database system is closed/interrupted unexpectedly,

2. If postgresql lastly somehow started with a wrong user and the process is not responding to requests because of permission problems.

3. Database upgrade process needs to be started manually after major version upgrade from brew upgrade.

If the problem is one of those 1, and 2 above;

Execute the command below in your command line;

postgres -D /opt/homebrew/var/postgres

If the output of command contains something like below you do not need to do anything additionally, because the recovery would be done automatically thanks to the command above;

LOG: database system is ready to accept connections

If the output of command does not end like above then you should kill the process with referred process id;

So you should execute command below;

kill -9 {$processID}

And then restart the service with command below;

brew services restart postgresql

That’s all.