LoginSignup
21
26

More than 5 years have passed since last update.

PostgreSQL チートシート

Last updated at Posted at 2013-08-28

MacのローカルでPostgreSQLを開発用に使うときの覚書

環境

  • Mac OSX El Capitan

インストール

$ brew install postgresql
$ mkdir -p ~/Library/LaunchAgents
$ ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

起動/終了

psqlを再起動する

brew upgradeしたあとなどに

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

PostgreSQLのバージョンを確認する

psql template1
SELECT version();

psqlを終了する

\q

ユーザ(role)

ユーザ(role)を追加する

対話的にユーザを追加する

$ createuser --interactive
Enter name of role to add: yourusername
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) n

パスワード付きでsuperuser権限のあるユーザを追加する

$ createuser --superuser --pwprompt USERNAME

ユーザのパスワードを設定する

psql -c "alter role USERNAME with password 'PASSWORD';" template1

ユーザにsuperuser権限を付与する

psql -c 'alter role USERNAME with superuser;' template1

ユーザの一覧を表示する

psql template1
select usename from pg_user;

あるいは

psql -c'select usename from pg_user;' template1

データベース

データベースの一覧を表示する

psql -l

データベースを作成する

createdb --owner=ユーザ名 データベース名

データベースに接続する

psql -d データベース名

テーブルの一覧を表示する

\d

データベースを削除する

dropdb データベース名

データベースをバックアップする(テキストダンプ)

pg_dump データベース名 > バックアップファイル名

バックアップしたファイルからリストアする(テキストダンプ)

createdb --owner=ロール名 リストア先のデータベース名
psql リストア先のデータベース名 < バックアップファイル名

データベースをバックアップする(custom)

  • backup_2013-09-10_0.custom のようなファイル名にしておくとあとでわかりやすい
pg_dump --format=custom データベース名 > バックアップファイル名

バックアップしたファイルからリストアする(custom)

  • -d で指定するDB名は必ず postgres にする
pg_restore -C -d postgres < バックアップファイル名

バックアップしたファイルからリストアする(customでリストア先のDBが異なる場合)

pg_restore -d リストア先のデータベース名 < バックアップファイル名

参考

21
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
26