diadia

興味があることをやってみる。自分のメモを残しておきます。

postgresqlをmacosにbrewでインストールする場合について

Brewでインストールする場合

https://docs.djangoproject.com/ja/2.2/ref/contrib/gis/install/#homebrew
下記の方法でpostgresqlをインストールすることができる。

brew install postgresql
#$ brew install postgis
#$ brew install gdal
#$ brew install libgeoip

なお、インストールしたままpsqlコマンドを叩くと、

psql: could not connect to server: No such file or directory
	Is the server running locally and accepting
	connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

となる。brewでインストールしたものは別途postgresqlサーバーを起動させなければならない。

インストールすると以下のコメントが表示される。

To have launchd start postgresql@12 now and restart at login: brew services start postgresql@12 Or, if you don't want/need a background service you can just run: pg_ctl -D /usr/local/var/postgres@12 start

brew services startコマンドかpg_ctl コマンドでpostgresqlサーバーを起動させることをアナウンスしてくれる。

pg_ctl -D /usr/local/var/postgres start

pg_ctlでサーバーを起動させる方法はデーモンモードで起動させる事ができるようだ。

postgres -D /usr/local/var/postgres

こちらの方法もあるようだ。https://qiita.com/mochizukikotaro/items/84204d5c46b67c9b74f4

brewを使ってインストールする場合には、インストールしたソフトウエアの環境変数をセットする必要があることがわかった。今までpythonを使った場合、pipでインストールしたソフトウエアのパスを書く必要がなかった?けど、全てがそのようなことではないらしい。brew installした場合にはbash_profileに記述すべき要素がインストールした時点で表示されるのでそれを利用すると楽に環境構築できる。

https://morphocode.com/how-to-install-postgis-on-mac-os-x/

改定版

ここからはpostgisをどのようにインストールするかについてのメモを書く。

参考:
https://docs.djangoproject.com/ja/2.2/ref/contrib/gis/install/#homebrew
https://medium.com/@Umesh_Kafle/postgresql-and-postgis-installation-in-mac-os-87fa98a6814d

まずbrewをインストールする。次にbrewを使ってpostgresql, postgis, gdal, libgeoipをインストールする。それができたらpostgresqlのサービスを開始する。そしてinitdbコマンドを実行する。しかしながらうまく実行できないのでまず、ディレクトリを削除してもう一度initdbを実行する。つぎにcreatedbコマンドを実行し、データベースを作成する。データベースを作成するcreatedbコマンドは、サービスがスタートされていないと実行できないので注意すること。
crearedbコマンドで作成したDBに次にpsqlコマンドで接続する。接続したDBにてCREATE EXTENSION postgis;コマンドを実行する。

brew install postgres   
brew install postgis
brew install gdal
brew install libgeoip

#postgresqlサーバーを開始させる
pg_ctl -D /usr/local/var/postgres start

#データベースクラスターを生成する
initdb /usr/local/var/postgres

#コマンド実行後以下のエラーが出る可能性がある
initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".

#この場合にはデータベースクラスターを削除し再度生成する
rm -r /usr/local/var/postgres
initdb /usr/local/var/postgres

#エラーが出ない場合データベースをcreatedbコマンドで作成する
createdb postgis_test

#データベースに接続する
psql postgis_test

#DBに接続した状態でCREATE EXTENSION postgis; コマンドを実行する
CREATE EXTENSION postgis;

#CREATE EXTENSION postgis;コマンドが成功したか確認
SELECT PostGIS_Version();




    

補足; brew install postgres@12みたいなことをやっても、psqlコマンドは使えない事がわかった。 psqlコマンドを使うには必ず通常版のpostgresをインストールすること。そのうえでバージョン指定したpostgresをインストールする手順を踏む。