Restart stuck PostgreSQL on macOS

While connecting to PostgreSQL, you might get the following error.

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

This usually means that PostgreSQL is not running, but sometimes it might get stuck, and you will get the error even if it is running.

How to fix

Delete the following file.

rm /usr/local/var/postgres/

Then restart PostgreSQL, and it should work.

# with postgres
pg_ctl -D /usr/local/var/postgres restart

# with brew
brew services restart postgresql