Postgresql

無法在 macOS 上連接 psql

  • March 13, 2022

安裝

$ brew install postgresql
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/postgresql-12.1.mojave.bottle.tar.gz
Already downloaded: /Users/user/Library/Caches/Homebrew/downloads/525a3637cd6f7b7a7e0bfe5adb102483ae01f4be31269aaf4348f6f4291f8a86--postgresql-12.1.mojave.bottle.tar.gz
==> Pouring postgresql-12.1.mojave.bottle.tar.gz
==> /usr/local/Cellar/postgresql/12.1/bin/initdb --locale=C -E UTF-8 /usr/local/var/postgres
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
 brew postgresql-upgrade-database

To have launchd start postgresql now and restart at login:
 brew services start postgresql
Or, if you don't want/need a background service you can just run:
 pg_ctl -D /usr/local/var/postgres start
==> Summary
🍺  /usr/local/Cellar/postgresql/12.1: 3,217 files, 37.3MB

檢查狀態

$ brew services list
postgresql     started user /Users/user/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

連接

$ psql
psql: error: could not connect to server: FATAL:  database "user" does not exist
$ psql -U postgres
psql: error: could not connect to server: FATAL:  database "postgres" does not exist

它已經初始化了數據庫,為什麼postgres不存在呢?

本指南效果很好:

https://gist.github.com/ibraheem4/ce5ccd3e4d7a65589ce84f2a3b7c23a3

有必要手動創建數據庫和角色,因為它們不存在。

我在 macOS monterey 上為自製 postgresql 14 找到的唯一解決方案是:

   brew services stop postgresql
   cd /opt/homebrew/var/postgres
   rm -rf /opt/homebrew/var/postgres/*
   initdb -U `whoami` .
   brew services start postgresql
   psql template1

引用自:https://dba.stackexchange.com/questions/256255