What to do when you realize brew has updated posgresql all of a sudden

Problem:

start postgresql as usual

 

pg_ctl -w -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Output :

 

waiting for server to start.... stopped waiting
pg_ctl: could not start server
Examine the log output. 

Open the log file to identify the problem

vi /usr/local/var/log/server.log 

Log file error 

 

FATAL:  database files are incompatible with server
DETAIL:  The data directory was initialized by PostgreSQL version 9.5, which is not compatible with this version 9.6.2.

Solution:

Execute the following commands to solve the problem. According to the error above the 

oldversion : 9.5.3

(Although they say 9.5 in the error the actual version was 9.5.3. Check this with ls )

newversion: 9.6.2

(but note that once you run the "brew upgrade postgresql" command the new version might chnage ex: 9.6.2 ->9.6.3)

 

$ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

$ mv /usr/local/var/postgres /usr/local/var/<oldversion>

$ brew update

$ brew upgrade postgresql

$ initdb /usr/local/var/postgres -E utf8

$ pg_upgrade -b /usr/local/Cellar/postgresql/<oldversion>/bin -B /usr/local/Cellar/postgresql/<newversion>/bin  -d /usr/local/var/<oldversion> -D/usr/local/var/postgres

$ cp /usr/local/Cellar/postgresql/<newversion>/homebrew.mxcl.postgresql.plist~/Library/LaunchAgents/

$ pg_ctl -w  -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

$ rm -rf /usr/local/var/<oldversion>

Problem solved