1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PostgreSQLでテーブルやビューの一覧を得て1行づつ処理したい

Last updated at Posted at 2020-02-04

テーブルとビューの一覧を得る

current_schema() はしばしば 'public' だと思いますが、適宜置き換えてください。

テーブルの一覧を得る(見るだけなら \dt でもよい)

SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type='BASE TABLE';

ビューの一覧を得る

SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'VIEW';
-- もしくは
SELECT table_name FROM information_schema.views WHERE table_catalog = current_database() AND table_schema = current_schema();

テーブルとビューの一覧を得る

SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type IN ('BASE TABLE', 'VIEW');

追記: 最初はtabale_typeを無視していたが、BASE TABLEとVIEWだけではないので、ちゃんと設定したほうが良さそう。 refs: 第37章 情報スキーマ - PostgreSQL 11.5文書

おまけ:テーブルorビューの定義を見る(SELECTするカラム名を覗きたいとき)

\d テーブル名

テーブル名やビュー名を1行づつ処理したい

psql-A -tオプションをつけると、パイプで繋いでコマンドで処理できます。雑に権限つけたいときなど。

DATABASE=データベース名
ROLENAME=ロール名
psql -U postgres -d $DATABASE -A -t -c "SELECT table_name FROM information_schema.tables WHERE table_schema='public'" \
  | xargs -I{} psql -U postgres -d $DATABASE -c "GRANT ALL ON {} TO $ROLENAME"
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?